viewer.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define("BabylonViewer", [], factory);
  6. else if(typeof exports === 'object')
  7. exports["BabylonViewer"] = factory();
  8. else
  9. root["BabylonViewer"] = factory();
  10. })(this, function() {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, {
  50. /******/ configurable: false,
  51. /******/ enumerable: true,
  52. /******/ get: getter
  53. /******/ });
  54. /******/ }
  55. /******/ };
  56. /******/
  57. /******/ // getDefaultExport function for compatibility with non-harmony modules
  58. /******/ __webpack_require__.n = function(module) {
  59. /******/ var getter = module && module.__esModule ?
  60. /******/ function getDefault() { return module['default']; } :
  61. /******/ function getModuleExports() { return module; };
  62. /******/ __webpack_require__.d(getter, 'a', getter);
  63. /******/ return getter;
  64. /******/ };
  65. /******/
  66. /******/ // Object.prototype.hasOwnProperty.call
  67. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  68. /******/
  69. /******/ // __webpack_public_path__
  70. /******/ __webpack_require__.p = "";
  71. /******/
  72. /******/ // Load entry module and return exports
  73. /******/ return __webpack_require__(__webpack_require__.s = 14);
  74. /******/ })
  75. /************************************************************************/
  76. /******/ ([
  77. /* 0 */
  78. /***/ (function(module, exports, __webpack_require__) {
  79. /* WEBPACK VAR INJECTION */(function(global) {var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  80. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  81. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  82. 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;
  83. return c > 3 && r && Object.defineProperty(target, key, r), r;
  84. };
  85. var __extends = (this && this.__extends) || (function () {
  86. var extendStatics = Object.setPrototypeOf ||
  87. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  88. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  89. return function (d, b) {
  90. extendStatics(d, b);
  91. function __() { this.constructor = d; }
  92. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  93. };
  94. })();
  95. //# sourceMappingURL=babylon.types.js.map
  96. var BABYLON;
  97. (function (BABYLON) {
  98. var KeyboardEventTypes = /** @class */ (function () {
  99. function KeyboardEventTypes() {
  100. }
  101. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  102. get: function () {
  103. return KeyboardEventTypes._KEYDOWN;
  104. },
  105. enumerable: true,
  106. configurable: true
  107. });
  108. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  109. get: function () {
  110. return KeyboardEventTypes._KEYUP;
  111. },
  112. enumerable: true,
  113. configurable: true
  114. });
  115. KeyboardEventTypes._KEYDOWN = 0x01;
  116. KeyboardEventTypes._KEYUP = 0x02;
  117. return KeyboardEventTypes;
  118. }());
  119. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  120. var KeyboardInfo = /** @class */ (function () {
  121. function KeyboardInfo(type, event) {
  122. this.type = type;
  123. this.event = event;
  124. }
  125. return KeyboardInfo;
  126. }());
  127. BABYLON.KeyboardInfo = KeyboardInfo;
  128. /**
  129. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  130. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  131. */
  132. var KeyboardInfoPre = /** @class */ (function (_super) {
  133. __extends(KeyboardInfoPre, _super);
  134. function KeyboardInfoPre(type, event) {
  135. var _this = _super.call(this, type, event) || this;
  136. _this.skipOnPointerObservable = false;
  137. return _this;
  138. }
  139. return KeyboardInfoPre;
  140. }(KeyboardInfo));
  141. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  142. })(BABYLON || (BABYLON = {}));
  143. //# sourceMappingURL=babylon.keyboardEvents.js.map
  144. var BABYLON;
  145. (function (BABYLON) {
  146. var PointerEventTypes = /** @class */ (function () {
  147. function PointerEventTypes() {
  148. }
  149. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  150. get: function () {
  151. return PointerEventTypes._POINTERDOWN;
  152. },
  153. enumerable: true,
  154. configurable: true
  155. });
  156. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  157. get: function () {
  158. return PointerEventTypes._POINTERUP;
  159. },
  160. enumerable: true,
  161. configurable: true
  162. });
  163. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  164. get: function () {
  165. return PointerEventTypes._POINTERMOVE;
  166. },
  167. enumerable: true,
  168. configurable: true
  169. });
  170. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  171. get: function () {
  172. return PointerEventTypes._POINTERWHEEL;
  173. },
  174. enumerable: true,
  175. configurable: true
  176. });
  177. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  178. get: function () {
  179. return PointerEventTypes._POINTERPICK;
  180. },
  181. enumerable: true,
  182. configurable: true
  183. });
  184. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  185. get: function () {
  186. return PointerEventTypes._POINTERTAP;
  187. },
  188. enumerable: true,
  189. configurable: true
  190. });
  191. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  192. get: function () {
  193. return PointerEventTypes._POINTERDOUBLETAP;
  194. },
  195. enumerable: true,
  196. configurable: true
  197. });
  198. PointerEventTypes._POINTERDOWN = 0x01;
  199. PointerEventTypes._POINTERUP = 0x02;
  200. PointerEventTypes._POINTERMOVE = 0x04;
  201. PointerEventTypes._POINTERWHEEL = 0x08;
  202. PointerEventTypes._POINTERPICK = 0x10;
  203. PointerEventTypes._POINTERTAP = 0x20;
  204. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  205. return PointerEventTypes;
  206. }());
  207. BABYLON.PointerEventTypes = PointerEventTypes;
  208. var PointerInfoBase = /** @class */ (function () {
  209. function PointerInfoBase(type, event) {
  210. this.type = type;
  211. this.event = event;
  212. }
  213. return PointerInfoBase;
  214. }());
  215. BABYLON.PointerInfoBase = PointerInfoBase;
  216. /**
  217. * This class is used to store pointer related info for the onPrePointerObservable event.
  218. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  219. */
  220. var PointerInfoPre = /** @class */ (function (_super) {
  221. __extends(PointerInfoPre, _super);
  222. function PointerInfoPre(type, event, localX, localY) {
  223. var _this = _super.call(this, type, event) || this;
  224. _this.skipOnPointerObservable = false;
  225. _this.localPosition = new BABYLON.Vector2(localX, localY);
  226. return _this;
  227. }
  228. return PointerInfoPre;
  229. }(PointerInfoBase));
  230. BABYLON.PointerInfoPre = PointerInfoPre;
  231. /**
  232. * This type contains all the data related to a pointer event in Babylon.js.
  233. * 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.
  234. */
  235. var PointerInfo = /** @class */ (function (_super) {
  236. __extends(PointerInfo, _super);
  237. function PointerInfo(type, event, pickInfo) {
  238. var _this = _super.call(this, type, event) || this;
  239. _this.pickInfo = pickInfo;
  240. return _this;
  241. }
  242. return PointerInfo;
  243. }(PointerInfoBase));
  244. BABYLON.PointerInfo = PointerInfo;
  245. })(BABYLON || (BABYLON = {}));
  246. //# sourceMappingURL=babylon.pointerEvents.js.map
  247. var BABYLON;
  248. (function (BABYLON) {
  249. BABYLON.ToGammaSpace = 1 / 2.2;
  250. BABYLON.ToLinearSpace = 2.2;
  251. BABYLON.Epsilon = 0.001;
  252. var Color3 = /** @class */ (function () {
  253. /**
  254. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  255. */
  256. function Color3(r, g, b) {
  257. if (r === void 0) { r = 0; }
  258. if (g === void 0) { g = 0; }
  259. if (b === void 0) { b = 0; }
  260. this.r = r;
  261. this.g = g;
  262. this.b = b;
  263. }
  264. /**
  265. * Returns a string with the Color3 current values.
  266. */
  267. Color3.prototype.toString = function () {
  268. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  269. };
  270. /**
  271. * Returns the string "Color3".
  272. */
  273. Color3.prototype.getClassName = function () {
  274. return "Color3";
  275. };
  276. /**
  277. * Returns the Color3 hash code.
  278. */
  279. Color3.prototype.getHashCode = function () {
  280. var hash = this.r || 0;
  281. hash = (hash * 397) ^ (this.g || 0);
  282. hash = (hash * 397) ^ (this.b || 0);
  283. return hash;
  284. };
  285. // Operators
  286. /**
  287. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  288. * Returns the Color3.
  289. */
  290. Color3.prototype.toArray = function (array, index) {
  291. if (index === undefined) {
  292. index = 0;
  293. }
  294. array[index] = this.r;
  295. array[index + 1] = this.g;
  296. array[index + 2] = this.b;
  297. return this;
  298. };
  299. /**
  300. * Returns a new Color4 object from the current Color3 and the passed alpha.
  301. */
  302. Color3.prototype.toColor4 = function (alpha) {
  303. if (alpha === void 0) { alpha = 1; }
  304. return new Color4(this.r, this.g, this.b, alpha);
  305. };
  306. /**
  307. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  308. */
  309. Color3.prototype.asArray = function () {
  310. var result = new Array();
  311. this.toArray(result, 0);
  312. return result;
  313. };
  314. /**
  315. * Returns the luminance value (float).
  316. */
  317. Color3.prototype.toLuminance = function () {
  318. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  319. };
  320. /**
  321. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  322. * Returns this new object.
  323. */
  324. Color3.prototype.multiply = function (otherColor) {
  325. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  326. };
  327. /**
  328. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  329. * Returns the current Color3.
  330. */
  331. Color3.prototype.multiplyToRef = function (otherColor, result) {
  332. result.r = this.r * otherColor.r;
  333. result.g = this.g * otherColor.g;
  334. result.b = this.b * otherColor.b;
  335. return this;
  336. };
  337. /**
  338. * Boolean : True if the rgb values are equal to the passed ones.
  339. */
  340. Color3.prototype.equals = function (otherColor) {
  341. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  342. };
  343. /**
  344. * Boolean : True if the rgb values are equal to the passed ones.
  345. */
  346. Color3.prototype.equalsFloats = function (r, g, b) {
  347. return this.r === r && this.g === g && this.b === b;
  348. };
  349. /**
  350. * Multiplies in place each rgb value by scale.
  351. * Returns the updated Color3.
  352. */
  353. Color3.prototype.scale = function (scale) {
  354. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  355. };
  356. /**
  357. * Multiplies the rgb values by scale and stores the result into "result".
  358. * Returns the unmodified current Color3.
  359. */
  360. Color3.prototype.scaleToRef = function (scale, result) {
  361. result.r = this.r * scale;
  362. result.g = this.g * scale;
  363. result.b = this.b * scale;
  364. return this;
  365. };
  366. /**
  367. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  368. */
  369. Color3.prototype.add = function (otherColor) {
  370. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  371. };
  372. /**
  373. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  374. * Returns the unmodified current Color3.
  375. */
  376. Color3.prototype.addToRef = function (otherColor, result) {
  377. result.r = this.r + otherColor.r;
  378. result.g = this.g + otherColor.g;
  379. result.b = this.b + otherColor.b;
  380. return this;
  381. };
  382. /**
  383. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  384. */
  385. Color3.prototype.subtract = function (otherColor) {
  386. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  387. };
  388. /**
  389. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  390. * Returns the unmodified current Color3.
  391. */
  392. Color3.prototype.subtractToRef = function (otherColor, result) {
  393. result.r = this.r - otherColor.r;
  394. result.g = this.g - otherColor.g;
  395. result.b = this.b - otherColor.b;
  396. return this;
  397. };
  398. /**
  399. * Returns a new Color3 copied the current one.
  400. */
  401. Color3.prototype.clone = function () {
  402. return new Color3(this.r, this.g, this.b);
  403. };
  404. /**
  405. * Copies the rgb values from the source in the current Color3.
  406. * Returns the updated Color3.
  407. */
  408. Color3.prototype.copyFrom = function (source) {
  409. this.r = source.r;
  410. this.g = source.g;
  411. this.b = source.b;
  412. return this;
  413. };
  414. /**
  415. * Updates the Color3 rgb values from the passed floats.
  416. * Returns the Color3.
  417. */
  418. Color3.prototype.copyFromFloats = function (r, g, b) {
  419. this.r = r;
  420. this.g = g;
  421. this.b = b;
  422. return this;
  423. };
  424. /**
  425. * Updates the Color3 rgb values from the passed floats.
  426. * Returns the Color3.
  427. */
  428. Color3.prototype.set = function (r, g, b) {
  429. return this.copyFromFloats(r, g, b);
  430. };
  431. /**
  432. * Returns the Color3 hexadecimal code as a string.
  433. */
  434. Color3.prototype.toHexString = function () {
  435. var intR = (this.r * 255) | 0;
  436. var intG = (this.g * 255) | 0;
  437. var intB = (this.b * 255) | 0;
  438. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  439. };
  440. /**
  441. * Returns a new Color3 converted to linear space.
  442. */
  443. Color3.prototype.toLinearSpace = function () {
  444. var convertedColor = new Color3();
  445. this.toLinearSpaceToRef(convertedColor);
  446. return convertedColor;
  447. };
  448. /**
  449. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  450. * Returns the unmodified Color3.
  451. */
  452. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  453. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  454. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  455. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  456. return this;
  457. };
  458. /**
  459. * Returns a new Color3 converted to gamma space.
  460. */
  461. Color3.prototype.toGammaSpace = function () {
  462. var convertedColor = new Color3();
  463. this.toGammaSpaceToRef(convertedColor);
  464. return convertedColor;
  465. };
  466. /**
  467. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  468. * Returns the unmodified Color3.
  469. */
  470. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  471. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  472. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  473. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  474. return this;
  475. };
  476. // Statics
  477. /**
  478. * Creates a new Color3 from the string containing valid hexadecimal values.
  479. */
  480. Color3.FromHexString = function (hex) {
  481. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  482. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  483. return new Color3(0, 0, 0);
  484. }
  485. var r = parseInt(hex.substring(1, 3), 16);
  486. var g = parseInt(hex.substring(3, 5), 16);
  487. var b = parseInt(hex.substring(5, 7), 16);
  488. return Color3.FromInts(r, g, b);
  489. };
  490. /**
  491. * Creates a new Vector3 from the startind index of the passed array.
  492. */
  493. Color3.FromArray = function (array, offset) {
  494. if (offset === void 0) { offset = 0; }
  495. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  496. };
  497. /**
  498. * Creates a new Color3 from integer values ( < 256).
  499. */
  500. Color3.FromInts = function (r, g, b) {
  501. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  502. };
  503. /**
  504. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  505. */
  506. Color3.Lerp = function (start, end, amount) {
  507. var r = start.r + ((end.r - start.r) * amount);
  508. var g = start.g + ((end.g - start.g) * amount);
  509. var b = start.b + ((end.b - start.b) * amount);
  510. return new Color3(r, g, b);
  511. };
  512. Color3.Red = function () { return new Color3(1, 0, 0); };
  513. Color3.Green = function () { return new Color3(0, 1, 0); };
  514. Color3.Blue = function () { return new Color3(0, 0, 1); };
  515. Color3.Black = function () { return new Color3(0, 0, 0); };
  516. Color3.White = function () { return new Color3(1, 1, 1); };
  517. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  518. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  519. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  520. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  521. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  522. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  523. return Color3;
  524. }());
  525. BABYLON.Color3 = Color3;
  526. var Color4 = /** @class */ (function () {
  527. /**
  528. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  529. */
  530. function Color4(r, g, b, a) {
  531. if (r === void 0) { r = 0; }
  532. if (g === void 0) { g = 0; }
  533. if (b === void 0) { b = 0; }
  534. if (a === void 0) { a = 1; }
  535. this.r = r;
  536. this.g = g;
  537. this.b = b;
  538. this.a = a;
  539. }
  540. // Operators
  541. /**
  542. * Adds in place the passed Color4 values to the current Color4.
  543. * Returns the updated Color4.
  544. */
  545. Color4.prototype.addInPlace = function (right) {
  546. this.r += right.r;
  547. this.g += right.g;
  548. this.b += right.b;
  549. this.a += right.a;
  550. return this;
  551. };
  552. /**
  553. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  554. */
  555. Color4.prototype.asArray = function () {
  556. var result = new Array();
  557. this.toArray(result, 0);
  558. return result;
  559. };
  560. /**
  561. * Stores from the starting index in the passed array the Color4 successive values.
  562. * Returns the Color4.
  563. */
  564. Color4.prototype.toArray = function (array, index) {
  565. if (index === undefined) {
  566. index = 0;
  567. }
  568. array[index] = this.r;
  569. array[index + 1] = this.g;
  570. array[index + 2] = this.b;
  571. array[index + 3] = this.a;
  572. return this;
  573. };
  574. /**
  575. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  576. */
  577. Color4.prototype.add = function (right) {
  578. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  579. };
  580. /**
  581. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  582. */
  583. Color4.prototype.subtract = function (right) {
  584. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  585. };
  586. /**
  587. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  588. * Returns the Color4.
  589. */
  590. Color4.prototype.subtractToRef = function (right, result) {
  591. result.r = this.r - right.r;
  592. result.g = this.g - right.g;
  593. result.b = this.b - right.b;
  594. result.a = this.a - right.a;
  595. return this;
  596. };
  597. /**
  598. * Creates a new Color4 with the current Color4 values multiplied by scale.
  599. */
  600. Color4.prototype.scale = function (scale) {
  601. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  602. };
  603. /**
  604. * Multiplies the current Color4 values by scale and stores the result in "result".
  605. * Returns the Color4.
  606. */
  607. Color4.prototype.scaleToRef = function (scale, result) {
  608. result.r = this.r * scale;
  609. result.g = this.g * scale;
  610. result.b = this.b * scale;
  611. result.a = this.a * scale;
  612. return this;
  613. };
  614. /**
  615. * Multipy an RGBA Color4 value by another and return a new Color4 object
  616. * @param color The Color4 (RGBA) value to multiply by
  617. * @returns A new Color4.
  618. */
  619. Color4.prototype.multiply = function (color) {
  620. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  621. };
  622. /**
  623. * Multipy an RGBA Color4 value by another and push the result in a reference value
  624. * @param color The Color4 (RGBA) value to multiply by
  625. * @param result The Color4 (RGBA) to fill the result in
  626. * @returns the result Color4.
  627. */
  628. Color4.prototype.multiplyToRef = function (color, result) {
  629. result.r = this.r * color.r;
  630. result.g = this.g * color.g;
  631. result.b = this.b * color.b;
  632. result.a = this.a * color.a;
  633. return result;
  634. };
  635. /**
  636. * Returns a string with the Color4 values.
  637. */
  638. Color4.prototype.toString = function () {
  639. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  640. };
  641. /**
  642. * Returns the string "Color4"
  643. */
  644. Color4.prototype.getClassName = function () {
  645. return "Color4";
  646. };
  647. /**
  648. * Return the Color4 hash code as a number.
  649. */
  650. Color4.prototype.getHashCode = function () {
  651. var hash = this.r || 0;
  652. hash = (hash * 397) ^ (this.g || 0);
  653. hash = (hash * 397) ^ (this.b || 0);
  654. hash = (hash * 397) ^ (this.a || 0);
  655. return hash;
  656. };
  657. /**
  658. * Creates a new Color4 copied from the current one.
  659. */
  660. Color4.prototype.clone = function () {
  661. return new Color4(this.r, this.g, this.b, this.a);
  662. };
  663. /**
  664. * Copies the passed Color4 values into the current one.
  665. * Returns the updated Color4.
  666. */
  667. Color4.prototype.copyFrom = function (source) {
  668. this.r = source.r;
  669. this.g = source.g;
  670. this.b = source.b;
  671. this.a = source.a;
  672. return this;
  673. };
  674. /**
  675. * Copies the passed float values into the current one.
  676. * Returns the updated Color4.
  677. */
  678. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  679. this.r = r;
  680. this.g = g;
  681. this.b = b;
  682. this.a = a;
  683. return this;
  684. };
  685. /**
  686. * Copies the passed float values into the current one.
  687. * Returns the updated Color4.
  688. */
  689. Color4.prototype.set = function (r, g, b, a) {
  690. return this.copyFromFloats(r, g, b, a);
  691. };
  692. /**
  693. * Returns a string containing the hexadecimal Color4 code.
  694. */
  695. Color4.prototype.toHexString = function () {
  696. var intR = (this.r * 255) | 0;
  697. var intG = (this.g * 255) | 0;
  698. var intB = (this.b * 255) | 0;
  699. var intA = (this.a * 255) | 0;
  700. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  701. };
  702. /**
  703. * Returns a new Color4 converted to linear space.
  704. */
  705. Color4.prototype.toLinearSpace = function () {
  706. var convertedColor = new Color4();
  707. this.toLinearSpaceToRef(convertedColor);
  708. return convertedColor;
  709. };
  710. /**
  711. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  712. * Returns the unmodified Color4.
  713. */
  714. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  715. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  716. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  717. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  718. convertedColor.a = this.a;
  719. return this;
  720. };
  721. /**
  722. * Returns a new Color4 converted to gamma space.
  723. */
  724. Color4.prototype.toGammaSpace = function () {
  725. var convertedColor = new Color4();
  726. this.toGammaSpaceToRef(convertedColor);
  727. return convertedColor;
  728. };
  729. /**
  730. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  731. * Returns the unmodified Color4.
  732. */
  733. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  734. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  735. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  736. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  737. convertedColor.a = this.a;
  738. return this;
  739. };
  740. // Statics
  741. /**
  742. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  743. */
  744. Color4.FromHexString = function (hex) {
  745. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  746. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  747. return new Color4(0.0, 0.0, 0.0, 0.0);
  748. }
  749. var r = parseInt(hex.substring(1, 3), 16);
  750. var g = parseInt(hex.substring(3, 5), 16);
  751. var b = parseInt(hex.substring(5, 7), 16);
  752. var a = parseInt(hex.substring(7, 9), 16);
  753. return Color4.FromInts(r, g, b, a);
  754. };
  755. /**
  756. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  757. */
  758. Color4.Lerp = function (left, right, amount) {
  759. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  760. Color4.LerpToRef(left, right, amount, result);
  761. return result;
  762. };
  763. /**
  764. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  765. */
  766. Color4.LerpToRef = function (left, right, amount, result) {
  767. result.r = left.r + (right.r - left.r) * amount;
  768. result.g = left.g + (right.g - left.g) * amount;
  769. result.b = left.b + (right.b - left.b) * amount;
  770. result.a = left.a + (right.a - left.a) * amount;
  771. };
  772. /**
  773. * Creates a new Color4 from the starting index element of the passed array.
  774. */
  775. Color4.FromArray = function (array, offset) {
  776. if (offset === void 0) { offset = 0; }
  777. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  778. };
  779. /**
  780. * Creates a new Color4 from the passed integers ( < 256 ).
  781. */
  782. Color4.FromInts = function (r, g, b, a) {
  783. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  784. };
  785. Color4.CheckColors4 = function (colors, count) {
  786. // Check if color3 was used
  787. if (colors.length === count * 3) {
  788. var colors4 = [];
  789. for (var index = 0; index < colors.length; index += 3) {
  790. var newIndex = (index / 3) * 4;
  791. colors4[newIndex] = colors[index];
  792. colors4[newIndex + 1] = colors[index + 1];
  793. colors4[newIndex + 2] = colors[index + 2];
  794. colors4[newIndex + 3] = 1.0;
  795. }
  796. return colors4;
  797. }
  798. return colors;
  799. };
  800. return Color4;
  801. }());
  802. BABYLON.Color4 = Color4;
  803. var Vector2 = /** @class */ (function () {
  804. /**
  805. * Creates a new Vector2 from the passed x and y coordinates.
  806. */
  807. function Vector2(x, y) {
  808. this.x = x;
  809. this.y = y;
  810. }
  811. /**
  812. * Returns a string with the Vector2 coordinates.
  813. */
  814. Vector2.prototype.toString = function () {
  815. return "{X: " + this.x + " Y:" + this.y + "}";
  816. };
  817. /**
  818. * Returns the string "Vector2"
  819. */
  820. Vector2.prototype.getClassName = function () {
  821. return "Vector2";
  822. };
  823. /**
  824. * Returns the Vector2 hash code as a number.
  825. */
  826. Vector2.prototype.getHashCode = function () {
  827. var hash = this.x || 0;
  828. hash = (hash * 397) ^ (this.y || 0);
  829. return hash;
  830. };
  831. // Operators
  832. /**
  833. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  834. * Returns the Vector2.
  835. */
  836. Vector2.prototype.toArray = function (array, index) {
  837. if (index === void 0) { index = 0; }
  838. array[index] = this.x;
  839. array[index + 1] = this.y;
  840. return this;
  841. };
  842. /**
  843. * Returns a new array with 2 elements : the Vector2 coordinates.
  844. */
  845. Vector2.prototype.asArray = function () {
  846. var result = new Array();
  847. this.toArray(result, 0);
  848. return result;
  849. };
  850. /**
  851. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  852. * Returns the updated Vector2.
  853. */
  854. Vector2.prototype.copyFrom = function (source) {
  855. this.x = source.x;
  856. this.y = source.y;
  857. return this;
  858. };
  859. /**
  860. * Sets the Vector2 coordinates with the passed floats.
  861. * Returns the updated Vector2.
  862. */
  863. Vector2.prototype.copyFromFloats = function (x, y) {
  864. this.x = x;
  865. this.y = y;
  866. return this;
  867. };
  868. /**
  869. * Sets the Vector2 coordinates with the passed floats.
  870. * Returns the updated Vector2.
  871. */
  872. Vector2.prototype.set = function (x, y) {
  873. return this.copyFromFloats(x, y);
  874. };
  875. /**
  876. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  877. */
  878. Vector2.prototype.add = function (otherVector) {
  879. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  880. };
  881. /**
  882. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  883. * Returns the Vector2.
  884. */
  885. Vector2.prototype.addToRef = function (otherVector, result) {
  886. result.x = this.x + otherVector.x;
  887. result.y = this.y + otherVector.y;
  888. return this;
  889. };
  890. /**
  891. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  892. * Returns the updated Vector2.
  893. */
  894. Vector2.prototype.addInPlace = function (otherVector) {
  895. this.x += otherVector.x;
  896. this.y += otherVector.y;
  897. return this;
  898. };
  899. /**
  900. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  901. */
  902. Vector2.prototype.addVector3 = function (otherVector) {
  903. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  904. };
  905. /**
  906. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  907. */
  908. Vector2.prototype.subtract = function (otherVector) {
  909. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  910. };
  911. /**
  912. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  913. * Returns the Vector2.
  914. */
  915. Vector2.prototype.subtractToRef = function (otherVector, result) {
  916. result.x = this.x - otherVector.x;
  917. result.y = this.y - otherVector.y;
  918. return this;
  919. };
  920. /**
  921. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  922. * Returns the updated Vector2.
  923. */
  924. Vector2.prototype.subtractInPlace = function (otherVector) {
  925. this.x -= otherVector.x;
  926. this.y -= otherVector.y;
  927. return this;
  928. };
  929. /**
  930. * Multiplies in place the current Vector2 coordinates by the passed ones.
  931. * Returns the updated Vector2.
  932. */
  933. Vector2.prototype.multiplyInPlace = function (otherVector) {
  934. this.x *= otherVector.x;
  935. this.y *= otherVector.y;
  936. return this;
  937. };
  938. /**
  939. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  940. */
  941. Vector2.prototype.multiply = function (otherVector) {
  942. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  943. };
  944. /**
  945. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  946. * Returns the Vector2.
  947. */
  948. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  949. result.x = this.x * otherVector.x;
  950. result.y = this.y * otherVector.y;
  951. return this;
  952. };
  953. /**
  954. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  955. */
  956. Vector2.prototype.multiplyByFloats = function (x, y) {
  957. return new Vector2(this.x * x, this.y * y);
  958. };
  959. /**
  960. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  961. */
  962. Vector2.prototype.divide = function (otherVector) {
  963. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  964. };
  965. /**
  966. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  967. * Returns the Vector2.
  968. */
  969. Vector2.prototype.divideToRef = function (otherVector, result) {
  970. result.x = this.x / otherVector.x;
  971. result.y = this.y / otherVector.y;
  972. return this;
  973. };
  974. /**
  975. * Returns a new Vector2 with current Vector2 negated coordinates.
  976. */
  977. Vector2.prototype.negate = function () {
  978. return new Vector2(-this.x, -this.y);
  979. };
  980. /**
  981. * Multiply the Vector2 coordinates by scale.
  982. * Returns the updated Vector2.
  983. */
  984. Vector2.prototype.scaleInPlace = function (scale) {
  985. this.x *= scale;
  986. this.y *= scale;
  987. return this;
  988. };
  989. /**
  990. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  991. */
  992. Vector2.prototype.scale = function (scale) {
  993. return new Vector2(this.x * scale, this.y * scale);
  994. };
  995. /**
  996. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  997. */
  998. Vector2.prototype.equals = function (otherVector) {
  999. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1000. };
  1001. /**
  1002. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1003. */
  1004. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1005. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1006. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1007. };
  1008. // Properties
  1009. /**
  1010. * Returns the vector length (float).
  1011. */
  1012. Vector2.prototype.length = function () {
  1013. return Math.sqrt(this.x * this.x + this.y * this.y);
  1014. };
  1015. /**
  1016. * Returns the vector squared length (float);
  1017. */
  1018. Vector2.prototype.lengthSquared = function () {
  1019. return (this.x * this.x + this.y * this.y);
  1020. };
  1021. // Methods
  1022. /**
  1023. * Normalize the vector.
  1024. * Returns the updated Vector2.
  1025. */
  1026. Vector2.prototype.normalize = function () {
  1027. var len = this.length();
  1028. if (len === 0)
  1029. return this;
  1030. var num = 1.0 / len;
  1031. this.x *= num;
  1032. this.y *= num;
  1033. return this;
  1034. };
  1035. /**
  1036. * Returns a new Vector2 copied from the Vector2.
  1037. */
  1038. Vector2.prototype.clone = function () {
  1039. return new Vector2(this.x, this.y);
  1040. };
  1041. // Statics
  1042. /**
  1043. * Returns a new Vector2(0, 0)
  1044. */
  1045. Vector2.Zero = function () {
  1046. return new Vector2(0, 0);
  1047. };
  1048. /**
  1049. * Returns a new Vector2(1, 1)
  1050. */
  1051. Vector2.One = function () {
  1052. return new Vector2(1, 1);
  1053. };
  1054. /**
  1055. * Returns a new Vector2 set from the passed index element of the passed array.
  1056. */
  1057. Vector2.FromArray = function (array, offset) {
  1058. if (offset === void 0) { offset = 0; }
  1059. return new Vector2(array[offset], array[offset + 1]);
  1060. };
  1061. /**
  1062. * Sets "result" from the passed index element of the passed array.
  1063. */
  1064. Vector2.FromArrayToRef = function (array, offset, result) {
  1065. result.x = array[offset];
  1066. result.y = array[offset + 1];
  1067. };
  1068. /**
  1069. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1070. */
  1071. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1072. var squared = amount * amount;
  1073. var cubed = amount * squared;
  1074. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1075. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1076. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1077. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1078. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1079. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1080. return new Vector2(x, y);
  1081. };
  1082. /**
  1083. * 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".
  1084. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1085. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1086. */
  1087. Vector2.Clamp = function (value, min, max) {
  1088. var x = value.x;
  1089. x = (x > max.x) ? max.x : x;
  1090. x = (x < min.x) ? min.x : x;
  1091. var y = value.y;
  1092. y = (y > max.y) ? max.y : y;
  1093. y = (y < min.y) ? min.y : y;
  1094. return new Vector2(x, y);
  1095. };
  1096. /**
  1097. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1098. */
  1099. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1100. var squared = amount * amount;
  1101. var cubed = amount * squared;
  1102. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1103. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1104. var part3 = (cubed - (2.0 * squared)) + amount;
  1105. var part4 = cubed - squared;
  1106. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1107. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1108. return new Vector2(x, y);
  1109. };
  1110. /**
  1111. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1112. */
  1113. Vector2.Lerp = function (start, end, amount) {
  1114. var x = start.x + ((end.x - start.x) * amount);
  1115. var y = start.y + ((end.y - start.y) * amount);
  1116. return new Vector2(x, y);
  1117. };
  1118. /**
  1119. * Returns the dot product (float) of the vector "left" and the vector "right".
  1120. */
  1121. Vector2.Dot = function (left, right) {
  1122. return left.x * right.x + left.y * right.y;
  1123. };
  1124. /**
  1125. * Returns a new Vector2 equal to the normalized passed vector.
  1126. */
  1127. Vector2.Normalize = function (vector) {
  1128. var newVector = vector.clone();
  1129. newVector.normalize();
  1130. return newVector;
  1131. };
  1132. /**
  1133. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1134. */
  1135. Vector2.Minimize = function (left, right) {
  1136. var x = (left.x < right.x) ? left.x : right.x;
  1137. var y = (left.y < right.y) ? left.y : right.y;
  1138. return new Vector2(x, y);
  1139. };
  1140. /**
  1141. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1142. */
  1143. Vector2.Maximize = function (left, right) {
  1144. var x = (left.x > right.x) ? left.x : right.x;
  1145. var y = (left.y > right.y) ? left.y : right.y;
  1146. return new Vector2(x, y);
  1147. };
  1148. /**
  1149. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1150. */
  1151. Vector2.Transform = function (vector, transformation) {
  1152. var r = Vector2.Zero();
  1153. Vector2.TransformToRef(vector, transformation, r);
  1154. return r;
  1155. };
  1156. /**
  1157. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1158. */
  1159. Vector2.TransformToRef = function (vector, transformation, result) {
  1160. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1161. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1162. result.x = x;
  1163. result.y = y;
  1164. };
  1165. /**
  1166. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1167. */
  1168. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1169. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1170. var sign = a < 0 ? -1 : 1;
  1171. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1172. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1173. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1174. };
  1175. /**
  1176. * Returns the distance (float) between the vectors "value1" and "value2".
  1177. */
  1178. Vector2.Distance = function (value1, value2) {
  1179. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1180. };
  1181. /**
  1182. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1183. */
  1184. Vector2.DistanceSquared = function (value1, value2) {
  1185. var x = value1.x - value2.x;
  1186. var y = value1.y - value2.y;
  1187. return (x * x) + (y * y);
  1188. };
  1189. /**
  1190. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1191. */
  1192. Vector2.Center = function (value1, value2) {
  1193. var center = value1.add(value2);
  1194. center.scaleInPlace(0.5);
  1195. return center;
  1196. };
  1197. /**
  1198. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1199. */
  1200. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1201. var l2 = Vector2.DistanceSquared(segA, segB);
  1202. if (l2 === 0.0) {
  1203. return Vector2.Distance(p, segA);
  1204. }
  1205. var v = segB.subtract(segA);
  1206. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1207. var proj = segA.add(v.multiplyByFloats(t, t));
  1208. return Vector2.Distance(p, proj);
  1209. };
  1210. return Vector2;
  1211. }());
  1212. BABYLON.Vector2 = Vector2;
  1213. var Vector3 = /** @class */ (function () {
  1214. /**
  1215. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1216. * A Vector3 is the main object used in 3D geometry.
  1217. * It can represent etiher the coordinates of a point the space, either a direction.
  1218. */
  1219. function Vector3(x, y, z) {
  1220. this.x = x;
  1221. this.y = y;
  1222. this.z = z;
  1223. }
  1224. /**
  1225. * Returns a string with the Vector3 coordinates.
  1226. */
  1227. Vector3.prototype.toString = function () {
  1228. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1229. };
  1230. /**
  1231. * Returns the string "Vector3"
  1232. */
  1233. Vector3.prototype.getClassName = function () {
  1234. return "Vector3";
  1235. };
  1236. /**
  1237. * Returns the Vector hash code.
  1238. */
  1239. Vector3.prototype.getHashCode = function () {
  1240. var hash = this.x || 0;
  1241. hash = (hash * 397) ^ (this.y || 0);
  1242. hash = (hash * 397) ^ (this.z || 0);
  1243. return hash;
  1244. };
  1245. // Operators
  1246. /**
  1247. * Returns a new array with three elements : the coordinates the Vector3.
  1248. */
  1249. Vector3.prototype.asArray = function () {
  1250. var result = [];
  1251. this.toArray(result, 0);
  1252. return result;
  1253. };
  1254. /**
  1255. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1256. * Returns the Vector3.
  1257. */
  1258. Vector3.prototype.toArray = function (array, index) {
  1259. if (index === void 0) { index = 0; }
  1260. array[index] = this.x;
  1261. array[index + 1] = this.y;
  1262. array[index + 2] = this.z;
  1263. return this;
  1264. };
  1265. /**
  1266. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1267. */
  1268. Vector3.prototype.toQuaternion = function () {
  1269. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1270. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1271. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1272. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1273. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1274. var cosy = Math.cos(this.y * 0.5);
  1275. var siny = Math.sin(this.y * 0.5);
  1276. result.x = coszMinusx * siny;
  1277. result.y = -sinzMinusx * siny;
  1278. result.z = sinxPlusz * cosy;
  1279. result.w = cosxPlusz * cosy;
  1280. return result;
  1281. };
  1282. /**
  1283. * Adds the passed vector to the current Vector3.
  1284. * Returns the updated Vector3.
  1285. */
  1286. Vector3.prototype.addInPlace = function (otherVector) {
  1287. this.x += otherVector.x;
  1288. this.y += otherVector.y;
  1289. this.z += otherVector.z;
  1290. return this;
  1291. };
  1292. /**
  1293. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1294. */
  1295. Vector3.prototype.add = function (otherVector) {
  1296. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1297. };
  1298. /**
  1299. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1300. * Returns the current Vector3.
  1301. */
  1302. Vector3.prototype.addToRef = function (otherVector, result) {
  1303. result.x = this.x + otherVector.x;
  1304. result.y = this.y + otherVector.y;
  1305. result.z = this.z + otherVector.z;
  1306. return this;
  1307. };
  1308. /**
  1309. * Subtract the passed vector from the current Vector3.
  1310. * Returns the updated Vector3.
  1311. */
  1312. Vector3.prototype.subtractInPlace = function (otherVector) {
  1313. this.x -= otherVector.x;
  1314. this.y -= otherVector.y;
  1315. this.z -= otherVector.z;
  1316. return this;
  1317. };
  1318. /**
  1319. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1320. */
  1321. Vector3.prototype.subtract = function (otherVector) {
  1322. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1323. };
  1324. /**
  1325. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1326. * Returns the current Vector3.
  1327. */
  1328. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1329. result.x = this.x - otherVector.x;
  1330. result.y = this.y - otherVector.y;
  1331. result.z = this.z - otherVector.z;
  1332. return this;
  1333. };
  1334. /**
  1335. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1336. */
  1337. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1338. return new Vector3(this.x - x, this.y - y, this.z - z);
  1339. };
  1340. /**
  1341. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1342. * Returns the current Vector3.
  1343. */
  1344. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1345. result.x = this.x - x;
  1346. result.y = this.y - y;
  1347. result.z = this.z - z;
  1348. return this;
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1352. */
  1353. Vector3.prototype.negate = function () {
  1354. return new Vector3(-this.x, -this.y, -this.z);
  1355. };
  1356. /**
  1357. * Multiplies the Vector3 coordinates by the float "scale".
  1358. * Returns the updated Vector3.
  1359. */
  1360. Vector3.prototype.scaleInPlace = function (scale) {
  1361. this.x *= scale;
  1362. this.y *= scale;
  1363. this.z *= scale;
  1364. return this;
  1365. };
  1366. /**
  1367. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1368. */
  1369. Vector3.prototype.scale = function (scale) {
  1370. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1371. };
  1372. /**
  1373. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1374. * Returns the current Vector3.
  1375. */
  1376. Vector3.prototype.scaleToRef = function (scale, result) {
  1377. result.x = this.x * scale;
  1378. result.y = this.y * scale;
  1379. result.z = this.z * scale;
  1380. return this;
  1381. };
  1382. /**
  1383. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1384. */
  1385. Vector3.prototype.equals = function (otherVector) {
  1386. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1387. };
  1388. /**
  1389. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1390. */
  1391. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1392. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1393. 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);
  1394. };
  1395. /**
  1396. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1397. */
  1398. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1399. return this.x === x && this.y === y && this.z === z;
  1400. };
  1401. /**
  1402. * Muliplies the current Vector3 coordinates by the passed ones.
  1403. * Returns the updated Vector3.
  1404. */
  1405. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1406. this.x *= otherVector.x;
  1407. this.y *= otherVector.y;
  1408. this.z *= otherVector.z;
  1409. return this;
  1410. };
  1411. /**
  1412. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1413. */
  1414. Vector3.prototype.multiply = function (otherVector) {
  1415. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1416. };
  1417. /**
  1418. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1419. * Returns the current Vector3.
  1420. */
  1421. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1422. result.x = this.x * otherVector.x;
  1423. result.y = this.y * otherVector.y;
  1424. result.z = this.z * otherVector.z;
  1425. return this;
  1426. };
  1427. /**
  1428. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1429. */
  1430. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1431. return new Vector3(this.x * x, this.y * y, this.z * z);
  1432. };
  1433. /**
  1434. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1435. */
  1436. Vector3.prototype.divide = function (otherVector) {
  1437. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1438. };
  1439. /**
  1440. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1441. * Returns the current Vector3.
  1442. */
  1443. Vector3.prototype.divideToRef = function (otherVector, result) {
  1444. result.x = this.x / otherVector.x;
  1445. result.y = this.y / otherVector.y;
  1446. result.z = this.z / otherVector.z;
  1447. return this;
  1448. };
  1449. /**
  1450. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1451. * Returns the updated Vector3.
  1452. */
  1453. Vector3.prototype.MinimizeInPlace = function (other) {
  1454. if (other.x < this.x)
  1455. this.x = other.x;
  1456. if (other.y < this.y)
  1457. this.y = other.y;
  1458. if (other.z < this.z)
  1459. this.z = other.z;
  1460. return this;
  1461. };
  1462. /**
  1463. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1464. * Returns the updated Vector3.
  1465. */
  1466. Vector3.prototype.MaximizeInPlace = function (other) {
  1467. if (other.x > this.x)
  1468. this.x = other.x;
  1469. if (other.y > this.y)
  1470. this.y = other.y;
  1471. if (other.z > this.z)
  1472. this.z = other.z;
  1473. return this;
  1474. };
  1475. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1476. /**
  1477. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1478. */
  1479. get: function () {
  1480. var absX = Math.abs(this.x);
  1481. var absY = Math.abs(this.y);
  1482. if (absX !== absY) {
  1483. return true;
  1484. }
  1485. var absZ = Math.abs(this.z);
  1486. if (absX !== absZ) {
  1487. return true;
  1488. }
  1489. if (absY !== absZ) {
  1490. return true;
  1491. }
  1492. return false;
  1493. },
  1494. enumerable: true,
  1495. configurable: true
  1496. });
  1497. // Properties
  1498. /**
  1499. * Returns the length of the Vector3 (float).
  1500. */
  1501. Vector3.prototype.length = function () {
  1502. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1503. };
  1504. /**
  1505. * Returns the squared length of the Vector3 (float).
  1506. */
  1507. Vector3.prototype.lengthSquared = function () {
  1508. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1509. };
  1510. // Methods
  1511. /**
  1512. * Normalize the current Vector3.
  1513. * Returns the updated Vector3.
  1514. */
  1515. Vector3.prototype.normalize = function () {
  1516. var len = this.length();
  1517. if (len === 0 || len === 1.0)
  1518. return this;
  1519. var num = 1.0 / len;
  1520. this.x *= num;
  1521. this.y *= num;
  1522. this.z *= num;
  1523. return this;
  1524. };
  1525. /**
  1526. * Returns a new Vector3 copied from the current Vector3.
  1527. */
  1528. Vector3.prototype.clone = function () {
  1529. return new Vector3(this.x, this.y, this.z);
  1530. };
  1531. /**
  1532. * Copies the passed vector coordinates to the current Vector3 ones.
  1533. * Returns the updated Vector3.
  1534. */
  1535. Vector3.prototype.copyFrom = function (source) {
  1536. this.x = source.x;
  1537. this.y = source.y;
  1538. this.z = source.z;
  1539. return this;
  1540. };
  1541. /**
  1542. * Copies the passed floats to the current Vector3 coordinates.
  1543. * Returns the updated Vector3.
  1544. */
  1545. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1546. this.x = x;
  1547. this.y = y;
  1548. this.z = z;
  1549. return this;
  1550. };
  1551. /**
  1552. * Copies the passed floats to the current Vector3 coordinates.
  1553. * Returns the updated Vector3.
  1554. */
  1555. Vector3.prototype.set = function (x, y, z) {
  1556. return this.copyFromFloats(x, y, z);
  1557. };
  1558. // Statics
  1559. /**
  1560. *
  1561. */
  1562. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1563. var d0 = Vector3.Dot(vector0, axis) - size;
  1564. var d1 = Vector3.Dot(vector1, axis) - size;
  1565. var s = d0 / (d0 - d1);
  1566. return s;
  1567. };
  1568. /**
  1569. * Returns a new Vector3 set from the index "offset" of the passed array.
  1570. */
  1571. Vector3.FromArray = function (array, offset) {
  1572. if (!offset) {
  1573. offset = 0;
  1574. }
  1575. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1579. * This function is deprecated. Use FromArray instead.
  1580. */
  1581. Vector3.FromFloatArray = function (array, offset) {
  1582. return Vector3.FromArray(array, offset);
  1583. };
  1584. /**
  1585. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1586. */
  1587. Vector3.FromArrayToRef = function (array, offset, result) {
  1588. result.x = array[offset];
  1589. result.y = array[offset + 1];
  1590. result.z = array[offset + 2];
  1591. };
  1592. /**
  1593. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1594. * This function is deprecated. Use FromArrayToRef instead.
  1595. */
  1596. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1597. return Vector3.FromArrayToRef(array, offset, result);
  1598. };
  1599. /**
  1600. * Sets the passed vector "result" with the passed floats.
  1601. */
  1602. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1603. result.x = x;
  1604. result.y = y;
  1605. result.z = z;
  1606. };
  1607. /**
  1608. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1609. */
  1610. Vector3.Zero = function () {
  1611. return new Vector3(0.0, 0.0, 0.0);
  1612. };
  1613. /**
  1614. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1615. */
  1616. Vector3.One = function () {
  1617. return new Vector3(1.0, 1.0, 1.0);
  1618. };
  1619. /**
  1620. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1621. */
  1622. Vector3.Up = function () {
  1623. return new Vector3(0.0, 1.0, 0.0);
  1624. };
  1625. /**
  1626. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1627. */
  1628. Vector3.Forward = function () {
  1629. return new Vector3(0.0, 0.0, 1.0);
  1630. };
  1631. /**
  1632. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1633. */
  1634. Vector3.Right = function () {
  1635. return new Vector3(1.0, 0.0, 0.0);
  1636. };
  1637. /**
  1638. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1639. */
  1640. Vector3.Left = function () {
  1641. return new Vector3(-1.0, 0.0, 0.0);
  1642. };
  1643. /**
  1644. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1645. * This method computes tranformed coordinates only, not transformed direction vectors.
  1646. */
  1647. Vector3.TransformCoordinates = function (vector, transformation) {
  1648. var result = Vector3.Zero();
  1649. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1650. return result;
  1651. };
  1652. /**
  1653. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1654. * This method computes tranformed coordinates only, not transformed direction vectors.
  1655. */
  1656. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1657. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1658. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1659. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1660. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1661. result.x = x / w;
  1662. result.y = y / w;
  1663. result.z = z / w;
  1664. };
  1665. /**
  1666. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1667. * This method computes tranformed coordinates only, not transformed direction vectors.
  1668. */
  1669. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1670. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1671. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1672. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1673. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1674. result.x = rx / rw;
  1675. result.y = ry / rw;
  1676. result.z = rz / rw;
  1677. };
  1678. /**
  1679. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1680. * This methods computes transformed normalized direction vectors only.
  1681. */
  1682. Vector3.TransformNormal = function (vector, transformation) {
  1683. var result = Vector3.Zero();
  1684. Vector3.TransformNormalToRef(vector, transformation, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1689. * This methods computes transformed normalized direction vectors only.
  1690. */
  1691. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1692. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1693. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1694. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1695. result.x = x;
  1696. result.y = y;
  1697. result.z = z;
  1698. };
  1699. /**
  1700. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1701. * This methods computes transformed normalized direction vectors only.
  1702. */
  1703. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1704. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1705. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1706. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1707. };
  1708. /**
  1709. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1710. */
  1711. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1712. var squared = amount * amount;
  1713. var cubed = amount * squared;
  1714. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1715. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1716. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1717. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1718. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1719. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1720. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1721. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1722. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1723. return new Vector3(x, y, z);
  1724. };
  1725. /**
  1726. * 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".
  1727. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1728. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1729. */
  1730. Vector3.Clamp = function (value, min, max) {
  1731. var x = value.x;
  1732. x = (x > max.x) ? max.x : x;
  1733. x = (x < min.x) ? min.x : x;
  1734. var y = value.y;
  1735. y = (y > max.y) ? max.y : y;
  1736. y = (y < min.y) ? min.y : y;
  1737. var z = value.z;
  1738. z = (z > max.z) ? max.z : z;
  1739. z = (z < min.z) ? min.z : z;
  1740. return new Vector3(x, y, z);
  1741. };
  1742. /**
  1743. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1744. */
  1745. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1746. var squared = amount * amount;
  1747. var cubed = amount * squared;
  1748. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1749. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1750. var part3 = (cubed - (2.0 * squared)) + amount;
  1751. var part4 = cubed - squared;
  1752. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1753. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1754. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1755. return new Vector3(x, y, z);
  1756. };
  1757. /**
  1758. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1759. */
  1760. Vector3.Lerp = function (start, end, amount) {
  1761. var result = new Vector3(0, 0, 0);
  1762. Vector3.LerpToRef(start, end, amount, result);
  1763. return result;
  1764. };
  1765. /**
  1766. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1767. */
  1768. Vector3.LerpToRef = function (start, end, amount, result) {
  1769. result.x = start.x + ((end.x - start.x) * amount);
  1770. result.y = start.y + ((end.y - start.y) * amount);
  1771. result.z = start.z + ((end.z - start.z) * amount);
  1772. };
  1773. /**
  1774. * Returns the dot product (float) between the vectors "left" and "right".
  1775. */
  1776. Vector3.Dot = function (left, right) {
  1777. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1778. };
  1779. /**
  1780. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1781. * The cross product is then orthogonal to both "left" and "right".
  1782. */
  1783. Vector3.Cross = function (left, right) {
  1784. var result = Vector3.Zero();
  1785. Vector3.CrossToRef(left, right, result);
  1786. return result;
  1787. };
  1788. /**
  1789. * Sets the passed vector "result" with the cross product of "left" and "right".
  1790. * The cross product is then orthogonal to both "left" and "right".
  1791. */
  1792. Vector3.CrossToRef = function (left, right, result) {
  1793. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1794. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1795. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1796. result.copyFrom(MathTmp.Vector3[0]);
  1797. };
  1798. /**
  1799. * Returns a new Vector3 as the normalization of the passed vector.
  1800. */
  1801. Vector3.Normalize = function (vector) {
  1802. var result = Vector3.Zero();
  1803. Vector3.NormalizeToRef(vector, result);
  1804. return result;
  1805. };
  1806. /**
  1807. * Sets the passed vector "result" with the normalization of the passed first vector.
  1808. */
  1809. Vector3.NormalizeToRef = function (vector, result) {
  1810. result.copyFrom(vector);
  1811. result.normalize();
  1812. };
  1813. Vector3.Project = function (vector, world, transform, viewport) {
  1814. var cw = viewport.width;
  1815. var ch = viewport.height;
  1816. var cx = viewport.x;
  1817. var cy = viewport.y;
  1818. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1819. 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);
  1820. var matrix = MathTmp.Matrix[0];
  1821. world.multiplyToRef(transform, matrix);
  1822. matrix.multiplyToRef(viewportMatrix, matrix);
  1823. return Vector3.TransformCoordinates(vector, matrix);
  1824. };
  1825. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1826. var matrix = MathTmp.Matrix[0];
  1827. world.multiplyToRef(transform, matrix);
  1828. matrix.invert();
  1829. source.x = source.x / viewportWidth * 2 - 1;
  1830. source.y = -(source.y / viewportHeight * 2 - 1);
  1831. var vector = Vector3.TransformCoordinates(source, matrix);
  1832. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1833. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1834. vector = vector.scale(1.0 / num);
  1835. }
  1836. return vector;
  1837. };
  1838. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1839. var matrix = MathTmp.Matrix[0];
  1840. world.multiplyToRef(view, matrix);
  1841. matrix.multiplyToRef(projection, matrix);
  1842. matrix.invert();
  1843. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1844. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1845. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1846. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1847. vector = vector.scale(1.0 / num);
  1848. }
  1849. return vector;
  1850. };
  1851. Vector3.Minimize = function (left, right) {
  1852. var min = left.clone();
  1853. min.MinimizeInPlace(right);
  1854. return min;
  1855. };
  1856. Vector3.Maximize = function (left, right) {
  1857. var max = left.clone();
  1858. max.MaximizeInPlace(right);
  1859. return max;
  1860. };
  1861. /**
  1862. * Returns the distance (float) between the vectors "value1" and "value2".
  1863. */
  1864. Vector3.Distance = function (value1, value2) {
  1865. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1866. };
  1867. /**
  1868. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1869. */
  1870. Vector3.DistanceSquared = function (value1, value2) {
  1871. var x = value1.x - value2.x;
  1872. var y = value1.y - value2.y;
  1873. var z = value1.z - value2.z;
  1874. return (x * x) + (y * y) + (z * z);
  1875. };
  1876. /**
  1877. * Returns a new Vector3 located at the center between "value1" and "value2".
  1878. */
  1879. Vector3.Center = function (value1, value2) {
  1880. var center = value1.add(value2);
  1881. center.scaleInPlace(0.5);
  1882. return center;
  1883. };
  1884. /**
  1885. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1886. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1887. * to something in order to rotate it from its local system to the given target system.
  1888. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1889. * Returns a new Vector3.
  1890. */
  1891. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1892. var rotation = Vector3.Zero();
  1893. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1894. return rotation;
  1895. };
  1896. /**
  1897. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1898. */
  1899. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1900. var quat = MathTmp.Quaternion[0];
  1901. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1902. quat.toEulerAnglesToRef(ref);
  1903. };
  1904. return Vector3;
  1905. }());
  1906. BABYLON.Vector3 = Vector3;
  1907. //Vector4 class created for EulerAngle class conversion to Quaternion
  1908. var Vector4 = /** @class */ (function () {
  1909. /**
  1910. * Creates a Vector4 object from the passed floats.
  1911. */
  1912. function Vector4(x, y, z, w) {
  1913. this.x = x;
  1914. this.y = y;
  1915. this.z = z;
  1916. this.w = w;
  1917. }
  1918. /**
  1919. * Returns the string with the Vector4 coordinates.
  1920. */
  1921. Vector4.prototype.toString = function () {
  1922. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1923. };
  1924. /**
  1925. * Returns the string "Vector4".
  1926. */
  1927. Vector4.prototype.getClassName = function () {
  1928. return "Vector4";
  1929. };
  1930. /**
  1931. * Returns the Vector4 hash code.
  1932. */
  1933. Vector4.prototype.getHashCode = function () {
  1934. var hash = this.x || 0;
  1935. hash = (hash * 397) ^ (this.y || 0);
  1936. hash = (hash * 397) ^ (this.z || 0);
  1937. hash = (hash * 397) ^ (this.w || 0);
  1938. return hash;
  1939. };
  1940. // Operators
  1941. /**
  1942. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1943. */
  1944. Vector4.prototype.asArray = function () {
  1945. var result = new Array();
  1946. this.toArray(result, 0);
  1947. return result;
  1948. };
  1949. /**
  1950. * Populates the passed array from the passed index with the Vector4 coordinates.
  1951. * Returns the Vector4.
  1952. */
  1953. Vector4.prototype.toArray = function (array, index) {
  1954. if (index === undefined) {
  1955. index = 0;
  1956. }
  1957. array[index] = this.x;
  1958. array[index + 1] = this.y;
  1959. array[index + 2] = this.z;
  1960. array[index + 3] = this.w;
  1961. return this;
  1962. };
  1963. /**
  1964. * Adds the passed vector to the current Vector4.
  1965. * Returns the updated Vector4.
  1966. */
  1967. Vector4.prototype.addInPlace = function (otherVector) {
  1968. this.x += otherVector.x;
  1969. this.y += otherVector.y;
  1970. this.z += otherVector.z;
  1971. this.w += otherVector.w;
  1972. return this;
  1973. };
  1974. /**
  1975. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1976. */
  1977. Vector4.prototype.add = function (otherVector) {
  1978. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1979. };
  1980. /**
  1981. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1982. * Returns the current Vector4.
  1983. */
  1984. Vector4.prototype.addToRef = function (otherVector, result) {
  1985. result.x = this.x + otherVector.x;
  1986. result.y = this.y + otherVector.y;
  1987. result.z = this.z + otherVector.z;
  1988. result.w = this.w + otherVector.w;
  1989. return this;
  1990. };
  1991. /**
  1992. * Subtract in place the passed vector from the current Vector4.
  1993. * Returns the updated Vector4.
  1994. */
  1995. Vector4.prototype.subtractInPlace = function (otherVector) {
  1996. this.x -= otherVector.x;
  1997. this.y -= otherVector.y;
  1998. this.z -= otherVector.z;
  1999. this.w -= otherVector.w;
  2000. return this;
  2001. };
  2002. /**
  2003. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2004. */
  2005. Vector4.prototype.subtract = function (otherVector) {
  2006. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2007. };
  2008. /**
  2009. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2010. * Returns the current Vector4.
  2011. */
  2012. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2013. result.x = this.x - otherVector.x;
  2014. result.y = this.y - otherVector.y;
  2015. result.z = this.z - otherVector.z;
  2016. result.w = this.w - otherVector.w;
  2017. return this;
  2018. };
  2019. /**
  2020. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2021. */
  2022. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2023. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2024. };
  2025. /**
  2026. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2027. * Returns the current Vector4.
  2028. */
  2029. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2030. result.x = this.x - x;
  2031. result.y = this.y - y;
  2032. result.z = this.z - z;
  2033. result.w = this.w - w;
  2034. return this;
  2035. };
  2036. /**
  2037. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2038. */
  2039. Vector4.prototype.negate = function () {
  2040. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2041. };
  2042. /**
  2043. * Multiplies the current Vector4 coordinates by scale (float).
  2044. * Returns the updated Vector4.
  2045. */
  2046. Vector4.prototype.scaleInPlace = function (scale) {
  2047. this.x *= scale;
  2048. this.y *= scale;
  2049. this.z *= scale;
  2050. this.w *= scale;
  2051. return this;
  2052. };
  2053. /**
  2054. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2055. */
  2056. Vector4.prototype.scale = function (scale) {
  2057. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2058. };
  2059. /**
  2060. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2061. * Returns the current Vector4.
  2062. */
  2063. Vector4.prototype.scaleToRef = function (scale, result) {
  2064. result.x = this.x * scale;
  2065. result.y = this.y * scale;
  2066. result.z = this.z * scale;
  2067. result.w = this.w * scale;
  2068. return this;
  2069. };
  2070. /**
  2071. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2072. */
  2073. Vector4.prototype.equals = function (otherVector) {
  2074. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2075. };
  2076. /**
  2077. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2078. */
  2079. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2080. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2081. return otherVector
  2082. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2083. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2084. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2085. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2086. };
  2087. /**
  2088. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2089. */
  2090. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2091. return this.x === x && this.y === y && this.z === z && this.w === w;
  2092. };
  2093. /**
  2094. * Multiplies in place the current Vector4 by the passed one.
  2095. * Returns the updated Vector4.
  2096. */
  2097. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2098. this.x *= otherVector.x;
  2099. this.y *= otherVector.y;
  2100. this.z *= otherVector.z;
  2101. this.w *= otherVector.w;
  2102. return this;
  2103. };
  2104. /**
  2105. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2106. */
  2107. Vector4.prototype.multiply = function (otherVector) {
  2108. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2109. };
  2110. /**
  2111. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2112. * Returns the current Vector4.
  2113. */
  2114. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2115. result.x = this.x * otherVector.x;
  2116. result.y = this.y * otherVector.y;
  2117. result.z = this.z * otherVector.z;
  2118. result.w = this.w * otherVector.w;
  2119. return this;
  2120. };
  2121. /**
  2122. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2123. */
  2124. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2125. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2126. };
  2127. /**
  2128. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2129. */
  2130. Vector4.prototype.divide = function (otherVector) {
  2131. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2132. };
  2133. /**
  2134. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2135. * Returns the current Vector4.
  2136. */
  2137. Vector4.prototype.divideToRef = function (otherVector, result) {
  2138. result.x = this.x / otherVector.x;
  2139. result.y = this.y / otherVector.y;
  2140. result.z = this.z / otherVector.z;
  2141. result.w = this.w / otherVector.w;
  2142. return this;
  2143. };
  2144. /**
  2145. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2146. */
  2147. Vector4.prototype.MinimizeInPlace = function (other) {
  2148. if (other.x < this.x)
  2149. this.x = other.x;
  2150. if (other.y < this.y)
  2151. this.y = other.y;
  2152. if (other.z < this.z)
  2153. this.z = other.z;
  2154. if (other.w < this.w)
  2155. this.w = other.w;
  2156. return this;
  2157. };
  2158. /**
  2159. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2160. */
  2161. Vector4.prototype.MaximizeInPlace = function (other) {
  2162. if (other.x > this.x)
  2163. this.x = other.x;
  2164. if (other.y > this.y)
  2165. this.y = other.y;
  2166. if (other.z > this.z)
  2167. this.z = other.z;
  2168. if (other.w > this.w)
  2169. this.w = other.w;
  2170. return this;
  2171. };
  2172. // Properties
  2173. /**
  2174. * Returns the Vector4 length (float).
  2175. */
  2176. Vector4.prototype.length = function () {
  2177. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2178. };
  2179. /**
  2180. * Returns the Vector4 squared length (float).
  2181. */
  2182. Vector4.prototype.lengthSquared = function () {
  2183. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2184. };
  2185. // Methods
  2186. /**
  2187. * Normalizes in place the Vector4.
  2188. * Returns the updated Vector4.
  2189. */
  2190. Vector4.prototype.normalize = function () {
  2191. var len = this.length();
  2192. if (len === 0)
  2193. return this;
  2194. var num = 1.0 / len;
  2195. this.x *= num;
  2196. this.y *= num;
  2197. this.z *= num;
  2198. this.w *= num;
  2199. return this;
  2200. };
  2201. /**
  2202. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2203. */
  2204. Vector4.prototype.toVector3 = function () {
  2205. return new Vector3(this.x, this.y, this.z);
  2206. };
  2207. /**
  2208. * Returns a new Vector4 copied from the current one.
  2209. */
  2210. Vector4.prototype.clone = function () {
  2211. return new Vector4(this.x, this.y, this.z, this.w);
  2212. };
  2213. /**
  2214. * Updates the current Vector4 with the passed one coordinates.
  2215. * Returns the updated Vector4.
  2216. */
  2217. Vector4.prototype.copyFrom = function (source) {
  2218. this.x = source.x;
  2219. this.y = source.y;
  2220. this.z = source.z;
  2221. this.w = source.w;
  2222. return this;
  2223. };
  2224. /**
  2225. * Updates the current Vector4 coordinates with the passed floats.
  2226. * Returns the updated Vector4.
  2227. */
  2228. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2229. this.x = x;
  2230. this.y = y;
  2231. this.z = z;
  2232. this.w = w;
  2233. return this;
  2234. };
  2235. /**
  2236. * Updates the current Vector4 coordinates with the passed floats.
  2237. * Returns the updated Vector4.
  2238. */
  2239. Vector4.prototype.set = function (x, y, z, w) {
  2240. return this.copyFromFloats(x, y, z, w);
  2241. };
  2242. // Statics
  2243. /**
  2244. * Returns a new Vector4 set from the starting index of the passed array.
  2245. */
  2246. Vector4.FromArray = function (array, offset) {
  2247. if (!offset) {
  2248. offset = 0;
  2249. }
  2250. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2251. };
  2252. /**
  2253. * Updates the passed vector "result" from the starting index of the passed array.
  2254. */
  2255. Vector4.FromArrayToRef = function (array, offset, result) {
  2256. result.x = array[offset];
  2257. result.y = array[offset + 1];
  2258. result.z = array[offset + 2];
  2259. result.w = array[offset + 3];
  2260. };
  2261. /**
  2262. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2263. */
  2264. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2265. Vector4.FromArrayToRef(array, offset, result);
  2266. };
  2267. /**
  2268. * Updates the passed vector "result" coordinates from the passed floats.
  2269. */
  2270. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2271. result.x = x;
  2272. result.y = y;
  2273. result.z = z;
  2274. result.w = w;
  2275. };
  2276. /**
  2277. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2278. */
  2279. Vector4.Zero = function () {
  2280. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2281. };
  2282. /**
  2283. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2284. */
  2285. Vector4.One = function () {
  2286. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2287. };
  2288. /**
  2289. * Returns a new normalized Vector4 from the passed one.
  2290. */
  2291. Vector4.Normalize = function (vector) {
  2292. var result = Vector4.Zero();
  2293. Vector4.NormalizeToRef(vector, result);
  2294. return result;
  2295. };
  2296. /**
  2297. * Updates the passed vector "result" from the normalization of the passed one.
  2298. */
  2299. Vector4.NormalizeToRef = function (vector, result) {
  2300. result.copyFrom(vector);
  2301. result.normalize();
  2302. };
  2303. Vector4.Minimize = function (left, right) {
  2304. var min = left.clone();
  2305. min.MinimizeInPlace(right);
  2306. return min;
  2307. };
  2308. Vector4.Maximize = function (left, right) {
  2309. var max = left.clone();
  2310. max.MaximizeInPlace(right);
  2311. return max;
  2312. };
  2313. /**
  2314. * Returns the distance (float) between the vectors "value1" and "value2".
  2315. */
  2316. Vector4.Distance = function (value1, value2) {
  2317. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2318. };
  2319. /**
  2320. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2321. */
  2322. Vector4.DistanceSquared = function (value1, value2) {
  2323. var x = value1.x - value2.x;
  2324. var y = value1.y - value2.y;
  2325. var z = value1.z - value2.z;
  2326. var w = value1.w - value2.w;
  2327. return (x * x) + (y * y) + (z * z) + (w * w);
  2328. };
  2329. /**
  2330. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2331. */
  2332. Vector4.Center = function (value1, value2) {
  2333. var center = value1.add(value2);
  2334. center.scaleInPlace(0.5);
  2335. return center;
  2336. };
  2337. /**
  2338. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2339. * This methods computes transformed normalized direction vectors only.
  2340. */
  2341. Vector4.TransformNormal = function (vector, transformation) {
  2342. var result = Vector4.Zero();
  2343. Vector4.TransformNormalToRef(vector, transformation, result);
  2344. return result;
  2345. };
  2346. /**
  2347. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2348. * This methods computes transformed normalized direction vectors only.
  2349. */
  2350. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2351. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2352. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2353. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2354. result.x = x;
  2355. result.y = y;
  2356. result.z = z;
  2357. result.w = vector.w;
  2358. };
  2359. /**
  2360. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2361. * This methods computes transformed normalized direction vectors only.
  2362. */
  2363. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2364. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2365. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2366. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2367. result.w = w;
  2368. };
  2369. return Vector4;
  2370. }());
  2371. BABYLON.Vector4 = Vector4;
  2372. var Size = /** @class */ (function () {
  2373. /**
  2374. * Creates a Size object from the passed width and height (floats).
  2375. */
  2376. function Size(width, height) {
  2377. this.width = width;
  2378. this.height = height;
  2379. }
  2380. // Returns a string with the Size width and height.
  2381. Size.prototype.toString = function () {
  2382. return "{W: " + this.width + ", H: " + this.height + "}";
  2383. };
  2384. /**
  2385. * Returns the string "Size"
  2386. */
  2387. Size.prototype.getClassName = function () {
  2388. return "Size";
  2389. };
  2390. /**
  2391. * Returns the Size hash code.
  2392. */
  2393. Size.prototype.getHashCode = function () {
  2394. var hash = this.width || 0;
  2395. hash = (hash * 397) ^ (this.height || 0);
  2396. return hash;
  2397. };
  2398. /**
  2399. * Updates the current size from the passed one.
  2400. * Returns the updated Size.
  2401. */
  2402. Size.prototype.copyFrom = function (src) {
  2403. this.width = src.width;
  2404. this.height = src.height;
  2405. };
  2406. /**
  2407. * Updates in place the current Size from the passed floats.
  2408. * Returns the updated Size.
  2409. */
  2410. Size.prototype.copyFromFloats = function (width, height) {
  2411. this.width = width;
  2412. this.height = height;
  2413. return this;
  2414. };
  2415. /**
  2416. * Updates in place the current Size from the passed floats.
  2417. * Returns the updated Size.
  2418. */
  2419. Size.prototype.set = function (width, height) {
  2420. return this.copyFromFloats(width, height);
  2421. };
  2422. /**
  2423. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2424. */
  2425. Size.prototype.multiplyByFloats = function (w, h) {
  2426. return new Size(this.width * w, this.height * h);
  2427. };
  2428. /**
  2429. * Returns a new Size copied from the passed one.
  2430. */
  2431. Size.prototype.clone = function () {
  2432. return new Size(this.width, this.height);
  2433. };
  2434. /**
  2435. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2436. */
  2437. Size.prototype.equals = function (other) {
  2438. if (!other) {
  2439. return false;
  2440. }
  2441. return (this.width === other.width) && (this.height === other.height);
  2442. };
  2443. Object.defineProperty(Size.prototype, "surface", {
  2444. /**
  2445. * Returns the surface of the Size : width * height (float).
  2446. */
  2447. get: function () {
  2448. return this.width * this.height;
  2449. },
  2450. enumerable: true,
  2451. configurable: true
  2452. });
  2453. /**
  2454. * Returns a new Size set to (0.0, 0.0)
  2455. */
  2456. Size.Zero = function () {
  2457. return new Size(0.0, 0.0);
  2458. };
  2459. /**
  2460. * Returns a new Size set as the addition result of the current Size and the passed one.
  2461. */
  2462. Size.prototype.add = function (otherSize) {
  2463. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2464. return r;
  2465. };
  2466. /**
  2467. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2468. */
  2469. Size.prototype.subtract = function (otherSize) {
  2470. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2471. return r;
  2472. };
  2473. /**
  2474. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2475. */
  2476. Size.Lerp = function (start, end, amount) {
  2477. var w = start.width + ((end.width - start.width) * amount);
  2478. var h = start.height + ((end.height - start.height) * amount);
  2479. return new Size(w, h);
  2480. };
  2481. return Size;
  2482. }());
  2483. BABYLON.Size = Size;
  2484. var Quaternion = /** @class */ (function () {
  2485. /**
  2486. * Creates a new Quaternion from the passed floats.
  2487. */
  2488. function Quaternion(x, y, z, w) {
  2489. if (x === void 0) { x = 0.0; }
  2490. if (y === void 0) { y = 0.0; }
  2491. if (z === void 0) { z = 0.0; }
  2492. if (w === void 0) { w = 1.0; }
  2493. this.x = x;
  2494. this.y = y;
  2495. this.z = z;
  2496. this.w = w;
  2497. }
  2498. /**
  2499. * Returns a string with the Quaternion coordinates.
  2500. */
  2501. Quaternion.prototype.toString = function () {
  2502. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2503. };
  2504. /**
  2505. * Returns the string "Quaternion".
  2506. */
  2507. Quaternion.prototype.getClassName = function () {
  2508. return "Quaternion";
  2509. };
  2510. /**
  2511. * Returns the Quaternion hash code.
  2512. */
  2513. Quaternion.prototype.getHashCode = function () {
  2514. var hash = this.x || 0;
  2515. hash = (hash * 397) ^ (this.y || 0);
  2516. hash = (hash * 397) ^ (this.z || 0);
  2517. hash = (hash * 397) ^ (this.w || 0);
  2518. return hash;
  2519. };
  2520. /**
  2521. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2522. */
  2523. Quaternion.prototype.asArray = function () {
  2524. return [this.x, this.y, this.z, this.w];
  2525. };
  2526. /**
  2527. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2528. */
  2529. Quaternion.prototype.equals = function (otherQuaternion) {
  2530. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2531. };
  2532. /**
  2533. * Returns a new Quaternion copied from the current one.
  2534. */
  2535. Quaternion.prototype.clone = function () {
  2536. return new Quaternion(this.x, this.y, this.z, this.w);
  2537. };
  2538. /**
  2539. * Updates the current Quaternion from the passed one coordinates.
  2540. * Returns the updated Quaterion.
  2541. */
  2542. Quaternion.prototype.copyFrom = function (other) {
  2543. this.x = other.x;
  2544. this.y = other.y;
  2545. this.z = other.z;
  2546. this.w = other.w;
  2547. return this;
  2548. };
  2549. /**
  2550. * Updates the current Quaternion from the passed float coordinates.
  2551. * Returns the updated Quaterion.
  2552. */
  2553. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2554. this.x = x;
  2555. this.y = y;
  2556. this.z = z;
  2557. this.w = w;
  2558. return this;
  2559. };
  2560. /**
  2561. * Updates the current Quaternion from the passed float coordinates.
  2562. * Returns the updated Quaterion.
  2563. */
  2564. Quaternion.prototype.set = function (x, y, z, w) {
  2565. return this.copyFromFloats(x, y, z, w);
  2566. };
  2567. /**
  2568. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2569. */
  2570. Quaternion.prototype.add = function (other) {
  2571. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2572. };
  2573. /**
  2574. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2575. */
  2576. Quaternion.prototype.subtract = function (other) {
  2577. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2578. };
  2579. /**
  2580. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2581. */
  2582. Quaternion.prototype.scale = function (value) {
  2583. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2584. };
  2585. /**
  2586. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2587. */
  2588. Quaternion.prototype.multiply = function (q1) {
  2589. var result = new Quaternion(0, 0, 0, 1.0);
  2590. this.multiplyToRef(q1, result);
  2591. return result;
  2592. };
  2593. /**
  2594. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2595. * Returns the current Quaternion.
  2596. */
  2597. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2598. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2599. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2600. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2601. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2602. result.copyFromFloats(x, y, z, w);
  2603. return this;
  2604. };
  2605. /**
  2606. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2607. * Returns the updated Quaternion.
  2608. */
  2609. Quaternion.prototype.multiplyInPlace = function (q1) {
  2610. this.multiplyToRef(q1, this);
  2611. return this;
  2612. };
  2613. /**
  2614. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2615. * Returns the current Quaternion.
  2616. */
  2617. Quaternion.prototype.conjugateToRef = function (ref) {
  2618. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2619. return this;
  2620. };
  2621. /**
  2622. * Conjugates in place the current Quaternion.
  2623. * Returns the updated Quaternion.
  2624. */
  2625. Quaternion.prototype.conjugateInPlace = function () {
  2626. this.x *= -1;
  2627. this.y *= -1;
  2628. this.z *= -1;
  2629. return this;
  2630. };
  2631. /**
  2632. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2633. */
  2634. Quaternion.prototype.conjugate = function () {
  2635. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2636. return result;
  2637. };
  2638. /**
  2639. * Returns the Quaternion length (float).
  2640. */
  2641. Quaternion.prototype.length = function () {
  2642. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2643. };
  2644. /**
  2645. * Normalize in place the current Quaternion.
  2646. * Returns the updated Quaternion.
  2647. */
  2648. Quaternion.prototype.normalize = function () {
  2649. var length = 1.0 / this.length();
  2650. this.x *= length;
  2651. this.y *= length;
  2652. this.z *= length;
  2653. this.w *= length;
  2654. return this;
  2655. };
  2656. /**
  2657. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2658. */
  2659. Quaternion.prototype.toEulerAngles = function (order) {
  2660. if (order === void 0) { order = "YZX"; }
  2661. var result = Vector3.Zero();
  2662. this.toEulerAnglesToRef(result, order);
  2663. return result;
  2664. };
  2665. /**
  2666. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2667. * Returns the current Quaternion.
  2668. */
  2669. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2670. if (order === void 0) { order = "YZX"; }
  2671. var qz = this.z;
  2672. var qx = this.x;
  2673. var qy = this.y;
  2674. var qw = this.w;
  2675. var sqw = qw * qw;
  2676. var sqz = qz * qz;
  2677. var sqx = qx * qx;
  2678. var sqy = qy * qy;
  2679. var zAxisY = qy * qz - qx * qw;
  2680. var limit = .4999999;
  2681. if (zAxisY < -limit) {
  2682. result.y = 2 * Math.atan2(qy, qw);
  2683. result.x = Math.PI / 2;
  2684. result.z = 0;
  2685. }
  2686. else if (zAxisY > limit) {
  2687. result.y = 2 * Math.atan2(qy, qw);
  2688. result.x = -Math.PI / 2;
  2689. result.z = 0;
  2690. }
  2691. else {
  2692. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2693. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2694. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2695. }
  2696. return this;
  2697. };
  2698. /**
  2699. * Updates the passed rotation matrix with the current Quaternion values.
  2700. * Returns the current Quaternion.
  2701. */
  2702. Quaternion.prototype.toRotationMatrix = function (result) {
  2703. var xx = this.x * this.x;
  2704. var yy = this.y * this.y;
  2705. var zz = this.z * this.z;
  2706. var xy = this.x * this.y;
  2707. var zw = this.z * this.w;
  2708. var zx = this.z * this.x;
  2709. var yw = this.y * this.w;
  2710. var yz = this.y * this.z;
  2711. var xw = this.x * this.w;
  2712. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2713. result.m[1] = 2.0 * (xy + zw);
  2714. result.m[2] = 2.0 * (zx - yw);
  2715. result.m[3] = 0;
  2716. result.m[4] = 2.0 * (xy - zw);
  2717. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2718. result.m[6] = 2.0 * (yz + xw);
  2719. result.m[7] = 0;
  2720. result.m[8] = 2.0 * (zx + yw);
  2721. result.m[9] = 2.0 * (yz - xw);
  2722. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2723. result.m[11] = 0;
  2724. result.m[12] = 0;
  2725. result.m[13] = 0;
  2726. result.m[14] = 0;
  2727. result.m[15] = 1.0;
  2728. result._markAsUpdated();
  2729. return this;
  2730. };
  2731. /**
  2732. * Updates the current Quaternion from the passed rotation matrix values.
  2733. * Returns the updated Quaternion.
  2734. */
  2735. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2736. Quaternion.FromRotationMatrixToRef(matrix, this);
  2737. return this;
  2738. };
  2739. // Statics
  2740. /**
  2741. * Returns a new Quaternion set from the passed rotation matrix values.
  2742. */
  2743. Quaternion.FromRotationMatrix = function (matrix) {
  2744. var result = new Quaternion();
  2745. Quaternion.FromRotationMatrixToRef(matrix, result);
  2746. return result;
  2747. };
  2748. /**
  2749. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2750. */
  2751. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2752. var data = matrix.m;
  2753. var m11 = data[0], m12 = data[4], m13 = data[8];
  2754. var m21 = data[1], m22 = data[5], m23 = data[9];
  2755. var m31 = data[2], m32 = data[6], m33 = data[10];
  2756. var trace = m11 + m22 + m33;
  2757. var s;
  2758. if (trace > 0) {
  2759. s = 0.5 / Math.sqrt(trace + 1.0);
  2760. result.w = 0.25 / s;
  2761. result.x = (m32 - m23) * s;
  2762. result.y = (m13 - m31) * s;
  2763. result.z = (m21 - m12) * s;
  2764. }
  2765. else if (m11 > m22 && m11 > m33) {
  2766. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2767. result.w = (m32 - m23) / s;
  2768. result.x = 0.25 * s;
  2769. result.y = (m12 + m21) / s;
  2770. result.z = (m13 + m31) / s;
  2771. }
  2772. else if (m22 > m33) {
  2773. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2774. result.w = (m13 - m31) / s;
  2775. result.x = (m12 + m21) / s;
  2776. result.y = 0.25 * s;
  2777. result.z = (m23 + m32) / s;
  2778. }
  2779. else {
  2780. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2781. result.w = (m21 - m12) / s;
  2782. result.x = (m13 + m31) / s;
  2783. result.y = (m23 + m32) / s;
  2784. result.z = 0.25 * s;
  2785. }
  2786. };
  2787. /**
  2788. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2789. */
  2790. Quaternion.Zero = function () {
  2791. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2792. };
  2793. /**
  2794. * Returns a new Quaternion as the inverted current Quaternion.
  2795. */
  2796. Quaternion.Inverse = function (q) {
  2797. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2798. };
  2799. /**
  2800. * Returns the identity Quaternion.
  2801. */
  2802. Quaternion.Identity = function () {
  2803. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2804. };
  2805. Quaternion.IsIdentity = function (quaternion) {
  2806. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2807. };
  2808. /**
  2809. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2810. */
  2811. Quaternion.RotationAxis = function (axis, angle) {
  2812. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2813. };
  2814. /**
  2815. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2816. */
  2817. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2818. var sin = Math.sin(angle / 2);
  2819. axis.normalize();
  2820. result.w = Math.cos(angle / 2);
  2821. result.x = axis.x * sin;
  2822. result.y = axis.y * sin;
  2823. result.z = axis.z * sin;
  2824. return result;
  2825. };
  2826. /**
  2827. * Retuns a new Quaternion set from the starting index of the passed array.
  2828. */
  2829. Quaternion.FromArray = function (array, offset) {
  2830. if (!offset) {
  2831. offset = 0;
  2832. }
  2833. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2834. };
  2835. /**
  2836. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2837. */
  2838. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2839. var q = new Quaternion();
  2840. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2841. return q;
  2842. };
  2843. /**
  2844. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2845. */
  2846. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2847. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2848. var halfRoll = roll * 0.5;
  2849. var halfPitch = pitch * 0.5;
  2850. var halfYaw = yaw * 0.5;
  2851. var sinRoll = Math.sin(halfRoll);
  2852. var cosRoll = Math.cos(halfRoll);
  2853. var sinPitch = Math.sin(halfPitch);
  2854. var cosPitch = Math.cos(halfPitch);
  2855. var sinYaw = Math.sin(halfYaw);
  2856. var cosYaw = Math.cos(halfYaw);
  2857. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2858. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2859. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2860. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2861. };
  2862. /**
  2863. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2864. */
  2865. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2866. var result = new Quaternion();
  2867. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2868. return result;
  2869. };
  2870. /**
  2871. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2872. */
  2873. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2874. // Produces a quaternion from Euler angles in the z-x-z orientation
  2875. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2876. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2877. var halfBeta = beta * 0.5;
  2878. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2879. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2880. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2881. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2882. };
  2883. /**
  2884. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2885. * cf to Vector3.RotationFromAxis() documentation.
  2886. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2887. */
  2888. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2889. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2890. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2891. return quat;
  2892. };
  2893. /**
  2894. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2895. * cf to Vector3.RotationFromAxis() documentation.
  2896. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2897. */
  2898. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2899. var rotMat = MathTmp.Matrix[0];
  2900. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2901. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2902. };
  2903. Quaternion.Slerp = function (left, right, amount) {
  2904. var result = Quaternion.Identity();
  2905. Quaternion.SlerpToRef(left, right, amount, result);
  2906. return result;
  2907. };
  2908. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2909. var num2;
  2910. var num3;
  2911. var num = amount;
  2912. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2913. var flag = false;
  2914. if (num4 < 0) {
  2915. flag = true;
  2916. num4 = -num4;
  2917. }
  2918. if (num4 > 0.999999) {
  2919. num3 = 1 - num;
  2920. num2 = flag ? -num : num;
  2921. }
  2922. else {
  2923. var num5 = Math.acos(num4);
  2924. var num6 = (1.0 / Math.sin(num5));
  2925. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2926. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2927. }
  2928. result.x = (num3 * left.x) + (num2 * right.x);
  2929. result.y = (num3 * left.y) + (num2 * right.y);
  2930. result.z = (num3 * left.z) + (num2 * right.z);
  2931. result.w = (num3 * left.w) + (num2 * right.w);
  2932. };
  2933. /**
  2934. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2935. */
  2936. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2937. var squared = amount * amount;
  2938. var cubed = amount * squared;
  2939. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2940. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2941. var part3 = (cubed - (2.0 * squared)) + amount;
  2942. var part4 = cubed - squared;
  2943. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2944. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2945. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2946. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2947. return new Quaternion(x, y, z, w);
  2948. };
  2949. return Quaternion;
  2950. }());
  2951. BABYLON.Quaternion = Quaternion;
  2952. var Matrix = /** @class */ (function () {
  2953. function Matrix() {
  2954. this._isIdentity = false;
  2955. this._isIdentityDirty = true;
  2956. this.m = new Float32Array(16);
  2957. this._markAsUpdated();
  2958. }
  2959. Matrix.prototype._markAsUpdated = function () {
  2960. this.updateFlag = Matrix._updateFlagSeed++;
  2961. this._isIdentityDirty = true;
  2962. };
  2963. // Properties
  2964. /**
  2965. * Boolean : True is the matrix is the identity matrix
  2966. */
  2967. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2968. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2969. if (this._isIdentityDirty) {
  2970. this._isIdentityDirty = false;
  2971. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2972. this._isIdentity = false;
  2973. }
  2974. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2975. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2976. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2977. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2978. this._isIdentity = false;
  2979. }
  2980. else {
  2981. this._isIdentity = true;
  2982. }
  2983. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2984. this._isIdentity = false;
  2985. }
  2986. }
  2987. return this._isIdentity;
  2988. };
  2989. /**
  2990. * Returns the matrix determinant (float).
  2991. */
  2992. Matrix.prototype.determinant = function () {
  2993. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2994. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2995. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2996. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2997. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2998. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2999. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3000. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3001. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3002. };
  3003. // Methods
  3004. /**
  3005. * Returns the matrix underlying array.
  3006. */
  3007. Matrix.prototype.toArray = function () {
  3008. return this.m;
  3009. };
  3010. /**
  3011. * Returns the matrix underlying array.
  3012. */
  3013. Matrix.prototype.asArray = function () {
  3014. return this.toArray();
  3015. };
  3016. /**
  3017. * Inverts in place the Matrix.
  3018. * Returns the Matrix inverted.
  3019. */
  3020. Matrix.prototype.invert = function () {
  3021. this.invertToRef(this);
  3022. return this;
  3023. };
  3024. /**
  3025. * Sets all the matrix elements to zero.
  3026. * Returns the Matrix.
  3027. */
  3028. Matrix.prototype.reset = function () {
  3029. for (var index = 0; index < 16; index++) {
  3030. this.m[index] = 0.0;
  3031. }
  3032. this._markAsUpdated();
  3033. return this;
  3034. };
  3035. /**
  3036. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3037. */
  3038. Matrix.prototype.add = function (other) {
  3039. var result = new Matrix();
  3040. this.addToRef(other, result);
  3041. return result;
  3042. };
  3043. /**
  3044. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3045. * Returns the Matrix.
  3046. */
  3047. Matrix.prototype.addToRef = function (other, result) {
  3048. for (var index = 0; index < 16; index++) {
  3049. result.m[index] = this.m[index] + other.m[index];
  3050. }
  3051. result._markAsUpdated();
  3052. return this;
  3053. };
  3054. /**
  3055. * Adds in place the passed matrix to the current Matrix.
  3056. * Returns the updated Matrix.
  3057. */
  3058. Matrix.prototype.addToSelf = function (other) {
  3059. for (var index = 0; index < 16; index++) {
  3060. this.m[index] += other.m[index];
  3061. }
  3062. this._markAsUpdated();
  3063. return this;
  3064. };
  3065. /**
  3066. * Sets the passed matrix with the current inverted Matrix.
  3067. * Returns the unmodified current Matrix.
  3068. */
  3069. Matrix.prototype.invertToRef = function (other) {
  3070. var l1 = this.m[0];
  3071. var l2 = this.m[1];
  3072. var l3 = this.m[2];
  3073. var l4 = this.m[3];
  3074. var l5 = this.m[4];
  3075. var l6 = this.m[5];
  3076. var l7 = this.m[6];
  3077. var l8 = this.m[7];
  3078. var l9 = this.m[8];
  3079. var l10 = this.m[9];
  3080. var l11 = this.m[10];
  3081. var l12 = this.m[11];
  3082. var l13 = this.m[12];
  3083. var l14 = this.m[13];
  3084. var l15 = this.m[14];
  3085. var l16 = this.m[15];
  3086. var l17 = (l11 * l16) - (l12 * l15);
  3087. var l18 = (l10 * l16) - (l12 * l14);
  3088. var l19 = (l10 * l15) - (l11 * l14);
  3089. var l20 = (l9 * l16) - (l12 * l13);
  3090. var l21 = (l9 * l15) - (l11 * l13);
  3091. var l22 = (l9 * l14) - (l10 * l13);
  3092. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3093. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3094. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3095. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3096. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3097. var l28 = (l7 * l16) - (l8 * l15);
  3098. var l29 = (l6 * l16) - (l8 * l14);
  3099. var l30 = (l6 * l15) - (l7 * l14);
  3100. var l31 = (l5 * l16) - (l8 * l13);
  3101. var l32 = (l5 * l15) - (l7 * l13);
  3102. var l33 = (l5 * l14) - (l6 * l13);
  3103. var l34 = (l7 * l12) - (l8 * l11);
  3104. var l35 = (l6 * l12) - (l8 * l10);
  3105. var l36 = (l6 * l11) - (l7 * l10);
  3106. var l37 = (l5 * l12) - (l8 * l9);
  3107. var l38 = (l5 * l11) - (l7 * l9);
  3108. var l39 = (l5 * l10) - (l6 * l9);
  3109. other.m[0] = l23 * l27;
  3110. other.m[4] = l24 * l27;
  3111. other.m[8] = l25 * l27;
  3112. other.m[12] = l26 * l27;
  3113. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3114. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3115. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3116. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3117. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3118. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3119. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3120. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3121. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3122. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3123. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3124. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3125. other._markAsUpdated();
  3126. return this;
  3127. };
  3128. /**
  3129. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3130. * Returns the updated Matrix.
  3131. */
  3132. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3133. this.m[12] = x;
  3134. this.m[13] = y;
  3135. this.m[14] = z;
  3136. this._markAsUpdated();
  3137. return this;
  3138. };
  3139. /**
  3140. * Inserts the translation vector in the current Matrix.
  3141. * Returns the updated Matrix.
  3142. */
  3143. Matrix.prototype.setTranslation = function (vector3) {
  3144. this.m[12] = vector3.x;
  3145. this.m[13] = vector3.y;
  3146. this.m[14] = vector3.z;
  3147. this._markAsUpdated();
  3148. return this;
  3149. };
  3150. /**
  3151. * Returns a new Vector3 as the extracted translation from the Matrix.
  3152. */
  3153. Matrix.prototype.getTranslation = function () {
  3154. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3155. };
  3156. /**
  3157. * Fill a Vector3 with the extracted translation from the Matrix.
  3158. */
  3159. Matrix.prototype.getTranslationToRef = function (result) {
  3160. result.x = this.m[12];
  3161. result.y = this.m[13];
  3162. result.z = this.m[14];
  3163. return this;
  3164. };
  3165. /**
  3166. * Remove rotation and scaling part from the Matrix.
  3167. * Returns the updated Matrix.
  3168. */
  3169. Matrix.prototype.removeRotationAndScaling = function () {
  3170. this.setRowFromFloats(0, 1, 0, 0, 0);
  3171. this.setRowFromFloats(1, 0, 1, 0, 0);
  3172. this.setRowFromFloats(2, 0, 0, 1, 0);
  3173. return this;
  3174. };
  3175. /**
  3176. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3177. */
  3178. Matrix.prototype.multiply = function (other) {
  3179. var result = new Matrix();
  3180. this.multiplyToRef(other, result);
  3181. return result;
  3182. };
  3183. /**
  3184. * Updates the current Matrix from the passed one values.
  3185. * Returns the updated Matrix.
  3186. */
  3187. Matrix.prototype.copyFrom = function (other) {
  3188. for (var index = 0; index < 16; index++) {
  3189. this.m[index] = other.m[index];
  3190. }
  3191. this._markAsUpdated();
  3192. return this;
  3193. };
  3194. /**
  3195. * Populates the passed array from the starting index with the Matrix values.
  3196. * Returns the Matrix.
  3197. */
  3198. Matrix.prototype.copyToArray = function (array, offset) {
  3199. if (offset === void 0) { offset = 0; }
  3200. for (var index = 0; index < 16; index++) {
  3201. array[offset + index] = this.m[index];
  3202. }
  3203. return this;
  3204. };
  3205. /**
  3206. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3207. */
  3208. Matrix.prototype.multiplyToRef = function (other, result) {
  3209. this.multiplyToArray(other, result.m, 0);
  3210. result._markAsUpdated();
  3211. return this;
  3212. };
  3213. /**
  3214. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3215. */
  3216. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3217. var tm0 = this.m[0];
  3218. var tm1 = this.m[1];
  3219. var tm2 = this.m[2];
  3220. var tm3 = this.m[3];
  3221. var tm4 = this.m[4];
  3222. var tm5 = this.m[5];
  3223. var tm6 = this.m[6];
  3224. var tm7 = this.m[7];
  3225. var tm8 = this.m[8];
  3226. var tm9 = this.m[9];
  3227. var tm10 = this.m[10];
  3228. var tm11 = this.m[11];
  3229. var tm12 = this.m[12];
  3230. var tm13 = this.m[13];
  3231. var tm14 = this.m[14];
  3232. var tm15 = this.m[15];
  3233. var om0 = other.m[0];
  3234. var om1 = other.m[1];
  3235. var om2 = other.m[2];
  3236. var om3 = other.m[3];
  3237. var om4 = other.m[4];
  3238. var om5 = other.m[5];
  3239. var om6 = other.m[6];
  3240. var om7 = other.m[7];
  3241. var om8 = other.m[8];
  3242. var om9 = other.m[9];
  3243. var om10 = other.m[10];
  3244. var om11 = other.m[11];
  3245. var om12 = other.m[12];
  3246. var om13 = other.m[13];
  3247. var om14 = other.m[14];
  3248. var om15 = other.m[15];
  3249. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3250. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3251. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3252. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3253. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3254. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3255. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3256. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3257. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3258. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3259. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3260. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3261. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3262. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3263. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3264. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3265. return this;
  3266. };
  3267. /**
  3268. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3269. */
  3270. Matrix.prototype.equals = function (value) {
  3271. return value &&
  3272. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3273. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3274. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3275. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3276. };
  3277. /**
  3278. * Returns a new Matrix from the current Matrix.
  3279. */
  3280. Matrix.prototype.clone = function () {
  3281. 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]);
  3282. };
  3283. /**
  3284. * Returns the string "Matrix"
  3285. */
  3286. Matrix.prototype.getClassName = function () {
  3287. return "Matrix";
  3288. };
  3289. /**
  3290. * Returns the Matrix hash code.
  3291. */
  3292. Matrix.prototype.getHashCode = function () {
  3293. var hash = this.m[0] || 0;
  3294. for (var i = 1; i < 16; i++) {
  3295. hash = (hash * 397) ^ (this.m[i] || 0);
  3296. }
  3297. return hash;
  3298. };
  3299. /**
  3300. * Decomposes the current Matrix into :
  3301. * - a scale vector3 passed as a reference to update,
  3302. * - a rotation quaternion passed as a reference to update,
  3303. * - a translation vector3 passed as a reference to update.
  3304. * Returns the boolean `true`.
  3305. */
  3306. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3307. translation.x = this.m[12];
  3308. translation.y = this.m[13];
  3309. translation.z = this.m[14];
  3310. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3311. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3312. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3313. if (this.determinant() <= 0) {
  3314. scale.y *= -1;
  3315. }
  3316. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3317. rotation.x = 0;
  3318. rotation.y = 0;
  3319. rotation.z = 0;
  3320. rotation.w = 1;
  3321. return false;
  3322. }
  3323. 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]);
  3324. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3325. return true;
  3326. };
  3327. /**
  3328. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3329. */
  3330. Matrix.prototype.getRotationMatrix = function () {
  3331. var result = Matrix.Identity();
  3332. this.getRotationMatrixToRef(result);
  3333. return result;
  3334. };
  3335. /**
  3336. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3337. * Returns the current Matrix.
  3338. */
  3339. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3340. var m = this.m;
  3341. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3342. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3343. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3344. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3345. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3346. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3347. 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);
  3348. return this;
  3349. };
  3350. // Statics
  3351. /**
  3352. * Returns a new Matrix set from the starting index of the passed array.
  3353. */
  3354. Matrix.FromArray = function (array, offset) {
  3355. var result = new Matrix();
  3356. if (!offset) {
  3357. offset = 0;
  3358. }
  3359. Matrix.FromArrayToRef(array, offset, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the passed "result" matrix from the starting index of the passed array.
  3364. */
  3365. Matrix.FromArrayToRef = function (array, offset, result) {
  3366. for (var index = 0; index < 16; index++) {
  3367. result.m[index] = array[index + offset];
  3368. }
  3369. result._markAsUpdated();
  3370. };
  3371. /**
  3372. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3373. */
  3374. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3375. for (var index = 0; index < 16; index++) {
  3376. result.m[index] = array[index + offset] * scale;
  3377. }
  3378. result._markAsUpdated();
  3379. };
  3380. /**
  3381. * Sets the passed matrix "result" with the 16 passed floats.
  3382. */
  3383. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3384. result.m[0] = initialM11;
  3385. result.m[1] = initialM12;
  3386. result.m[2] = initialM13;
  3387. result.m[3] = initialM14;
  3388. result.m[4] = initialM21;
  3389. result.m[5] = initialM22;
  3390. result.m[6] = initialM23;
  3391. result.m[7] = initialM24;
  3392. result.m[8] = initialM31;
  3393. result.m[9] = initialM32;
  3394. result.m[10] = initialM33;
  3395. result.m[11] = initialM34;
  3396. result.m[12] = initialM41;
  3397. result.m[13] = initialM42;
  3398. result.m[14] = initialM43;
  3399. result.m[15] = initialM44;
  3400. result._markAsUpdated();
  3401. };
  3402. /**
  3403. * Returns the index-th row of the current matrix as a new Vector4.
  3404. */
  3405. Matrix.prototype.getRow = function (index) {
  3406. if (index < 0 || index > 3) {
  3407. return null;
  3408. }
  3409. var i = index * 4;
  3410. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3411. };
  3412. /**
  3413. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3414. * Returns the updated Matrix.
  3415. */
  3416. Matrix.prototype.setRow = function (index, row) {
  3417. if (index < 0 || index > 3) {
  3418. return this;
  3419. }
  3420. var i = index * 4;
  3421. this.m[i + 0] = row.x;
  3422. this.m[i + 1] = row.y;
  3423. this.m[i + 2] = row.z;
  3424. this.m[i + 3] = row.w;
  3425. this._markAsUpdated();
  3426. return this;
  3427. };
  3428. /**
  3429. * Compute the transpose of the matrix.
  3430. * Returns a new Matrix.
  3431. */
  3432. Matrix.prototype.transpose = function () {
  3433. return Matrix.Transpose(this);
  3434. };
  3435. /**
  3436. * Compute the transpose of the matrix.
  3437. * Returns the current matrix.
  3438. */
  3439. Matrix.prototype.transposeToRef = function (result) {
  3440. Matrix.TransposeToRef(this, result);
  3441. return this;
  3442. };
  3443. /**
  3444. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3445. * Returns the updated Matrix.
  3446. */
  3447. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3448. if (index < 0 || index > 3) {
  3449. return this;
  3450. }
  3451. var i = index * 4;
  3452. this.m[i + 0] = x;
  3453. this.m[i + 1] = y;
  3454. this.m[i + 2] = z;
  3455. this.m[i + 3] = w;
  3456. this._markAsUpdated();
  3457. return this;
  3458. };
  3459. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3460. /**
  3461. * Static identity matrix to be used as readonly matrix
  3462. * Must not be updated.
  3463. */
  3464. get: function () {
  3465. return Matrix._identityReadOnly;
  3466. },
  3467. enumerable: true,
  3468. configurable: true
  3469. });
  3470. /**
  3471. * Returns a new Matrix set from the 16 passed floats.
  3472. */
  3473. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3474. var result = new Matrix();
  3475. result.m[0] = initialM11;
  3476. result.m[1] = initialM12;
  3477. result.m[2] = initialM13;
  3478. result.m[3] = initialM14;
  3479. result.m[4] = initialM21;
  3480. result.m[5] = initialM22;
  3481. result.m[6] = initialM23;
  3482. result.m[7] = initialM24;
  3483. result.m[8] = initialM31;
  3484. result.m[9] = initialM32;
  3485. result.m[10] = initialM33;
  3486. result.m[11] = initialM34;
  3487. result.m[12] = initialM41;
  3488. result.m[13] = initialM42;
  3489. result.m[14] = initialM43;
  3490. result.m[15] = initialM44;
  3491. return result;
  3492. };
  3493. /**
  3494. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3495. */
  3496. Matrix.Compose = function (scale, rotation, translation) {
  3497. var result = Matrix.Identity();
  3498. Matrix.ComposeToRef(scale, rotation, translation, result);
  3499. return result;
  3500. };
  3501. /**
  3502. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3503. */
  3504. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3505. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3506. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3507. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3508. result.setTranslation(translation);
  3509. };
  3510. /**
  3511. * Returns a new indentity Matrix.
  3512. */
  3513. Matrix.Identity = function () {
  3514. 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);
  3515. };
  3516. /**
  3517. * Sets the passed "result" as an identity matrix.
  3518. */
  3519. Matrix.IdentityToRef = function (result) {
  3520. 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);
  3521. };
  3522. /**
  3523. * Returns a new zero Matrix.
  3524. */
  3525. Matrix.Zero = function () {
  3526. 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);
  3527. };
  3528. /**
  3529. * Returns a new rotation matrix for "angle" radians around the X axis.
  3530. */
  3531. Matrix.RotationX = function (angle) {
  3532. var result = new Matrix();
  3533. Matrix.RotationXToRef(angle, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Returns a new Matrix as the passed inverted one.
  3538. */
  3539. Matrix.Invert = function (source) {
  3540. var result = new Matrix();
  3541. source.invertToRef(result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3546. */
  3547. Matrix.RotationXToRef = function (angle, result) {
  3548. var s = Math.sin(angle);
  3549. var c = Math.cos(angle);
  3550. result.m[0] = 1.0;
  3551. result.m[15] = 1.0;
  3552. result.m[5] = c;
  3553. result.m[10] = c;
  3554. result.m[9] = -s;
  3555. result.m[6] = s;
  3556. result.m[1] = 0.0;
  3557. result.m[2] = 0.0;
  3558. result.m[3] = 0.0;
  3559. result.m[4] = 0.0;
  3560. result.m[7] = 0.0;
  3561. result.m[8] = 0.0;
  3562. result.m[11] = 0.0;
  3563. result.m[12] = 0.0;
  3564. result.m[13] = 0.0;
  3565. result.m[14] = 0.0;
  3566. result._markAsUpdated();
  3567. };
  3568. /**
  3569. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3570. */
  3571. Matrix.RotationY = function (angle) {
  3572. var result = new Matrix();
  3573. Matrix.RotationYToRef(angle, result);
  3574. return result;
  3575. };
  3576. /**
  3577. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3578. */
  3579. Matrix.RotationYToRef = function (angle, result) {
  3580. var s = Math.sin(angle);
  3581. var c = Math.cos(angle);
  3582. result.m[5] = 1.0;
  3583. result.m[15] = 1.0;
  3584. result.m[0] = c;
  3585. result.m[2] = -s;
  3586. result.m[8] = s;
  3587. result.m[10] = c;
  3588. result.m[1] = 0.0;
  3589. result.m[3] = 0.0;
  3590. result.m[4] = 0.0;
  3591. result.m[6] = 0.0;
  3592. result.m[7] = 0.0;
  3593. result.m[9] = 0.0;
  3594. result.m[11] = 0.0;
  3595. result.m[12] = 0.0;
  3596. result.m[13] = 0.0;
  3597. result.m[14] = 0.0;
  3598. result._markAsUpdated();
  3599. };
  3600. /**
  3601. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3602. */
  3603. Matrix.RotationZ = function (angle) {
  3604. var result = new Matrix();
  3605. Matrix.RotationZToRef(angle, result);
  3606. return result;
  3607. };
  3608. /**
  3609. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3610. */
  3611. Matrix.RotationZToRef = function (angle, result) {
  3612. var s = Math.sin(angle);
  3613. var c = Math.cos(angle);
  3614. result.m[10] = 1.0;
  3615. result.m[15] = 1.0;
  3616. result.m[0] = c;
  3617. result.m[1] = s;
  3618. result.m[4] = -s;
  3619. result.m[5] = c;
  3620. result.m[2] = 0.0;
  3621. result.m[3] = 0.0;
  3622. result.m[6] = 0.0;
  3623. result.m[7] = 0.0;
  3624. result.m[8] = 0.0;
  3625. result.m[9] = 0.0;
  3626. result.m[11] = 0.0;
  3627. result.m[12] = 0.0;
  3628. result.m[13] = 0.0;
  3629. result.m[14] = 0.0;
  3630. result._markAsUpdated();
  3631. };
  3632. /**
  3633. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3634. */
  3635. Matrix.RotationAxis = function (axis, angle) {
  3636. var result = Matrix.Zero();
  3637. Matrix.RotationAxisToRef(axis, angle, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3642. */
  3643. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3644. var s = Math.sin(-angle);
  3645. var c = Math.cos(-angle);
  3646. var c1 = 1 - c;
  3647. axis.normalize();
  3648. result.m[0] = (axis.x * axis.x) * c1 + c;
  3649. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3650. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3651. result.m[3] = 0.0;
  3652. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3653. result.m[5] = (axis.y * axis.y) * c1 + c;
  3654. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3655. result.m[7] = 0.0;
  3656. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3657. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3658. result.m[10] = (axis.z * axis.z) * c1 + c;
  3659. result.m[11] = 0.0;
  3660. result.m[15] = 1.0;
  3661. result._markAsUpdated();
  3662. };
  3663. /**
  3664. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3665. */
  3666. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3667. var result = new Matrix();
  3668. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3669. return result;
  3670. };
  3671. /**
  3672. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3673. */
  3674. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3675. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3676. this._tempQuaternion.toRotationMatrix(result);
  3677. };
  3678. /**
  3679. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3680. */
  3681. Matrix.Scaling = function (x, y, z) {
  3682. var result = Matrix.Zero();
  3683. Matrix.ScalingToRef(x, y, z, result);
  3684. return result;
  3685. };
  3686. /**
  3687. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3688. */
  3689. Matrix.ScalingToRef = function (x, y, z, result) {
  3690. result.m[0] = x;
  3691. result.m[1] = 0.0;
  3692. result.m[2] = 0.0;
  3693. result.m[3] = 0.0;
  3694. result.m[4] = 0.0;
  3695. result.m[5] = y;
  3696. result.m[6] = 0.0;
  3697. result.m[7] = 0.0;
  3698. result.m[8] = 0.0;
  3699. result.m[9] = 0.0;
  3700. result.m[10] = z;
  3701. result.m[11] = 0.0;
  3702. result.m[12] = 0.0;
  3703. result.m[13] = 0.0;
  3704. result.m[14] = 0.0;
  3705. result.m[15] = 1.0;
  3706. result._markAsUpdated();
  3707. };
  3708. /**
  3709. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3710. */
  3711. Matrix.Translation = function (x, y, z) {
  3712. var result = Matrix.Identity();
  3713. Matrix.TranslationToRef(x, y, z, result);
  3714. return result;
  3715. };
  3716. /**
  3717. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3718. */
  3719. Matrix.TranslationToRef = function (x, y, z, result) {
  3720. 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);
  3721. };
  3722. /**
  3723. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3724. */
  3725. Matrix.Lerp = function (startValue, endValue, gradient) {
  3726. var result = Matrix.Zero();
  3727. for (var index = 0; index < 16; index++) {
  3728. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3729. }
  3730. result._markAsUpdated();
  3731. return result;
  3732. };
  3733. /**
  3734. * Returns a new Matrix whose values are computed by :
  3735. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3736. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3737. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3738. */
  3739. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3740. var startScale = new Vector3(0, 0, 0);
  3741. var startRotation = new Quaternion();
  3742. var startTranslation = new Vector3(0, 0, 0);
  3743. startValue.decompose(startScale, startRotation, startTranslation);
  3744. var endScale = new Vector3(0, 0, 0);
  3745. var endRotation = new Quaternion();
  3746. var endTranslation = new Vector3(0, 0, 0);
  3747. endValue.decompose(endScale, endRotation, endTranslation);
  3748. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3749. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3750. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3751. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3752. };
  3753. /**
  3754. * 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".
  3755. * This methods works for a Left-Handed system.
  3756. */
  3757. Matrix.LookAtLH = function (eye, target, up) {
  3758. var result = Matrix.Zero();
  3759. Matrix.LookAtLHToRef(eye, target, up, result);
  3760. return result;
  3761. };
  3762. /**
  3763. * 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".
  3764. * This methods works for a Left-Handed system.
  3765. */
  3766. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3767. // Z axis
  3768. target.subtractToRef(eye, this._zAxis);
  3769. this._zAxis.normalize();
  3770. // X axis
  3771. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3772. if (this._xAxis.lengthSquared() === 0) {
  3773. this._xAxis.x = 1.0;
  3774. }
  3775. else {
  3776. this._xAxis.normalize();
  3777. }
  3778. // Y axis
  3779. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3780. this._yAxis.normalize();
  3781. // Eye angles
  3782. var ex = -Vector3.Dot(this._xAxis, eye);
  3783. var ey = -Vector3.Dot(this._yAxis, eye);
  3784. var ez = -Vector3.Dot(this._zAxis, eye);
  3785. 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);
  3786. };
  3787. /**
  3788. * 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".
  3789. * This methods works for a Right-Handed system.
  3790. */
  3791. Matrix.LookAtRH = function (eye, target, up) {
  3792. var result = Matrix.Zero();
  3793. Matrix.LookAtRHToRef(eye, target, up, result);
  3794. return result;
  3795. };
  3796. /**
  3797. * 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".
  3798. * This methods works for a Left-Handed system.
  3799. */
  3800. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3801. // Z axis
  3802. eye.subtractToRef(target, this._zAxis);
  3803. this._zAxis.normalize();
  3804. // X axis
  3805. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3806. if (this._xAxis.lengthSquared() === 0) {
  3807. this._xAxis.x = 1.0;
  3808. }
  3809. else {
  3810. this._xAxis.normalize();
  3811. }
  3812. // Y axis
  3813. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3814. this._yAxis.normalize();
  3815. // Eye angles
  3816. var ex = -Vector3.Dot(this._xAxis, eye);
  3817. var ey = -Vector3.Dot(this._yAxis, eye);
  3818. var ez = -Vector3.Dot(this._zAxis, eye);
  3819. 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);
  3820. };
  3821. /**
  3822. * 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.
  3823. */
  3824. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3825. var matrix = Matrix.Zero();
  3826. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3827. return matrix;
  3828. };
  3829. /**
  3830. * 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.
  3831. */
  3832. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3833. var n = znear;
  3834. var f = zfar;
  3835. var a = 2.0 / width;
  3836. var b = 2.0 / height;
  3837. var c = 2.0 / (f - n);
  3838. var d = -(f + n) / (f - n);
  3839. BABYLON.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);
  3840. };
  3841. /**
  3842. * 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.
  3843. */
  3844. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3845. var matrix = Matrix.Zero();
  3846. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3847. return matrix;
  3848. };
  3849. /**
  3850. * 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.
  3851. */
  3852. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3853. var n = znear;
  3854. var f = zfar;
  3855. var a = 2.0 / (right - left);
  3856. var b = 2.0 / (top - bottom);
  3857. var c = 2.0 / (f - n);
  3858. var d = -(f + n) / (f - n);
  3859. var i0 = (left + right) / (left - right);
  3860. var i1 = (top + bottom) / (bottom - top);
  3861. BABYLON.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);
  3862. };
  3863. /**
  3864. * 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.
  3865. */
  3866. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3867. var matrix = Matrix.Zero();
  3868. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3869. return matrix;
  3870. };
  3871. /**
  3872. * 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.
  3873. */
  3874. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3875. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3876. result.m[10] *= -1.0;
  3877. };
  3878. /**
  3879. * 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.
  3880. */
  3881. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3882. var matrix = Matrix.Zero();
  3883. var n = znear;
  3884. var f = zfar;
  3885. var a = 2.0 * n / width;
  3886. var b = 2.0 * n / height;
  3887. var c = (f + n) / (f - n);
  3888. var d = -2.0 * f * n / (f - n);
  3889. BABYLON.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);
  3890. return matrix;
  3891. };
  3892. /**
  3893. * 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.
  3894. */
  3895. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3896. var matrix = Matrix.Zero();
  3897. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3898. return matrix;
  3899. };
  3900. /**
  3901. * 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.
  3902. */
  3903. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3904. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3905. var n = znear;
  3906. var f = zfar;
  3907. var t = 1.0 / (Math.tan(fov * 0.5));
  3908. var a = isVerticalFovFixed ? (t / aspect) : t;
  3909. var b = isVerticalFovFixed ? t : (t * aspect);
  3910. var c = (f + n) / (f - n);
  3911. var d = -2.0 * f * n / (f - n);
  3912. BABYLON.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);
  3913. };
  3914. /**
  3915. * 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.
  3916. */
  3917. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3918. var matrix = Matrix.Zero();
  3919. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3920. return matrix;
  3921. };
  3922. /**
  3923. * 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.
  3924. */
  3925. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3926. //alternatively this could be expressed as:
  3927. // m = PerspectiveFovLHToRef
  3928. // m[10] *= -1.0;
  3929. // m[11] *= -1.0;
  3930. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3931. var n = znear;
  3932. var f = zfar;
  3933. var t = 1.0 / (Math.tan(fov * 0.5));
  3934. var a = isVerticalFovFixed ? (t / aspect) : t;
  3935. var b = isVerticalFovFixed ? t : (t * aspect);
  3936. var c = -(f + n) / (f - n);
  3937. var d = -2 * f * n / (f - n);
  3938. BABYLON.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);
  3939. };
  3940. /**
  3941. * 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.
  3942. */
  3943. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3944. if (rightHanded === void 0) { rightHanded = false; }
  3945. var rightHandedFactor = rightHanded ? -1 : 1;
  3946. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3947. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3948. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3949. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3950. var xScale = 2.0 / (leftTan + rightTan);
  3951. var yScale = 2.0 / (upTan + downTan);
  3952. result.m[0] = xScale;
  3953. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3954. result.m[5] = yScale;
  3955. result.m[6] = result.m[7] = 0.0;
  3956. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3957. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3958. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3959. result.m[10] = -zfar / (znear - zfar);
  3960. result.m[11] = 1.0 * rightHandedFactor;
  3961. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3962. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3963. // result.m[14] = (znear * zfar) / (znear - zfar);
  3964. result._markAsUpdated();
  3965. };
  3966. /**
  3967. * Returns the final transformation matrix : world * view * projection * viewport
  3968. */
  3969. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3970. var cw = viewport.width;
  3971. var ch = viewport.height;
  3972. var cx = viewport.x;
  3973. var cy = viewport.y;
  3974. 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);
  3975. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3976. };
  3977. /**
  3978. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3979. */
  3980. Matrix.GetAsMatrix2x2 = function (matrix) {
  3981. return new Float32Array([
  3982. matrix.m[0], matrix.m[1],
  3983. matrix.m[4], matrix.m[5]
  3984. ]);
  3985. };
  3986. /**
  3987. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3988. */
  3989. Matrix.GetAsMatrix3x3 = function (matrix) {
  3990. return new Float32Array([
  3991. matrix.m[0], matrix.m[1], matrix.m[2],
  3992. matrix.m[4], matrix.m[5], matrix.m[6],
  3993. matrix.m[8], matrix.m[9], matrix.m[10]
  3994. ]);
  3995. };
  3996. /**
  3997. * Compute the transpose of the passed Matrix.
  3998. * Returns a new Matrix.
  3999. */
  4000. Matrix.Transpose = function (matrix) {
  4001. var result = new Matrix();
  4002. Matrix.TransposeToRef(matrix, result);
  4003. return result;
  4004. };
  4005. /**
  4006. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4007. */
  4008. Matrix.TransposeToRef = function (matrix, result) {
  4009. result.m[0] = matrix.m[0];
  4010. result.m[1] = matrix.m[4];
  4011. result.m[2] = matrix.m[8];
  4012. result.m[3] = matrix.m[12];
  4013. result.m[4] = matrix.m[1];
  4014. result.m[5] = matrix.m[5];
  4015. result.m[6] = matrix.m[9];
  4016. result.m[7] = matrix.m[13];
  4017. result.m[8] = matrix.m[2];
  4018. result.m[9] = matrix.m[6];
  4019. result.m[10] = matrix.m[10];
  4020. result.m[11] = matrix.m[14];
  4021. result.m[12] = matrix.m[3];
  4022. result.m[13] = matrix.m[7];
  4023. result.m[14] = matrix.m[11];
  4024. result.m[15] = matrix.m[15];
  4025. };
  4026. /**
  4027. * Returns a new Matrix as the reflection matrix across the passed plane.
  4028. */
  4029. Matrix.Reflection = function (plane) {
  4030. var matrix = new Matrix();
  4031. Matrix.ReflectionToRef(plane, matrix);
  4032. return matrix;
  4033. };
  4034. /**
  4035. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4036. */
  4037. Matrix.ReflectionToRef = function (plane, result) {
  4038. plane.normalize();
  4039. var x = plane.normal.x;
  4040. var y = plane.normal.y;
  4041. var z = plane.normal.z;
  4042. var temp = -2 * x;
  4043. var temp2 = -2 * y;
  4044. var temp3 = -2 * z;
  4045. result.m[0] = (temp * x) + 1;
  4046. result.m[1] = temp2 * x;
  4047. result.m[2] = temp3 * x;
  4048. result.m[3] = 0.0;
  4049. result.m[4] = temp * y;
  4050. result.m[5] = (temp2 * y) + 1;
  4051. result.m[6] = temp3 * y;
  4052. result.m[7] = 0.0;
  4053. result.m[8] = temp * z;
  4054. result.m[9] = temp2 * z;
  4055. result.m[10] = (temp3 * z) + 1;
  4056. result.m[11] = 0.0;
  4057. result.m[12] = temp * plane.d;
  4058. result.m[13] = temp2 * plane.d;
  4059. result.m[14] = temp3 * plane.d;
  4060. result.m[15] = 1.0;
  4061. result._markAsUpdated();
  4062. };
  4063. /**
  4064. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4065. */
  4066. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4067. result.m[0] = xaxis.x;
  4068. result.m[1] = xaxis.y;
  4069. result.m[2] = xaxis.z;
  4070. result.m[3] = 0.0;
  4071. result.m[4] = yaxis.x;
  4072. result.m[5] = yaxis.y;
  4073. result.m[6] = yaxis.z;
  4074. result.m[7] = 0.0;
  4075. result.m[8] = zaxis.x;
  4076. result.m[9] = zaxis.y;
  4077. result.m[10] = zaxis.z;
  4078. result.m[11] = 0.0;
  4079. result.m[12] = 0.0;
  4080. result.m[13] = 0.0;
  4081. result.m[14] = 0.0;
  4082. result.m[15] = 1.0;
  4083. result._markAsUpdated();
  4084. };
  4085. /**
  4086. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4087. */
  4088. Matrix.FromQuaternionToRef = function (quat, result) {
  4089. var xx = quat.x * quat.x;
  4090. var yy = quat.y * quat.y;
  4091. var zz = quat.z * quat.z;
  4092. var xy = quat.x * quat.y;
  4093. var zw = quat.z * quat.w;
  4094. var zx = quat.z * quat.x;
  4095. var yw = quat.y * quat.w;
  4096. var yz = quat.y * quat.z;
  4097. var xw = quat.x * quat.w;
  4098. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4099. result.m[1] = 2.0 * (xy + zw);
  4100. result.m[2] = 2.0 * (zx - yw);
  4101. result.m[3] = 0.0;
  4102. result.m[4] = 2.0 * (xy - zw);
  4103. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4104. result.m[6] = 2.0 * (yz + xw);
  4105. result.m[7] = 0.0;
  4106. result.m[8] = 2.0 * (zx + yw);
  4107. result.m[9] = 2.0 * (yz - xw);
  4108. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4109. result.m[11] = 0.0;
  4110. result.m[12] = 0.0;
  4111. result.m[13] = 0.0;
  4112. result.m[14] = 0.0;
  4113. result.m[15] = 1.0;
  4114. result._markAsUpdated();
  4115. };
  4116. Matrix._tempQuaternion = new Quaternion();
  4117. Matrix._xAxis = Vector3.Zero();
  4118. Matrix._yAxis = Vector3.Zero();
  4119. Matrix._zAxis = Vector3.Zero();
  4120. Matrix._updateFlagSeed = 0;
  4121. Matrix._identityReadOnly = Matrix.Identity();
  4122. return Matrix;
  4123. }());
  4124. BABYLON.Matrix = Matrix;
  4125. var Plane = /** @class */ (function () {
  4126. /**
  4127. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4128. */
  4129. function Plane(a, b, c, d) {
  4130. this.normal = new Vector3(a, b, c);
  4131. this.d = d;
  4132. }
  4133. /**
  4134. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4135. */
  4136. Plane.prototype.asArray = function () {
  4137. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4138. };
  4139. // Methods
  4140. /**
  4141. * Returns a new plane copied from the current Plane.
  4142. */
  4143. Plane.prototype.clone = function () {
  4144. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4145. };
  4146. /**
  4147. * Returns the string "Plane".
  4148. */
  4149. Plane.prototype.getClassName = function () {
  4150. return "Plane";
  4151. };
  4152. /**
  4153. * Returns the Plane hash code.
  4154. */
  4155. Plane.prototype.getHashCode = function () {
  4156. var hash = this.normal.getHashCode();
  4157. hash = (hash * 397) ^ (this.d || 0);
  4158. return hash;
  4159. };
  4160. /**
  4161. * Normalize the current Plane in place.
  4162. * Returns the updated Plane.
  4163. */
  4164. Plane.prototype.normalize = function () {
  4165. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4166. var magnitude = 0.0;
  4167. if (norm !== 0) {
  4168. magnitude = 1.0 / norm;
  4169. }
  4170. this.normal.x *= magnitude;
  4171. this.normal.y *= magnitude;
  4172. this.normal.z *= magnitude;
  4173. this.d *= magnitude;
  4174. return this;
  4175. };
  4176. /**
  4177. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4178. */
  4179. Plane.prototype.transform = function (transformation) {
  4180. var transposedMatrix = Matrix.Transpose(transformation);
  4181. var x = this.normal.x;
  4182. var y = this.normal.y;
  4183. var z = this.normal.z;
  4184. var d = this.d;
  4185. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4186. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4187. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4188. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4189. return new Plane(normalX, normalY, normalZ, finalD);
  4190. };
  4191. /**
  4192. * Returns the dot product (float) of the point coordinates and the plane normal.
  4193. */
  4194. Plane.prototype.dotCoordinate = function (point) {
  4195. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4196. };
  4197. /**
  4198. * Updates the current Plane from the plane defined by the three passed points.
  4199. * Returns the updated Plane.
  4200. */
  4201. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4202. var x1 = point2.x - point1.x;
  4203. var y1 = point2.y - point1.y;
  4204. var z1 = point2.z - point1.z;
  4205. var x2 = point3.x - point1.x;
  4206. var y2 = point3.y - point1.y;
  4207. var z2 = point3.z - point1.z;
  4208. var yz = (y1 * z2) - (z1 * y2);
  4209. var xz = (z1 * x2) - (x1 * z2);
  4210. var xy = (x1 * y2) - (y1 * x2);
  4211. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4212. var invPyth;
  4213. if (pyth !== 0) {
  4214. invPyth = 1.0 / pyth;
  4215. }
  4216. else {
  4217. invPyth = 0.0;
  4218. }
  4219. this.normal.x = yz * invPyth;
  4220. this.normal.y = xz * invPyth;
  4221. this.normal.z = xy * invPyth;
  4222. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4223. return this;
  4224. };
  4225. /**
  4226. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4227. */
  4228. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4229. var dot = Vector3.Dot(this.normal, direction);
  4230. return (dot <= epsilon);
  4231. };
  4232. /**
  4233. * Returns the signed distance (float) from the passed point to the Plane.
  4234. */
  4235. Plane.prototype.signedDistanceTo = function (point) {
  4236. return Vector3.Dot(point, this.normal) + this.d;
  4237. };
  4238. // Statics
  4239. /**
  4240. * Returns a new Plane from the passed array.
  4241. */
  4242. Plane.FromArray = function (array) {
  4243. return new Plane(array[0], array[1], array[2], array[3]);
  4244. };
  4245. /**
  4246. * Returns a new Plane defined by the three passed points.
  4247. */
  4248. Plane.FromPoints = function (point1, point2, point3) {
  4249. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4250. result.copyFromPoints(point1, point2, point3);
  4251. return result;
  4252. };
  4253. /**
  4254. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4255. * Note : the vector "normal" is updated because normalized.
  4256. */
  4257. Plane.FromPositionAndNormal = function (origin, normal) {
  4258. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4259. normal.normalize();
  4260. result.normal = normal;
  4261. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4262. return result;
  4263. };
  4264. /**
  4265. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4266. */
  4267. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4268. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4269. return Vector3.Dot(point, normal) + d;
  4270. };
  4271. return Plane;
  4272. }());
  4273. BABYLON.Plane = Plane;
  4274. var Viewport = /** @class */ (function () {
  4275. /**
  4276. * Creates a Viewport object located at (x, y) and sized (width, height).
  4277. */
  4278. function Viewport(x, y, width, height) {
  4279. this.x = x;
  4280. this.y = y;
  4281. this.width = width;
  4282. this.height = height;
  4283. }
  4284. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4285. if (renderWidthOrEngine.getRenderWidth) {
  4286. var engine = renderWidthOrEngine;
  4287. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4288. }
  4289. var renderWidth = renderWidthOrEngine;
  4290. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4291. };
  4292. /**
  4293. * Returns a new Viewport copied from the current one.
  4294. */
  4295. Viewport.prototype.clone = function () {
  4296. return new Viewport(this.x, this.y, this.width, this.height);
  4297. };
  4298. return Viewport;
  4299. }());
  4300. BABYLON.Viewport = Viewport;
  4301. var Frustum = /** @class */ (function () {
  4302. function Frustum() {
  4303. }
  4304. /**
  4305. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4306. */
  4307. Frustum.GetPlanes = function (transform) {
  4308. var frustumPlanes = [];
  4309. for (var index = 0; index < 6; index++) {
  4310. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4311. }
  4312. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4313. return frustumPlanes;
  4314. };
  4315. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4316. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4317. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4318. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4319. frustumPlane.d = transform.m[15] + transform.m[14];
  4320. frustumPlane.normalize();
  4321. };
  4322. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4323. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4324. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4325. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4326. frustumPlane.d = transform.m[15] - transform.m[14];
  4327. frustumPlane.normalize();
  4328. };
  4329. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4330. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4331. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4332. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4333. frustumPlane.d = transform.m[15] + transform.m[12];
  4334. frustumPlane.normalize();
  4335. };
  4336. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4337. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4338. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4339. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4340. frustumPlane.d = transform.m[15] - transform.m[12];
  4341. frustumPlane.normalize();
  4342. };
  4343. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4344. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4345. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4346. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4347. frustumPlane.d = transform.m[15] - transform.m[13];
  4348. frustumPlane.normalize();
  4349. };
  4350. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4351. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4352. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4353. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4354. frustumPlane.d = transform.m[15] + transform.m[13];
  4355. frustumPlane.normalize();
  4356. };
  4357. /**
  4358. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4359. */
  4360. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4361. // Near
  4362. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4363. // Far
  4364. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4365. // Left
  4366. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4367. // Right
  4368. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4369. // Top
  4370. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4371. // Bottom
  4372. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4373. };
  4374. return Frustum;
  4375. }());
  4376. BABYLON.Frustum = Frustum;
  4377. var Space;
  4378. (function (Space) {
  4379. Space[Space["LOCAL"] = 0] = "LOCAL";
  4380. Space[Space["WORLD"] = 1] = "WORLD";
  4381. Space[Space["BONE"] = 2] = "BONE";
  4382. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4383. var Axis = /** @class */ (function () {
  4384. function Axis() {
  4385. }
  4386. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4387. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4388. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4389. return Axis;
  4390. }());
  4391. BABYLON.Axis = Axis;
  4392. ;
  4393. var BezierCurve = /** @class */ (function () {
  4394. function BezierCurve() {
  4395. }
  4396. /**
  4397. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4398. */
  4399. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4400. // Extract X (which is equal to time here)
  4401. var f0 = 1 - 3 * x2 + 3 * x1;
  4402. var f1 = 3 * x2 - 6 * x1;
  4403. var f2 = 3 * x1;
  4404. var refinedT = t;
  4405. for (var i = 0; i < 5; i++) {
  4406. var refinedT2 = refinedT * refinedT;
  4407. var refinedT3 = refinedT2 * refinedT;
  4408. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4409. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4410. refinedT -= (x - t) * slope;
  4411. refinedT = Math.min(1, Math.max(0, refinedT));
  4412. }
  4413. // Resolve cubic bezier for the given x
  4414. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4415. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4416. Math.pow(refinedT, 3);
  4417. };
  4418. return BezierCurve;
  4419. }());
  4420. BABYLON.BezierCurve = BezierCurve;
  4421. var Orientation;
  4422. (function (Orientation) {
  4423. Orientation[Orientation["CW"] = 0] = "CW";
  4424. Orientation[Orientation["CCW"] = 1] = "CCW";
  4425. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4426. var Angle = /** @class */ (function () {
  4427. /**
  4428. * Creates an Angle object of "radians" radians (float).
  4429. */
  4430. function Angle(radians) {
  4431. var _this = this;
  4432. /**
  4433. * Returns the Angle value in degrees (float).
  4434. */
  4435. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4436. /**
  4437. * Returns the Angle value in radians (float).
  4438. */
  4439. this.radians = function () { return _this._radians; };
  4440. this._radians = radians;
  4441. if (this._radians < 0.0)
  4442. this._radians += (2.0 * Math.PI);
  4443. }
  4444. /**
  4445. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4446. */
  4447. Angle.BetweenTwoPoints = function (a, b) {
  4448. var delta = b.subtract(a);
  4449. var theta = Math.atan2(delta.y, delta.x);
  4450. return new Angle(theta);
  4451. };
  4452. /**
  4453. * Returns a new Angle object from the passed float in radians.
  4454. */
  4455. Angle.FromRadians = function (radians) {
  4456. return new Angle(radians);
  4457. };
  4458. /**
  4459. * Returns a new Angle object from the passed float in degrees.
  4460. */
  4461. Angle.FromDegrees = function (degrees) {
  4462. return new Angle(degrees * Math.PI / 180.0);
  4463. };
  4464. return Angle;
  4465. }());
  4466. BABYLON.Angle = Angle;
  4467. var Arc2 = /** @class */ (function () {
  4468. /**
  4469. * Creates an Arc object from the three passed points : start, middle and end.
  4470. */
  4471. function Arc2(startPoint, midPoint, endPoint) {
  4472. this.startPoint = startPoint;
  4473. this.midPoint = midPoint;
  4474. this.endPoint = endPoint;
  4475. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4476. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4477. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4478. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4479. 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);
  4480. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4481. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4482. var a1 = this.startAngle.degrees();
  4483. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4484. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4485. // angles correction
  4486. if (a2 - a1 > +180.0)
  4487. a2 -= 360.0;
  4488. if (a2 - a1 < -180.0)
  4489. a2 += 360.0;
  4490. if (a3 - a2 > +180.0)
  4491. a3 -= 360.0;
  4492. if (a3 - a2 < -180.0)
  4493. a3 += 360.0;
  4494. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4495. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4496. }
  4497. return Arc2;
  4498. }());
  4499. BABYLON.Arc2 = Arc2;
  4500. var Path2 = /** @class */ (function () {
  4501. /**
  4502. * Creates a Path2 object from the starting 2D coordinates x and y.
  4503. */
  4504. function Path2(x, y) {
  4505. this._points = new Array();
  4506. this._length = 0.0;
  4507. this.closed = false;
  4508. this._points.push(new Vector2(x, y));
  4509. }
  4510. /**
  4511. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4512. * Returns the updated Path2.
  4513. */
  4514. Path2.prototype.addLineTo = function (x, y) {
  4515. if (closed) {
  4516. //Tools.Error("cannot add lines to closed paths");
  4517. return this;
  4518. }
  4519. var newPoint = new Vector2(x, y);
  4520. var previousPoint = this._points[this._points.length - 1];
  4521. this._points.push(newPoint);
  4522. this._length += newPoint.subtract(previousPoint).length();
  4523. return this;
  4524. };
  4525. /**
  4526. * 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.
  4527. * Returns the updated Path2.
  4528. */
  4529. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4530. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4531. if (closed) {
  4532. //Tools.Error("cannot add arcs to closed paths");
  4533. return this;
  4534. }
  4535. var startPoint = this._points[this._points.length - 1];
  4536. var midPoint = new Vector2(midX, midY);
  4537. var endPoint = new Vector2(endX, endY);
  4538. var arc = new Arc2(startPoint, midPoint, endPoint);
  4539. var increment = arc.angle.radians() / numberOfSegments;
  4540. if (arc.orientation === Orientation.CW)
  4541. increment *= -1;
  4542. var currentAngle = arc.startAngle.radians() + increment;
  4543. for (var i = 0; i < numberOfSegments; i++) {
  4544. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4545. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4546. this.addLineTo(x, y);
  4547. currentAngle += increment;
  4548. }
  4549. return this;
  4550. };
  4551. /**
  4552. * Closes the Path2.
  4553. * Returns the Path2.
  4554. */
  4555. Path2.prototype.close = function () {
  4556. this.closed = true;
  4557. return this;
  4558. };
  4559. /**
  4560. * Returns the Path2 total length (float).
  4561. */
  4562. Path2.prototype.length = function () {
  4563. var result = this._length;
  4564. if (!this.closed) {
  4565. var lastPoint = this._points[this._points.length - 1];
  4566. var firstPoint = this._points[0];
  4567. result += (firstPoint.subtract(lastPoint).length());
  4568. }
  4569. return result;
  4570. };
  4571. /**
  4572. * Returns the Path2 internal array of points.
  4573. */
  4574. Path2.prototype.getPoints = function () {
  4575. return this._points;
  4576. };
  4577. /**
  4578. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4579. */
  4580. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4581. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4582. //Tools.Error("normalized length position should be between 0 and 1.");
  4583. return Vector2.Zero();
  4584. }
  4585. var lengthPosition = normalizedLengthPosition * this.length();
  4586. var previousOffset = 0;
  4587. for (var i = 0; i < this._points.length; i++) {
  4588. var j = (i + 1) % this._points.length;
  4589. var a = this._points[i];
  4590. var b = this._points[j];
  4591. var bToA = b.subtract(a);
  4592. var nextOffset = (bToA.length() + previousOffset);
  4593. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4594. var dir = bToA.normalize();
  4595. var localOffset = lengthPosition - previousOffset;
  4596. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4597. }
  4598. previousOffset = nextOffset;
  4599. }
  4600. //Tools.Error("internal error");
  4601. return Vector2.Zero();
  4602. };
  4603. /**
  4604. * Returns a new Path2 starting at the coordinates (x, y).
  4605. */
  4606. Path2.StartingAt = function (x, y) {
  4607. return new Path2(x, y);
  4608. };
  4609. return Path2;
  4610. }());
  4611. BABYLON.Path2 = Path2;
  4612. var Path3D = /** @class */ (function () {
  4613. /**
  4614. * new Path3D(path, normal, raw)
  4615. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4616. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4617. * path : an array of Vector3, the curve axis of the Path3D
  4618. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4619. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4620. */
  4621. function Path3D(path, firstNormal, raw) {
  4622. if (firstNormal === void 0) { firstNormal = null; }
  4623. this.path = path;
  4624. this._curve = new Array();
  4625. this._distances = new Array();
  4626. this._tangents = new Array();
  4627. this._normals = new Array();
  4628. this._binormals = new Array();
  4629. for (var p = 0; p < path.length; p++) {
  4630. this._curve[p] = path[p].clone(); // hard copy
  4631. }
  4632. this._raw = raw || false;
  4633. this._compute(firstNormal);
  4634. }
  4635. /**
  4636. * Returns the Path3D array of successive Vector3 designing its curve.
  4637. */
  4638. Path3D.prototype.getCurve = function () {
  4639. return this._curve;
  4640. };
  4641. /**
  4642. * Returns an array populated with tangent vectors on each Path3D curve point.
  4643. */
  4644. Path3D.prototype.getTangents = function () {
  4645. return this._tangents;
  4646. };
  4647. /**
  4648. * Returns an array populated with normal vectors on each Path3D curve point.
  4649. */
  4650. Path3D.prototype.getNormals = function () {
  4651. return this._normals;
  4652. };
  4653. /**
  4654. * Returns an array populated with binormal vectors on each Path3D curve point.
  4655. */
  4656. Path3D.prototype.getBinormals = function () {
  4657. return this._binormals;
  4658. };
  4659. /**
  4660. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4661. */
  4662. Path3D.prototype.getDistances = function () {
  4663. return this._distances;
  4664. };
  4665. /**
  4666. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4667. * Returns the same object updated.
  4668. */
  4669. Path3D.prototype.update = function (path, firstNormal) {
  4670. if (firstNormal === void 0) { firstNormal = null; }
  4671. for (var p = 0; p < path.length; p++) {
  4672. this._curve[p].x = path[p].x;
  4673. this._curve[p].y = path[p].y;
  4674. this._curve[p].z = path[p].z;
  4675. }
  4676. this._compute(firstNormal);
  4677. return this;
  4678. };
  4679. // private function compute() : computes tangents, normals and binormals
  4680. Path3D.prototype._compute = function (firstNormal) {
  4681. var l = this._curve.length;
  4682. // first and last tangents
  4683. this._tangents[0] = this._getFirstNonNullVector(0);
  4684. if (!this._raw) {
  4685. this._tangents[0].normalize();
  4686. }
  4687. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4688. if (!this._raw) {
  4689. this._tangents[l - 1].normalize();
  4690. }
  4691. // normals and binormals at first point : arbitrary vector with _normalVector()
  4692. var tg0 = this._tangents[0];
  4693. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4694. this._normals[0] = pp0;
  4695. if (!this._raw) {
  4696. this._normals[0].normalize();
  4697. }
  4698. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4699. if (!this._raw) {
  4700. this._binormals[0].normalize();
  4701. }
  4702. this._distances[0] = 0.0;
  4703. // normals and binormals : next points
  4704. var prev; // previous vector (segment)
  4705. var cur; // current vector (segment)
  4706. var curTang; // current tangent
  4707. // previous normal
  4708. var prevBinor; // previous binormal
  4709. for (var i = 1; i < l; i++) {
  4710. // tangents
  4711. prev = this._getLastNonNullVector(i);
  4712. if (i < l - 1) {
  4713. cur = this._getFirstNonNullVector(i);
  4714. this._tangents[i] = prev.add(cur);
  4715. this._tangents[i].normalize();
  4716. }
  4717. this._distances[i] = this._distances[i - 1] + prev.length();
  4718. // normals and binormals
  4719. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4720. curTang = this._tangents[i];
  4721. prevBinor = this._binormals[i - 1];
  4722. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4723. if (!this._raw) {
  4724. this._normals[i].normalize();
  4725. }
  4726. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4727. if (!this._raw) {
  4728. this._binormals[i].normalize();
  4729. }
  4730. }
  4731. };
  4732. // private function getFirstNonNullVector(index)
  4733. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4734. Path3D.prototype._getFirstNonNullVector = function (index) {
  4735. var i = 1;
  4736. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4737. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4738. i++;
  4739. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4740. }
  4741. return nNVector;
  4742. };
  4743. // private function getLastNonNullVector(index)
  4744. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4745. Path3D.prototype._getLastNonNullVector = function (index) {
  4746. var i = 1;
  4747. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4748. while (nLVector.length() === 0 && index > i + 1) {
  4749. i++;
  4750. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4751. }
  4752. return nLVector;
  4753. };
  4754. // private function normalVector(v0, vt, va) :
  4755. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4756. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4757. Path3D.prototype._normalVector = function (v0, vt, va) {
  4758. var normal0;
  4759. var tgl = vt.length();
  4760. if (tgl === 0.0) {
  4761. tgl = 1.0;
  4762. }
  4763. if (va === undefined || va === null) {
  4764. var point;
  4765. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4766. point = new Vector3(0.0, -1.0, 0.0);
  4767. }
  4768. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4769. point = new Vector3(1.0, 0.0, 0.0);
  4770. }
  4771. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4772. point = new Vector3(0.0, 0.0, 1.0);
  4773. }
  4774. else {
  4775. point = Vector3.Zero();
  4776. }
  4777. normal0 = Vector3.Cross(vt, point);
  4778. }
  4779. else {
  4780. normal0 = Vector3.Cross(vt, va);
  4781. Vector3.CrossToRef(normal0, vt, normal0);
  4782. }
  4783. normal0.normalize();
  4784. return normal0;
  4785. };
  4786. return Path3D;
  4787. }());
  4788. BABYLON.Path3D = Path3D;
  4789. var Curve3 = /** @class */ (function () {
  4790. /**
  4791. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4792. * A Curve3 is designed from a series of successive Vector3.
  4793. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4794. */
  4795. function Curve3(points) {
  4796. this._length = 0.0;
  4797. this._points = points;
  4798. this._length = this._computeLength(points);
  4799. }
  4800. /**
  4801. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4802. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4803. * @param v1 (Vector3) the control point
  4804. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4805. * @param nbPoints (integer) the wanted number of points in the curve
  4806. */
  4807. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4808. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4809. var bez = new Array();
  4810. var equation = function (t, val0, val1, val2) {
  4811. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4812. return res;
  4813. };
  4814. for (var i = 0; i <= nbPoints; i++) {
  4815. 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)));
  4816. }
  4817. return new Curve3(bez);
  4818. };
  4819. /**
  4820. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4821. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4822. * @param v1 (Vector3) the first control point
  4823. * @param v2 (Vector3) the second control point
  4824. * @param v3 (Vector3) the end point of the Cubic Bezier
  4825. * @param nbPoints (integer) the wanted number of points in the curve
  4826. */
  4827. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4828. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4829. var bez = new Array();
  4830. var equation = function (t, val0, val1, val2, val3) {
  4831. 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;
  4832. return res;
  4833. };
  4834. for (var i = 0; i <= nbPoints; i++) {
  4835. 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)));
  4836. }
  4837. return new Curve3(bez);
  4838. };
  4839. /**
  4840. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4841. * @param p1 (Vector3) the origin point of the Hermite Spline
  4842. * @param t1 (Vector3) the tangent vector at the origin point
  4843. * @param p2 (Vector3) the end point of the Hermite Spline
  4844. * @param t2 (Vector3) the tangent vector at the end point
  4845. * @param nbPoints (integer) the wanted number of points in the curve
  4846. */
  4847. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4848. var hermite = new Array();
  4849. var step = 1.0 / nbPoints;
  4850. for (var i = 0; i <= nbPoints; i++) {
  4851. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4852. }
  4853. return new Curve3(hermite);
  4854. };
  4855. /**
  4856. * Returns a Curve3 object along a CatmullRom Spline curve :
  4857. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4858. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4859. */
  4860. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4861. var totalPoints = new Array();
  4862. totalPoints.push(points[0].clone());
  4863. Array.prototype.push.apply(totalPoints, points);
  4864. totalPoints.push(points[points.length - 1].clone());
  4865. var catmullRom = new Array();
  4866. var step = 1.0 / nbPoints;
  4867. var amount = 0.0;
  4868. for (var i = 0; i < totalPoints.length - 3; i++) {
  4869. amount = 0;
  4870. for (var c = 0; c < nbPoints; c++) {
  4871. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4872. amount += step;
  4873. }
  4874. }
  4875. i--;
  4876. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4877. return new Curve3(catmullRom);
  4878. };
  4879. /**
  4880. * Returns the Curve3 stored array of successive Vector3
  4881. */
  4882. Curve3.prototype.getPoints = function () {
  4883. return this._points;
  4884. };
  4885. /**
  4886. * Returns the computed length (float) of the curve.
  4887. */
  4888. Curve3.prototype.length = function () {
  4889. return this._length;
  4890. };
  4891. /**
  4892. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4893. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4894. * curveA and curveB keep unchanged.
  4895. */
  4896. Curve3.prototype.continue = function (curve) {
  4897. var lastPoint = this._points[this._points.length - 1];
  4898. var continuedPoints = this._points.slice();
  4899. var curvePoints = curve.getPoints();
  4900. for (var i = 1; i < curvePoints.length; i++) {
  4901. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4902. }
  4903. var continuedCurve = new Curve3(continuedPoints);
  4904. return continuedCurve;
  4905. };
  4906. Curve3.prototype._computeLength = function (path) {
  4907. var l = 0;
  4908. for (var i = 1; i < path.length; i++) {
  4909. l += (path[i].subtract(path[i - 1])).length();
  4910. }
  4911. return l;
  4912. };
  4913. return Curve3;
  4914. }());
  4915. BABYLON.Curve3 = Curve3;
  4916. // Vertex formats
  4917. var PositionNormalVertex = /** @class */ (function () {
  4918. function PositionNormalVertex(position, normal) {
  4919. if (position === void 0) { position = Vector3.Zero(); }
  4920. if (normal === void 0) { normal = Vector3.Up(); }
  4921. this.position = position;
  4922. this.normal = normal;
  4923. }
  4924. PositionNormalVertex.prototype.clone = function () {
  4925. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4926. };
  4927. return PositionNormalVertex;
  4928. }());
  4929. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4930. var PositionNormalTextureVertex = /** @class */ (function () {
  4931. function PositionNormalTextureVertex(position, normal, uv) {
  4932. if (position === void 0) { position = Vector3.Zero(); }
  4933. if (normal === void 0) { normal = Vector3.Up(); }
  4934. if (uv === void 0) { uv = Vector2.Zero(); }
  4935. this.position = position;
  4936. this.normal = normal;
  4937. this.uv = uv;
  4938. }
  4939. PositionNormalTextureVertex.prototype.clone = function () {
  4940. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4941. };
  4942. return PositionNormalTextureVertex;
  4943. }());
  4944. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4945. // Temporary pre-allocated objects for engine internal use
  4946. // usage in any internal function :
  4947. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4948. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4949. var Tmp = /** @class */ (function () {
  4950. function Tmp() {
  4951. }
  4952. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4953. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4954. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4955. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4956. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4957. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4958. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4959. Matrix.Zero(), Matrix.Zero(),
  4960. Matrix.Zero(), Matrix.Zero(),
  4961. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4962. return Tmp;
  4963. }());
  4964. BABYLON.Tmp = Tmp;
  4965. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4966. var MathTmp = /** @class */ (function () {
  4967. function MathTmp() {
  4968. }
  4969. MathTmp.Vector3 = [Vector3.Zero()];
  4970. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4971. MathTmp.Quaternion = [Quaternion.Zero()];
  4972. return MathTmp;
  4973. }());
  4974. })(BABYLON || (BABYLON = {}));
  4975. //# sourceMappingURL=babylon.math.js.map
  4976. var BABYLON;
  4977. (function (BABYLON) {
  4978. var Scalar = /** @class */ (function () {
  4979. function Scalar() {
  4980. }
  4981. /**
  4982. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4983. */
  4984. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4985. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4986. var num = a - b;
  4987. return -epsilon <= num && num <= epsilon;
  4988. };
  4989. /**
  4990. * Returns a string : the upper case translation of the number i to hexadecimal.
  4991. */
  4992. Scalar.ToHex = function (i) {
  4993. var str = i.toString(16);
  4994. if (i <= 15) {
  4995. return ("0" + str).toUpperCase();
  4996. }
  4997. return str.toUpperCase();
  4998. };
  4999. /**
  5000. * Returns -1 if value is negative and +1 is value is positive.
  5001. * Returns the value itself if it's equal to zero.
  5002. */
  5003. Scalar.Sign = function (value) {
  5004. value = +value; // convert to a number
  5005. if (value === 0 || isNaN(value))
  5006. return value;
  5007. return value > 0 ? 1 : -1;
  5008. };
  5009. /**
  5010. * Returns the value itself if it's between min and max.
  5011. * Returns min if the value is lower than min.
  5012. * Returns max if the value is greater than max.
  5013. */
  5014. Scalar.Clamp = function (value, min, max) {
  5015. if (min === void 0) { min = 0; }
  5016. if (max === void 0) { max = 1; }
  5017. return Math.min(max, Math.max(min, value));
  5018. };
  5019. /**
  5020. * Returns the log2 of value.
  5021. */
  5022. Scalar.Log2 = function (value) {
  5023. return Math.log(value) * Math.LOG2E;
  5024. };
  5025. /**
  5026. * Loops the value, so that it is never larger than length and never smaller than 0.
  5027. *
  5028. * This is similar to the modulo operator but it works with floating point numbers.
  5029. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5030. * With t = 5 and length = 2.5, the result would be 0.0.
  5031. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5032. */
  5033. Scalar.Repeat = function (value, length) {
  5034. return value - Math.floor(value / length) * length;
  5035. };
  5036. /**
  5037. * Normalize the value between 0.0 and 1.0 using min and max values
  5038. */
  5039. Scalar.Normalize = function (value, min, max) {
  5040. return (value - min) / (max - min);
  5041. };
  5042. /**
  5043. * Denormalize the value from 0.0 and 1.0 using min and max values
  5044. */
  5045. Scalar.Denormalize = function (normalized, min, max) {
  5046. return (normalized * (max - min) + min);
  5047. };
  5048. /**
  5049. * Calculates the shortest difference between two given angles given in degrees.
  5050. */
  5051. Scalar.DeltaAngle = function (current, target) {
  5052. var num = Scalar.Repeat(target - current, 360.0);
  5053. if (num > 180.0) {
  5054. num -= 360.0;
  5055. }
  5056. return num;
  5057. };
  5058. /**
  5059. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5060. *
  5061. * The returned value will move back and forth between 0 and length
  5062. */
  5063. Scalar.PingPong = function (tx, length) {
  5064. var t = Scalar.Repeat(tx, length * 2.0);
  5065. return length - Math.abs(t - length);
  5066. };
  5067. /**
  5068. * Interpolates between min and max with smoothing at the limits.
  5069. *
  5070. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5071. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5072. */
  5073. Scalar.SmoothStep = function (from, to, tx) {
  5074. var t = Scalar.Clamp(tx);
  5075. t = -2.0 * t * t * t + 3.0 * t * t;
  5076. return to * t + from * (1.0 - t);
  5077. };
  5078. /**
  5079. * Moves a value current towards target.
  5080. *
  5081. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5082. * Negative values of maxDelta pushes the value away from target.
  5083. */
  5084. Scalar.MoveTowards = function (current, target, maxDelta) {
  5085. var result = 0;
  5086. if (Math.abs(target - current) <= maxDelta) {
  5087. result = target;
  5088. }
  5089. else {
  5090. result = current + Scalar.Sign(target - current) * maxDelta;
  5091. }
  5092. return result;
  5093. };
  5094. /**
  5095. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5096. *
  5097. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5098. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5099. */
  5100. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5101. var num = Scalar.DeltaAngle(current, target);
  5102. var result = 0;
  5103. if (-maxDelta < num && num < maxDelta) {
  5104. result = target;
  5105. }
  5106. else {
  5107. target = current + num;
  5108. result = Scalar.MoveTowards(current, target, maxDelta);
  5109. }
  5110. return result;
  5111. };
  5112. /**
  5113. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5114. */
  5115. Scalar.Lerp = function (start, end, amount) {
  5116. return start + ((end - start) * amount);
  5117. };
  5118. /**
  5119. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5120. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5121. */
  5122. Scalar.LerpAngle = function (start, end, amount) {
  5123. var num = Scalar.Repeat(end - start, 360.0);
  5124. if (num > 180.0) {
  5125. num -= 360.0;
  5126. }
  5127. return start + num * Scalar.Clamp(amount);
  5128. };
  5129. /**
  5130. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5131. */
  5132. Scalar.InverseLerp = function (a, b, value) {
  5133. var result = 0;
  5134. if (a != b) {
  5135. result = Scalar.Clamp((value - a) / (b - a));
  5136. }
  5137. else {
  5138. result = 0.0;
  5139. }
  5140. return result;
  5141. };
  5142. /**
  5143. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5144. */
  5145. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5146. var squared = amount * amount;
  5147. var cubed = amount * squared;
  5148. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5149. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5150. var part3 = (cubed - (2.0 * squared)) + amount;
  5151. var part4 = cubed - squared;
  5152. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5153. };
  5154. /**
  5155. * Returns a random float number between and min and max values
  5156. */
  5157. Scalar.RandomRange = function (min, max) {
  5158. if (min === max)
  5159. return min;
  5160. return ((Math.random() * (max - min)) + min);
  5161. };
  5162. /**
  5163. * This function returns percentage of a number in a given range.
  5164. *
  5165. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5166. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5167. */
  5168. Scalar.RangeToPercent = function (number, min, max) {
  5169. return ((number - min) / (max - min));
  5170. };
  5171. /**
  5172. * This function returns number that corresponds to the percentage in a given range.
  5173. *
  5174. * PercentToRange(0.34,0,100) will return 34.
  5175. */
  5176. Scalar.PercentToRange = function (percent, min, max) {
  5177. return ((max - min) * percent + min);
  5178. };
  5179. /**
  5180. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5181. * @param angle The angle to normalize in radian.
  5182. * @return The converted angle.
  5183. */
  5184. Scalar.NormalizeRadians = function (angle) {
  5185. // More precise but slower version kept for reference.
  5186. // angle = angle % Tools.TwoPi;
  5187. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5188. //if (angle > Math.PI) {
  5189. // angle -= Tools.TwoPi;
  5190. //}
  5191. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5192. return angle;
  5193. };
  5194. /**
  5195. * Two pi constants convenient for computation.
  5196. */
  5197. Scalar.TwoPi = Math.PI * 2;
  5198. return Scalar;
  5199. }());
  5200. BABYLON.Scalar = Scalar;
  5201. })(BABYLON || (BABYLON = {}));
  5202. //# sourceMappingURL=babylon.math.scalar.js.map
  5203. //# sourceMappingURL=babylon.mixins.js.map
  5204. var BABYLON;
  5205. (function (BABYLON) {
  5206. var __decoratorInitialStore = {};
  5207. var __mergedStore = {};
  5208. var _copySource = function (creationFunction, source, instanciate) {
  5209. var destination = creationFunction();
  5210. // Tags
  5211. if (BABYLON.Tags) {
  5212. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5213. }
  5214. var classStore = getMergedStore(destination);
  5215. // Properties
  5216. for (var property in classStore) {
  5217. var propertyDescriptor = classStore[property];
  5218. var sourceProperty = source[property];
  5219. var propertyType = propertyDescriptor.type;
  5220. if (sourceProperty !== undefined && sourceProperty !== null) {
  5221. switch (propertyType) {
  5222. case 0: // Value
  5223. case 6:// Mesh reference
  5224. destination[property] = sourceProperty;
  5225. break;
  5226. case 1:// Texture
  5227. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5228. break;
  5229. case 2: // Color3
  5230. case 3: // FresnelParameters
  5231. case 4: // Vector2
  5232. case 5: // Vector3
  5233. case 7:// Color Curves
  5234. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5235. break;
  5236. }
  5237. }
  5238. }
  5239. return destination;
  5240. };
  5241. function getDirectStore(target) {
  5242. var classKey = target.getClassName();
  5243. if (!__decoratorInitialStore[classKey]) {
  5244. __decoratorInitialStore[classKey] = {};
  5245. }
  5246. return __decoratorInitialStore[classKey];
  5247. }
  5248. /**
  5249. * Return the list of properties flagged as serializable
  5250. * @param target: host object
  5251. */
  5252. function getMergedStore(target) {
  5253. var classKey = target.getClassName();
  5254. if (__mergedStore[classKey]) {
  5255. return __mergedStore[classKey];
  5256. }
  5257. __mergedStore[classKey] = {};
  5258. var store = __mergedStore[classKey];
  5259. var currentTarget = target;
  5260. var currentKey = classKey;
  5261. while (currentKey) {
  5262. var initialStore = __decoratorInitialStore[currentKey];
  5263. for (var property in initialStore) {
  5264. store[property] = initialStore[property];
  5265. }
  5266. var parent_1 = void 0;
  5267. var done = false;
  5268. do {
  5269. parent_1 = Object.getPrototypeOf(currentTarget);
  5270. if (!parent_1.getClassName) {
  5271. done = true;
  5272. break;
  5273. }
  5274. if (parent_1.getClassName() !== currentKey) {
  5275. break;
  5276. }
  5277. currentTarget = parent_1;
  5278. } while (parent_1);
  5279. if (done) {
  5280. break;
  5281. }
  5282. currentKey = parent_1.getClassName();
  5283. currentTarget = parent_1;
  5284. }
  5285. return store;
  5286. }
  5287. function generateSerializableMember(type, sourceName) {
  5288. return function (target, propertyKey) {
  5289. var classStore = getDirectStore(target);
  5290. if (!classStore[propertyKey]) {
  5291. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5292. }
  5293. };
  5294. }
  5295. function generateExpandMember(setCallback, targetKey) {
  5296. if (targetKey === void 0) { targetKey = null; }
  5297. return function (target, propertyKey) {
  5298. var key = targetKey || ("_" + propertyKey);
  5299. Object.defineProperty(target, propertyKey, {
  5300. get: function () {
  5301. return this[key];
  5302. },
  5303. set: function (value) {
  5304. if (this[key] === value) {
  5305. return;
  5306. }
  5307. this[key] = value;
  5308. target[setCallback].apply(this);
  5309. },
  5310. enumerable: true,
  5311. configurable: true
  5312. });
  5313. };
  5314. }
  5315. function expandToProperty(callback, targetKey) {
  5316. if (targetKey === void 0) { targetKey = null; }
  5317. return generateExpandMember(callback, targetKey);
  5318. }
  5319. BABYLON.expandToProperty = expandToProperty;
  5320. function serialize(sourceName) {
  5321. return generateSerializableMember(0, sourceName); // value member
  5322. }
  5323. BABYLON.serialize = serialize;
  5324. function serializeAsTexture(sourceName) {
  5325. return generateSerializableMember(1, sourceName); // texture member
  5326. }
  5327. BABYLON.serializeAsTexture = serializeAsTexture;
  5328. function serializeAsColor3(sourceName) {
  5329. return generateSerializableMember(2, sourceName); // color3 member
  5330. }
  5331. BABYLON.serializeAsColor3 = serializeAsColor3;
  5332. function serializeAsFresnelParameters(sourceName) {
  5333. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5334. }
  5335. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5336. function serializeAsVector2(sourceName) {
  5337. return generateSerializableMember(4, sourceName); // vector2 member
  5338. }
  5339. BABYLON.serializeAsVector2 = serializeAsVector2;
  5340. function serializeAsVector3(sourceName) {
  5341. return generateSerializableMember(5, sourceName); // vector3 member
  5342. }
  5343. BABYLON.serializeAsVector3 = serializeAsVector3;
  5344. function serializeAsMeshReference(sourceName) {
  5345. return generateSerializableMember(6, sourceName); // mesh reference member
  5346. }
  5347. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5348. function serializeAsColorCurves(sourceName) {
  5349. return generateSerializableMember(7, sourceName); // color curves
  5350. }
  5351. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5352. function serializeAsColor4(sourceName) {
  5353. return generateSerializableMember(8, sourceName); // color 4
  5354. }
  5355. BABYLON.serializeAsColor4 = serializeAsColor4;
  5356. function serializeAsImageProcessingConfiguration(sourceName) {
  5357. return generateSerializableMember(9, sourceName); // image processing
  5358. }
  5359. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5360. var SerializationHelper = /** @class */ (function () {
  5361. function SerializationHelper() {
  5362. }
  5363. SerializationHelper.Serialize = function (entity, serializationObject) {
  5364. if (!serializationObject) {
  5365. serializationObject = {};
  5366. }
  5367. // Tags
  5368. if (BABYLON.Tags) {
  5369. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5370. }
  5371. var serializedProperties = getMergedStore(entity);
  5372. // Properties
  5373. for (var property in serializedProperties) {
  5374. var propertyDescriptor = serializedProperties[property];
  5375. var targetPropertyName = propertyDescriptor.sourceName || property;
  5376. var propertyType = propertyDescriptor.type;
  5377. var sourceProperty = entity[property];
  5378. if (sourceProperty !== undefined && sourceProperty !== null) {
  5379. switch (propertyType) {
  5380. case 0:// Value
  5381. serializationObject[targetPropertyName] = sourceProperty;
  5382. break;
  5383. case 1:// Texture
  5384. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5385. break;
  5386. case 2:// Color3
  5387. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5388. break;
  5389. case 3:// FresnelParameters
  5390. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5391. break;
  5392. case 4:// Vector2
  5393. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5394. break;
  5395. case 5:// Vector3
  5396. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5397. break;
  5398. case 6:// Mesh reference
  5399. serializationObject[targetPropertyName] = sourceProperty.id;
  5400. break;
  5401. case 7:// Color Curves
  5402. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5403. break;
  5404. case 8:// Color 4
  5405. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5406. break;
  5407. case 9:// Image Processing
  5408. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5409. break;
  5410. }
  5411. }
  5412. }
  5413. return serializationObject;
  5414. };
  5415. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5416. if (rootUrl === void 0) { rootUrl = null; }
  5417. var destination = creationFunction();
  5418. if (!rootUrl) {
  5419. rootUrl = "";
  5420. }
  5421. // Tags
  5422. if (BABYLON.Tags) {
  5423. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5424. }
  5425. var classStore = getMergedStore(destination);
  5426. // Properties
  5427. for (var property in classStore) {
  5428. var propertyDescriptor = classStore[property];
  5429. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5430. var propertyType = propertyDescriptor.type;
  5431. if (sourceProperty !== undefined && sourceProperty !== null) {
  5432. var dest = destination;
  5433. switch (propertyType) {
  5434. case 0:// Value
  5435. dest[property] = sourceProperty;
  5436. break;
  5437. case 1:// Texture
  5438. if (scene) {
  5439. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5440. }
  5441. break;
  5442. case 2:// Color3
  5443. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5444. break;
  5445. case 3:// FresnelParameters
  5446. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5447. break;
  5448. case 4:// Vector2
  5449. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5450. break;
  5451. case 5:// Vector3
  5452. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5453. break;
  5454. case 6:// Mesh reference
  5455. if (scene) {
  5456. dest[property] = scene.getLastMeshByID(sourceProperty);
  5457. }
  5458. break;
  5459. case 7:// Color Curves
  5460. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5461. break;
  5462. case 8:// Color 4
  5463. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5464. break;
  5465. case 9:// Image Processing
  5466. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5467. break;
  5468. }
  5469. }
  5470. }
  5471. return destination;
  5472. };
  5473. SerializationHelper.Clone = function (creationFunction, source) {
  5474. return _copySource(creationFunction, source, false);
  5475. };
  5476. SerializationHelper.Instanciate = function (creationFunction, source) {
  5477. return _copySource(creationFunction, source, true);
  5478. };
  5479. return SerializationHelper;
  5480. }());
  5481. BABYLON.SerializationHelper = SerializationHelper;
  5482. })(BABYLON || (BABYLON = {}));
  5483. //# sourceMappingURL=babylon.decorators.js.map
  5484. var BABYLON;
  5485. (function (BABYLON) {
  5486. /**
  5487. * A class serves as a medium between the observable and its observers
  5488. */
  5489. var EventState = /** @class */ (function () {
  5490. /**
  5491. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5492. */
  5493. function EventState(mask, skipNextObservers, target, currentTarget) {
  5494. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5495. this.initalize(mask, skipNextObservers, target, currentTarget);
  5496. }
  5497. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5498. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5499. this.mask = mask;
  5500. this.skipNextObservers = skipNextObservers;
  5501. this.target = target;
  5502. this.currentTarget = currentTarget;
  5503. return this;
  5504. };
  5505. return EventState;
  5506. }());
  5507. BABYLON.EventState = EventState;
  5508. /**
  5509. * Represent an Observer registered to a given Observable object.
  5510. */
  5511. var Observer = /** @class */ (function () {
  5512. function Observer(callback, mask, scope) {
  5513. if (scope === void 0) { scope = null; }
  5514. this.callback = callback;
  5515. this.mask = mask;
  5516. this.scope = scope;
  5517. }
  5518. return Observer;
  5519. }());
  5520. BABYLON.Observer = Observer;
  5521. /**
  5522. * Represent a list of observers registered to multiple Observables object.
  5523. */
  5524. var MultiObserver = /** @class */ (function () {
  5525. function MultiObserver() {
  5526. }
  5527. MultiObserver.prototype.dispose = function () {
  5528. if (this._observers && this._observables) {
  5529. for (var index = 0; index < this._observers.length; index++) {
  5530. this._observables[index].remove(this._observers[index]);
  5531. }
  5532. }
  5533. this._observers = null;
  5534. this._observables = null;
  5535. };
  5536. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5537. if (mask === void 0) { mask = -1; }
  5538. if (scope === void 0) { scope = null; }
  5539. var result = new MultiObserver();
  5540. result._observers = new Array();
  5541. result._observables = observables;
  5542. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5543. var observable = observables_1[_i];
  5544. var observer = observable.add(callback, mask, false, scope);
  5545. if (observer) {
  5546. result._observers.push(observer);
  5547. }
  5548. }
  5549. return result;
  5550. };
  5551. return MultiObserver;
  5552. }());
  5553. BABYLON.MultiObserver = MultiObserver;
  5554. /**
  5555. * The Observable class is a simple implementation of the Observable pattern.
  5556. * 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.
  5557. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5558. * 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).
  5559. * 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.
  5560. */
  5561. var Observable = /** @class */ (function () {
  5562. function Observable(onObserverAdded) {
  5563. this._observers = new Array();
  5564. this._eventState = new EventState(0);
  5565. if (onObserverAdded) {
  5566. this._onObserverAdded = onObserverAdded;
  5567. }
  5568. }
  5569. /**
  5570. * Create a new Observer with the specified callback
  5571. * @param callback the callback that will be executed for that Observer
  5572. * @param mask the mask used to filter observers
  5573. * @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.
  5574. * @param scope optional scope for the callback to be called from
  5575. */
  5576. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5577. if (mask === void 0) { mask = -1; }
  5578. if (insertFirst === void 0) { insertFirst = false; }
  5579. if (scope === void 0) { scope = null; }
  5580. if (!callback) {
  5581. return null;
  5582. }
  5583. var observer = new Observer(callback, mask, scope);
  5584. if (insertFirst) {
  5585. this._observers.unshift(observer);
  5586. }
  5587. else {
  5588. this._observers.push(observer);
  5589. }
  5590. if (this._onObserverAdded) {
  5591. this._onObserverAdded(observer);
  5592. }
  5593. return observer;
  5594. };
  5595. /**
  5596. * Remove an Observer from the Observable object
  5597. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5598. */
  5599. Observable.prototype.remove = function (observer) {
  5600. if (!observer) {
  5601. return false;
  5602. }
  5603. var index = this._observers.indexOf(observer);
  5604. if (index !== -1) {
  5605. this._observers.splice(index, 1);
  5606. return true;
  5607. }
  5608. return false;
  5609. };
  5610. /**
  5611. * Remove a callback from the Observable object
  5612. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5613. */
  5614. Observable.prototype.removeCallback = function (callback) {
  5615. for (var index = 0; index < this._observers.length; index++) {
  5616. if (this._observers[index].callback === callback) {
  5617. this._observers.splice(index, 1);
  5618. return true;
  5619. }
  5620. }
  5621. return false;
  5622. };
  5623. /**
  5624. * Notify all Observers by calling their respective callback with the given data
  5625. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5626. * @param eventData
  5627. * @param mask
  5628. */
  5629. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5630. if (mask === void 0) { mask = -1; }
  5631. if (!this._observers.length) {
  5632. return true;
  5633. }
  5634. var state = this._eventState;
  5635. state.mask = mask;
  5636. state.target = target;
  5637. state.currentTarget = currentTarget;
  5638. state.skipNextObservers = false;
  5639. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5640. var obs = _a[_i];
  5641. if (obs.mask & mask) {
  5642. if (obs.scope) {
  5643. obs.callback.apply(obs.scope, [eventData, state]);
  5644. }
  5645. else {
  5646. obs.callback(eventData, state);
  5647. }
  5648. }
  5649. if (state.skipNextObservers) {
  5650. return false;
  5651. }
  5652. }
  5653. return true;
  5654. };
  5655. /**
  5656. * Notify a specific observer
  5657. * @param eventData
  5658. * @param mask
  5659. */
  5660. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5661. if (mask === void 0) { mask = -1; }
  5662. var state = this._eventState;
  5663. state.mask = mask;
  5664. state.skipNextObservers = false;
  5665. observer.callback(eventData, state);
  5666. };
  5667. /**
  5668. * return true is the Observable has at least one Observer registered
  5669. */
  5670. Observable.prototype.hasObservers = function () {
  5671. return this._observers.length > 0;
  5672. };
  5673. /**
  5674. * Clear the list of observers
  5675. */
  5676. Observable.prototype.clear = function () {
  5677. this._observers = new Array();
  5678. this._onObserverAdded = null;
  5679. };
  5680. /**
  5681. * Clone the current observable
  5682. */
  5683. Observable.prototype.clone = function () {
  5684. var result = new Observable();
  5685. result._observers = this._observers.slice(0);
  5686. return result;
  5687. };
  5688. /**
  5689. * Does this observable handles observer registered with a given mask
  5690. * @param {number} trigger - the mask to be tested
  5691. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5692. **/
  5693. Observable.prototype.hasSpecificMask = function (mask) {
  5694. if (mask === void 0) { mask = -1; }
  5695. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5696. var obs = _a[_i];
  5697. if (obs.mask & mask || obs.mask === mask) {
  5698. return true;
  5699. }
  5700. }
  5701. return false;
  5702. };
  5703. return Observable;
  5704. }());
  5705. BABYLON.Observable = Observable;
  5706. })(BABYLON || (BABYLON = {}));
  5707. //# sourceMappingURL=babylon.observable.js.map
  5708. var BABYLON;
  5709. (function (BABYLON) {
  5710. var SmartArray = /** @class */ (function () {
  5711. function SmartArray(capacity) {
  5712. this.length = 0;
  5713. this.data = new Array(capacity);
  5714. this._id = SmartArray._GlobalId++;
  5715. }
  5716. SmartArray.prototype.push = function (value) {
  5717. this.data[this.length++] = value;
  5718. if (this.length > this.data.length) {
  5719. this.data.length *= 2;
  5720. }
  5721. };
  5722. SmartArray.prototype.forEach = function (func) {
  5723. for (var index = 0; index < this.length; index++) {
  5724. func(this.data[index]);
  5725. }
  5726. };
  5727. SmartArray.prototype.sort = function (compareFn) {
  5728. this.data.sort(compareFn);
  5729. };
  5730. SmartArray.prototype.reset = function () {
  5731. this.length = 0;
  5732. };
  5733. SmartArray.prototype.dispose = function () {
  5734. this.reset();
  5735. if (this.data) {
  5736. this.data.length = 0;
  5737. this.data = [];
  5738. }
  5739. };
  5740. SmartArray.prototype.concat = function (array) {
  5741. if (array.length === 0) {
  5742. return;
  5743. }
  5744. if (this.length + array.length > this.data.length) {
  5745. this.data.length = (this.length + array.length) * 2;
  5746. }
  5747. for (var index = 0; index < array.length; index++) {
  5748. this.data[this.length++] = (array.data || array)[index];
  5749. }
  5750. };
  5751. SmartArray.prototype.indexOf = function (value) {
  5752. var position = this.data.indexOf(value);
  5753. if (position >= this.length) {
  5754. return -1;
  5755. }
  5756. return position;
  5757. };
  5758. SmartArray.prototype.contains = function (value) {
  5759. return this.data.indexOf(value) !== -1;
  5760. };
  5761. // Statics
  5762. SmartArray._GlobalId = 0;
  5763. return SmartArray;
  5764. }());
  5765. BABYLON.SmartArray = SmartArray;
  5766. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5767. __extends(SmartArrayNoDuplicate, _super);
  5768. function SmartArrayNoDuplicate() {
  5769. var _this = _super !== null && _super.apply(this, arguments) || this;
  5770. _this._duplicateId = 0;
  5771. return _this;
  5772. }
  5773. SmartArrayNoDuplicate.prototype.push = function (value) {
  5774. _super.prototype.push.call(this, value);
  5775. if (!value.__smartArrayFlags) {
  5776. value.__smartArrayFlags = {};
  5777. }
  5778. value.__smartArrayFlags[this._id] = this._duplicateId;
  5779. };
  5780. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5781. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5782. return false;
  5783. }
  5784. this.push(value);
  5785. return true;
  5786. };
  5787. SmartArrayNoDuplicate.prototype.reset = function () {
  5788. _super.prototype.reset.call(this);
  5789. this._duplicateId++;
  5790. };
  5791. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5792. if (array.length === 0) {
  5793. return;
  5794. }
  5795. if (this.length + array.length > this.data.length) {
  5796. this.data.length = (this.length + array.length) * 2;
  5797. }
  5798. for (var index = 0; index < array.length; index++) {
  5799. var item = (array.data || array)[index];
  5800. this.pushNoDuplicate(item);
  5801. }
  5802. };
  5803. return SmartArrayNoDuplicate;
  5804. }(SmartArray));
  5805. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5806. })(BABYLON || (BABYLON = {}));
  5807. //# sourceMappingURL=babylon.smartArray.js.map
  5808. var BABYLON;
  5809. (function (BABYLON) {
  5810. // Screenshots
  5811. var screenshotCanvas;
  5812. var cloneValue = function (source, destinationObject) {
  5813. if (!source)
  5814. return null;
  5815. if (source instanceof BABYLON.Mesh) {
  5816. return null;
  5817. }
  5818. if (source instanceof BABYLON.SubMesh) {
  5819. return source.clone(destinationObject);
  5820. }
  5821. else if (source.clone) {
  5822. return source.clone();
  5823. }
  5824. return null;
  5825. };
  5826. var Tools = /** @class */ (function () {
  5827. function Tools() {
  5828. }
  5829. ;
  5830. /**
  5831. * Interpolates between a and b via alpha
  5832. * @param a The lower value (returned when alpha = 0)
  5833. * @param b The upper value (returned when alpha = 1)
  5834. * @param alpha The interpolation-factor
  5835. * @return The mixed value
  5836. */
  5837. Tools.Mix = function (a, b, alpha) {
  5838. return a * (1 - alpha) + b * alpha;
  5839. };
  5840. Tools.Instantiate = function (className) {
  5841. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5842. return Tools.RegisteredExternalClasses[className];
  5843. }
  5844. var arr = className.split(".");
  5845. var fn = (window || this);
  5846. for (var i = 0, len = arr.length; i < len; i++) {
  5847. fn = fn[arr[i]];
  5848. }
  5849. if (typeof fn !== "function") {
  5850. return null;
  5851. }
  5852. return fn;
  5853. };
  5854. Tools.SetImmediate = function (action) {
  5855. if (window.setImmediate) {
  5856. window.setImmediate(action);
  5857. }
  5858. else {
  5859. setTimeout(action, 1);
  5860. }
  5861. };
  5862. Tools.IsExponentOfTwo = function (value) {
  5863. var count = 1;
  5864. do {
  5865. count *= 2;
  5866. } while (count < value);
  5867. return count === value;
  5868. };
  5869. /**
  5870. * Find the next highest power of two.
  5871. * @param x Number to start search from.
  5872. * @return Next highest power of two.
  5873. */
  5874. Tools.CeilingPOT = function (x) {
  5875. x--;
  5876. x |= x >> 1;
  5877. x |= x >> 2;
  5878. x |= x >> 4;
  5879. x |= x >> 8;
  5880. x |= x >> 16;
  5881. x++;
  5882. return x;
  5883. };
  5884. /**
  5885. * Find the next lowest power of two.
  5886. * @param x Number to start search from.
  5887. * @return Next lowest power of two.
  5888. */
  5889. Tools.FloorPOT = function (x) {
  5890. x = x | (x >> 1);
  5891. x = x | (x >> 2);
  5892. x = x | (x >> 4);
  5893. x = x | (x >> 8);
  5894. x = x | (x >> 16);
  5895. return x - (x >> 1);
  5896. };
  5897. /**
  5898. * Find the nearest power of two.
  5899. * @param x Number to start search from.
  5900. * @return Next nearest power of two.
  5901. */
  5902. Tools.NearestPOT = function (x) {
  5903. var c = Tools.CeilingPOT(x);
  5904. var f = Tools.FloorPOT(x);
  5905. return (c - x) > (x - f) ? f : c;
  5906. };
  5907. Tools.GetExponentOfTwo = function (value, max, mode) {
  5908. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5909. var pot;
  5910. switch (mode) {
  5911. case BABYLON.Engine.SCALEMODE_FLOOR:
  5912. pot = Tools.FloorPOT(value);
  5913. break;
  5914. case BABYLON.Engine.SCALEMODE_NEAREST:
  5915. pot = Tools.NearestPOT(value);
  5916. break;
  5917. case BABYLON.Engine.SCALEMODE_CEILING:
  5918. default:
  5919. pot = Tools.CeilingPOT(value);
  5920. break;
  5921. }
  5922. return Math.min(pot, max);
  5923. };
  5924. Tools.GetFilename = function (path) {
  5925. var index = path.lastIndexOf("/");
  5926. if (index < 0)
  5927. return path;
  5928. return path.substring(index + 1);
  5929. };
  5930. Tools.GetFolderPath = function (uri) {
  5931. var index = uri.lastIndexOf("/");
  5932. if (index < 0)
  5933. return "";
  5934. return uri.substring(0, index + 1);
  5935. };
  5936. Tools.GetDOMTextContent = function (element) {
  5937. var result = "";
  5938. var child = element.firstChild;
  5939. while (child) {
  5940. if (child.nodeType === 3) {
  5941. result += child.textContent;
  5942. }
  5943. child = child.nextSibling;
  5944. }
  5945. return result;
  5946. };
  5947. Tools.ToDegrees = function (angle) {
  5948. return angle * 180 / Math.PI;
  5949. };
  5950. Tools.ToRadians = function (angle) {
  5951. return angle * Math.PI / 180;
  5952. };
  5953. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5954. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5955. var output = "";
  5956. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5957. var i = 0;
  5958. var bytes = new Uint8Array(buffer);
  5959. while (i < bytes.length) {
  5960. chr1 = bytes[i++];
  5961. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5962. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5963. enc1 = chr1 >> 2;
  5964. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5965. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5966. enc4 = chr3 & 63;
  5967. if (isNaN(chr2)) {
  5968. enc3 = enc4 = 64;
  5969. }
  5970. else if (isNaN(chr3)) {
  5971. enc4 = 64;
  5972. }
  5973. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5974. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5975. }
  5976. return "data:image/png;base64," + output;
  5977. };
  5978. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5979. if (bias === void 0) { bias = null; }
  5980. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5981. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5982. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5983. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5984. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5985. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5986. }
  5987. if (bias) {
  5988. minimum.x -= minimum.x * bias.x + bias.y;
  5989. minimum.y -= minimum.y * bias.x + bias.y;
  5990. minimum.z -= minimum.z * bias.x + bias.y;
  5991. maximum.x += maximum.x * bias.x + bias.y;
  5992. maximum.y += maximum.y * bias.x + bias.y;
  5993. maximum.z += maximum.z * bias.x + bias.y;
  5994. }
  5995. return {
  5996. minimum: minimum,
  5997. maximum: maximum
  5998. };
  5999. };
  6000. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6001. if (bias === void 0) { bias = null; }
  6002. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6003. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6004. if (!stride) {
  6005. stride = 3;
  6006. }
  6007. for (var index = start; index < start + count; index++) {
  6008. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6009. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6010. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6011. }
  6012. if (bias) {
  6013. minimum.x -= minimum.x * bias.x + bias.y;
  6014. minimum.y -= minimum.y * bias.x + bias.y;
  6015. minimum.z -= minimum.z * bias.x + bias.y;
  6016. maximum.x += maximum.x * bias.x + bias.y;
  6017. maximum.y += maximum.y * bias.x + bias.y;
  6018. maximum.z += maximum.z * bias.x + bias.y;
  6019. }
  6020. return {
  6021. minimum: minimum,
  6022. maximum: maximum
  6023. };
  6024. };
  6025. Tools.Vector2ArrayFeeder = function (array) {
  6026. return function (index) {
  6027. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6028. var length = isFloatArray ? array.length / 2 : array.length;
  6029. if (index >= length) {
  6030. return null;
  6031. }
  6032. if (isFloatArray) {
  6033. var fa = array;
  6034. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6035. }
  6036. var a = array;
  6037. return a[index];
  6038. };
  6039. };
  6040. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6041. if (bias === void 0) { bias = null; }
  6042. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6043. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6044. var i = 0;
  6045. var cur = feeder(i++);
  6046. while (cur) {
  6047. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6048. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6049. cur = feeder(i++);
  6050. }
  6051. if (bias) {
  6052. minimum.x -= minimum.x * bias.x + bias.y;
  6053. minimum.y -= minimum.y * bias.x + bias.y;
  6054. maximum.x += maximum.x * bias.x + bias.y;
  6055. maximum.y += maximum.y * bias.x + bias.y;
  6056. }
  6057. return {
  6058. minimum: minimum,
  6059. maximum: maximum
  6060. };
  6061. };
  6062. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6063. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6064. return null;
  6065. return Array.isArray(obj) ? obj : [obj];
  6066. };
  6067. // Misc.
  6068. Tools.GetPointerPrefix = function () {
  6069. var eventPrefix = "pointer";
  6070. // Check if pointer events are supported
  6071. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6072. eventPrefix = "mouse";
  6073. }
  6074. return eventPrefix;
  6075. };
  6076. /**
  6077. * @param func - the function to be called
  6078. * @param requester - the object that will request the next frame. Falls back to window.
  6079. */
  6080. Tools.QueueNewFrame = function (func, requester) {
  6081. if (!Tools.IsWindowObjectExist()) {
  6082. return setTimeout(func, 16);
  6083. }
  6084. if (!requester) {
  6085. requester = window;
  6086. }
  6087. if (requester.requestAnimationFrame) {
  6088. return requester.requestAnimationFrame(func);
  6089. }
  6090. else if (requester.msRequestAnimationFrame) {
  6091. return requester.msRequestAnimationFrame(func);
  6092. }
  6093. else if (requester.webkitRequestAnimationFrame) {
  6094. return requester.webkitRequestAnimationFrame(func);
  6095. }
  6096. else if (requester.mozRequestAnimationFrame) {
  6097. return requester.mozRequestAnimationFrame(func);
  6098. }
  6099. else if (requester.oRequestAnimationFrame) {
  6100. return requester.oRequestAnimationFrame(func);
  6101. }
  6102. else {
  6103. return window.setTimeout(func, 16);
  6104. }
  6105. };
  6106. Tools.RequestFullscreen = function (element) {
  6107. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6108. if (!requestFunction)
  6109. return;
  6110. requestFunction.call(element);
  6111. };
  6112. Tools.ExitFullscreen = function () {
  6113. if (document.exitFullscreen) {
  6114. document.exitFullscreen();
  6115. }
  6116. else if (document.mozCancelFullScreen) {
  6117. document.mozCancelFullScreen();
  6118. }
  6119. else if (document.webkitCancelFullScreen) {
  6120. document.webkitCancelFullScreen();
  6121. }
  6122. else if (document.msCancelFullScreen) {
  6123. document.msCancelFullScreen();
  6124. }
  6125. };
  6126. Tools.SetCorsBehavior = function (url, img) {
  6127. if (Tools.CorsBehavior) {
  6128. switch (typeof (Tools.CorsBehavior)) {
  6129. case "function":
  6130. var result = Tools.CorsBehavior(url);
  6131. if (result) {
  6132. img.crossOrigin = result;
  6133. }
  6134. break;
  6135. case "string":
  6136. default:
  6137. img.crossOrigin = Tools.CorsBehavior;
  6138. break;
  6139. }
  6140. }
  6141. };
  6142. // External files
  6143. Tools.CleanUrl = function (url) {
  6144. url = url.replace(/#/mg, "%23");
  6145. return url;
  6146. };
  6147. Tools.LoadImage = function (url, onLoad, onError, database) {
  6148. if (url instanceof ArrayBuffer) {
  6149. url = Tools.EncodeArrayBufferTobase64(url);
  6150. }
  6151. url = Tools.CleanUrl(url);
  6152. url = Tools.PreprocessUrl(url);
  6153. var img = new Image();
  6154. if (url.substr(0, 5) !== "data:") {
  6155. Tools.SetCorsBehavior(url, img);
  6156. }
  6157. img.onload = function () {
  6158. onLoad(img);
  6159. };
  6160. img.onerror = function (err) {
  6161. Tools.Error("Error while trying to load image: " + url);
  6162. if (Tools.UseFallbackTexture) {
  6163. img.src = Tools.fallbackTexture;
  6164. onLoad(img);
  6165. }
  6166. else {
  6167. onError("Error while trying to load image: " + url, err);
  6168. }
  6169. };
  6170. var noIndexedDB = function () {
  6171. img.src = url;
  6172. };
  6173. var loadFromIndexedDB = function () {
  6174. if (database) {
  6175. database.loadImageFromDB(url, img);
  6176. }
  6177. };
  6178. //ANY database to do!
  6179. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6180. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6181. }
  6182. else {
  6183. if (url.indexOf("file:") !== 0) {
  6184. noIndexedDB();
  6185. }
  6186. else {
  6187. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6188. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6189. try {
  6190. var blobURL;
  6191. try {
  6192. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6193. }
  6194. catch (ex) {
  6195. // Chrome doesn't support oneTimeOnly parameter
  6196. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6197. }
  6198. img.src = blobURL;
  6199. }
  6200. catch (e) {
  6201. img.src = "";
  6202. }
  6203. }
  6204. else {
  6205. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6206. img.src = Tools.fallbackTexture;
  6207. }
  6208. }
  6209. }
  6210. return img;
  6211. };
  6212. //ANY
  6213. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6214. url = Tools.CleanUrl(url);
  6215. url = Tools.PreprocessUrl(url);
  6216. var request = null;
  6217. var noIndexedDB = function () {
  6218. request = new XMLHttpRequest();
  6219. var loadUrl = Tools.BaseUrl + url;
  6220. request.open('GET', loadUrl, true);
  6221. if (useArrayBuffer) {
  6222. request.responseType = "arraybuffer";
  6223. }
  6224. if (progressCallBack) {
  6225. request.onprogress = progressCallBack;
  6226. }
  6227. request.onreadystatechange = function () {
  6228. var req = request;
  6229. // In case of undefined state in some browsers.
  6230. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6231. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6232. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6233. callback(!useArrayBuffer ? req.responseText : req.response);
  6234. }
  6235. else {
  6236. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6237. if (onError) {
  6238. onError(req, e);
  6239. }
  6240. else {
  6241. throw e;
  6242. }
  6243. }
  6244. }
  6245. };
  6246. request.send(null);
  6247. };
  6248. var loadFromIndexedDB = function () {
  6249. if (database) {
  6250. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6251. }
  6252. };
  6253. if (url.indexOf("file:") !== -1) {
  6254. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6255. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6256. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6257. }
  6258. else {
  6259. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6260. if (onError) {
  6261. var e = new Error(errorMessage);
  6262. onError(undefined, e);
  6263. }
  6264. else {
  6265. Tools.Error(errorMessage);
  6266. }
  6267. }
  6268. }
  6269. else {
  6270. // Caching all files
  6271. if (database && database.enableSceneOffline) {
  6272. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6273. }
  6274. else {
  6275. noIndexedDB();
  6276. }
  6277. }
  6278. return request;
  6279. };
  6280. /**
  6281. * Load a script (identified by an url). When the url returns, the
  6282. * content of this file is added into a new script element, attached to the DOM (body element)
  6283. */
  6284. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6285. var head = document.getElementsByTagName('head')[0];
  6286. var script = document.createElement('script');
  6287. script.type = 'text/javascript';
  6288. script.src = scriptUrl;
  6289. script.onload = function () {
  6290. if (onSuccess) {
  6291. onSuccess();
  6292. }
  6293. };
  6294. script.onerror = function (e) {
  6295. if (onError) {
  6296. onError("Unable to load script", e);
  6297. }
  6298. };
  6299. head.appendChild(script);
  6300. };
  6301. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6302. var reader = new FileReader();
  6303. reader.onload = function (e) {
  6304. //target doesn't have result from ts 1.3
  6305. callback(e.target['result']);
  6306. };
  6307. reader.onprogress = progressCallback;
  6308. reader.readAsDataURL(fileToLoad);
  6309. };
  6310. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6311. var reader = new FileReader();
  6312. reader.onerror = function (e) {
  6313. Tools.Log("Error while reading file: " + fileToLoad.name);
  6314. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6315. };
  6316. reader.onload = function (e) {
  6317. //target doesn't have result from ts 1.3
  6318. callback(e.target['result']);
  6319. };
  6320. if (progressCallBack) {
  6321. reader.onprogress = progressCallBack;
  6322. }
  6323. if (!useArrayBuffer) {
  6324. // Asynchronous read
  6325. reader.readAsText(fileToLoad);
  6326. }
  6327. else {
  6328. reader.readAsArrayBuffer(fileToLoad);
  6329. }
  6330. };
  6331. //returns a downloadable url to a file content.
  6332. Tools.FileAsURL = function (content) {
  6333. var fileBlob = new Blob([content]);
  6334. var url = window.URL || window.webkitURL;
  6335. var link = url.createObjectURL(fileBlob);
  6336. return link;
  6337. };
  6338. // Misc.
  6339. Tools.Format = function (value, decimals) {
  6340. if (decimals === void 0) { decimals = 2; }
  6341. return value.toFixed(decimals);
  6342. };
  6343. Tools.CheckExtends = function (v, min, max) {
  6344. if (v.x < min.x)
  6345. min.x = v.x;
  6346. if (v.y < min.y)
  6347. min.y = v.y;
  6348. if (v.z < min.z)
  6349. min.z = v.z;
  6350. if (v.x > max.x)
  6351. max.x = v.x;
  6352. if (v.y > max.y)
  6353. max.y = v.y;
  6354. if (v.z > max.z)
  6355. max.z = v.z;
  6356. };
  6357. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6358. for (var prop in source) {
  6359. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6360. continue;
  6361. }
  6362. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6363. continue;
  6364. }
  6365. var sourceValue = source[prop];
  6366. var typeOfSourceValue = typeof sourceValue;
  6367. if (typeOfSourceValue === "function") {
  6368. continue;
  6369. }
  6370. if (typeOfSourceValue === "object") {
  6371. if (sourceValue instanceof Array) {
  6372. destination[prop] = [];
  6373. if (sourceValue.length > 0) {
  6374. if (typeof sourceValue[0] == "object") {
  6375. for (var index = 0; index < sourceValue.length; index++) {
  6376. var clonedValue = cloneValue(sourceValue[index], destination);
  6377. if (destination[prop].indexOf(clonedValue) === -1) {
  6378. destination[prop].push(clonedValue);
  6379. }
  6380. }
  6381. }
  6382. else {
  6383. destination[prop] = sourceValue.slice(0);
  6384. }
  6385. }
  6386. }
  6387. else {
  6388. destination[prop] = cloneValue(sourceValue, destination);
  6389. }
  6390. }
  6391. else {
  6392. destination[prop] = sourceValue;
  6393. }
  6394. }
  6395. };
  6396. Tools.IsEmpty = function (obj) {
  6397. for (var i in obj) {
  6398. if (obj.hasOwnProperty(i)) {
  6399. return false;
  6400. }
  6401. }
  6402. return true;
  6403. };
  6404. Tools.RegisterTopRootEvents = function (events) {
  6405. for (var index = 0; index < events.length; index++) {
  6406. var event = events[index];
  6407. window.addEventListener(event.name, event.handler, false);
  6408. try {
  6409. if (window.parent) {
  6410. window.parent.addEventListener(event.name, event.handler, false);
  6411. }
  6412. }
  6413. catch (e) {
  6414. // Silently fails...
  6415. }
  6416. }
  6417. };
  6418. Tools.UnregisterTopRootEvents = function (events) {
  6419. for (var index = 0; index < events.length; index++) {
  6420. var event = events[index];
  6421. window.removeEventListener(event.name, event.handler);
  6422. try {
  6423. if (window.parent) {
  6424. window.parent.removeEventListener(event.name, event.handler);
  6425. }
  6426. }
  6427. catch (e) {
  6428. // Silently fails...
  6429. }
  6430. }
  6431. };
  6432. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6433. if (mimeType === void 0) { mimeType = "image/png"; }
  6434. // Read the contents of the framebuffer
  6435. var numberOfChannelsByLine = width * 4;
  6436. var halfHeight = height / 2;
  6437. //Reading datas from WebGL
  6438. var data = engine.readPixels(0, 0, width, height);
  6439. //To flip image on Y axis.
  6440. for (var i = 0; i < halfHeight; i++) {
  6441. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6442. var currentCell = j + i * numberOfChannelsByLine;
  6443. var targetLine = height - i - 1;
  6444. var targetCell = j + targetLine * numberOfChannelsByLine;
  6445. var temp = data[currentCell];
  6446. data[currentCell] = data[targetCell];
  6447. data[targetCell] = temp;
  6448. }
  6449. }
  6450. // Create a 2D canvas to store the result
  6451. if (!screenshotCanvas) {
  6452. screenshotCanvas = document.createElement('canvas');
  6453. }
  6454. screenshotCanvas.width = width;
  6455. screenshotCanvas.height = height;
  6456. var context = screenshotCanvas.getContext('2d');
  6457. if (context) {
  6458. // Copy the pixels to a 2D canvas
  6459. var imageData = context.createImageData(width, height);
  6460. var castData = (imageData.data);
  6461. castData.set(data);
  6462. context.putImageData(imageData, 0, 0);
  6463. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6464. }
  6465. };
  6466. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6467. if (mimeType === void 0) { mimeType = "image/png"; }
  6468. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6469. if (successCallback) {
  6470. successCallback(base64Image);
  6471. }
  6472. else {
  6473. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6474. if (("download" in document.createElement("a"))) {
  6475. var a = window.document.createElement("a");
  6476. a.href = base64Image;
  6477. var date = new Date();
  6478. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6479. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6480. window.document.body.appendChild(a);
  6481. a.addEventListener("click", function () {
  6482. if (a.parentElement) {
  6483. a.parentElement.removeChild(a);
  6484. }
  6485. });
  6486. a.click();
  6487. //Or opening a new tab with the image if it is not possible to automatically start download.
  6488. }
  6489. else {
  6490. var newWindow = window.open("");
  6491. var img = newWindow.document.createElement("img");
  6492. img.src = base64Image;
  6493. newWindow.document.body.appendChild(img);
  6494. }
  6495. }
  6496. };
  6497. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6498. if (mimeType === void 0) { mimeType = "image/png"; }
  6499. var width;
  6500. var height;
  6501. // If a precision value is specified
  6502. if (size.precision) {
  6503. width = Math.round(engine.getRenderWidth() * size.precision);
  6504. height = Math.round(width / engine.getAspectRatio(camera));
  6505. }
  6506. else if (size.width && size.height) {
  6507. width = size.width;
  6508. height = size.height;
  6509. }
  6510. else if (size.width && !size.height) {
  6511. width = size.width;
  6512. height = Math.round(width / engine.getAspectRatio(camera));
  6513. }
  6514. else if (size.height && !size.width) {
  6515. height = size.height;
  6516. width = Math.round(height * engine.getAspectRatio(camera));
  6517. }
  6518. else if (!isNaN(size)) {
  6519. height = size;
  6520. width = size;
  6521. }
  6522. else {
  6523. Tools.Error("Invalid 'size' parameter !");
  6524. return;
  6525. }
  6526. if (!screenshotCanvas) {
  6527. screenshotCanvas = document.createElement('canvas');
  6528. }
  6529. screenshotCanvas.width = width;
  6530. screenshotCanvas.height = height;
  6531. var renderContext = screenshotCanvas.getContext("2d");
  6532. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6533. var newWidth = width;
  6534. var newHeight = newWidth / ratio;
  6535. if (newHeight > height) {
  6536. newHeight = height;
  6537. newWidth = newHeight * ratio;
  6538. }
  6539. var offsetX = Math.max(0, width - newWidth) / 2;
  6540. var offsetY = Math.max(0, height - newHeight) / 2;
  6541. var renderingCanvas = engine.getRenderingCanvas();
  6542. if (renderContext && renderingCanvas) {
  6543. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6544. }
  6545. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6546. };
  6547. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6548. if (mimeType === void 0) { mimeType = "image/png"; }
  6549. if (samples === void 0) { samples = 1; }
  6550. var width;
  6551. var height;
  6552. //If a precision value is specified
  6553. if (size.precision) {
  6554. width = Math.round(engine.getRenderWidth() * size.precision);
  6555. height = Math.round(width / engine.getAspectRatio(camera));
  6556. size = { width: width, height: height };
  6557. }
  6558. else if (size.width && size.height) {
  6559. width = size.width;
  6560. height = size.height;
  6561. }
  6562. else if (size.width && !size.height) {
  6563. width = size.width;
  6564. height = Math.round(width / engine.getAspectRatio(camera));
  6565. size = { width: width, height: height };
  6566. }
  6567. else if (size.height && !size.width) {
  6568. height = size.height;
  6569. width = Math.round(height * engine.getAspectRatio(camera));
  6570. size = { width: width, height: height };
  6571. }
  6572. else if (!isNaN(size)) {
  6573. height = size;
  6574. width = size;
  6575. }
  6576. else {
  6577. Tools.Error("Invalid 'size' parameter !");
  6578. return;
  6579. }
  6580. var scene = camera.getScene();
  6581. var previousCamera = null;
  6582. if (scene.activeCamera !== camera) {
  6583. previousCamera = scene.activeCamera;
  6584. scene.activeCamera = camera;
  6585. }
  6586. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6587. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6588. texture.renderList = null;
  6589. texture.samples = samples;
  6590. texture.onAfterRenderObservable.add(function () {
  6591. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6592. });
  6593. scene.incrementRenderId();
  6594. scene.resetCachedMaterial();
  6595. texture.render(true);
  6596. texture.dispose();
  6597. if (previousCamera) {
  6598. scene.activeCamera = previousCamera;
  6599. }
  6600. camera.getProjectionMatrix(true); // Force cache refresh;
  6601. };
  6602. // XHR response validator for local file scenario
  6603. Tools.ValidateXHRData = function (xhr, dataType) {
  6604. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6605. if (dataType === void 0) { dataType = 7; }
  6606. try {
  6607. if (dataType & 1) {
  6608. if (xhr.responseText && xhr.responseText.length > 0) {
  6609. return true;
  6610. }
  6611. else if (dataType === 1) {
  6612. return false;
  6613. }
  6614. }
  6615. if (dataType & 2) {
  6616. // Check header width and height since there is no "TGA" magic number
  6617. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6618. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6619. return true;
  6620. }
  6621. else if (dataType === 2) {
  6622. return false;
  6623. }
  6624. }
  6625. if (dataType & 4) {
  6626. // Check for the "DDS" magic number
  6627. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6628. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6629. return true;
  6630. }
  6631. else {
  6632. return false;
  6633. }
  6634. }
  6635. }
  6636. catch (e) {
  6637. // Global protection
  6638. }
  6639. return false;
  6640. };
  6641. /**
  6642. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6643. * Be aware Math.random() could cause collisions, but:
  6644. * "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"
  6645. */
  6646. Tools.RandomId = function () {
  6647. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6648. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6649. return v.toString(16);
  6650. });
  6651. };
  6652. Object.defineProperty(Tools, "NoneLogLevel", {
  6653. get: function () {
  6654. return Tools._NoneLogLevel;
  6655. },
  6656. enumerable: true,
  6657. configurable: true
  6658. });
  6659. Object.defineProperty(Tools, "MessageLogLevel", {
  6660. get: function () {
  6661. return Tools._MessageLogLevel;
  6662. },
  6663. enumerable: true,
  6664. configurable: true
  6665. });
  6666. Object.defineProperty(Tools, "WarningLogLevel", {
  6667. get: function () {
  6668. return Tools._WarningLogLevel;
  6669. },
  6670. enumerable: true,
  6671. configurable: true
  6672. });
  6673. Object.defineProperty(Tools, "ErrorLogLevel", {
  6674. get: function () {
  6675. return Tools._ErrorLogLevel;
  6676. },
  6677. enumerable: true,
  6678. configurable: true
  6679. });
  6680. Object.defineProperty(Tools, "AllLogLevel", {
  6681. get: function () {
  6682. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6683. },
  6684. enumerable: true,
  6685. configurable: true
  6686. });
  6687. Tools._AddLogEntry = function (entry) {
  6688. Tools._LogCache = entry + Tools._LogCache;
  6689. if (Tools.OnNewCacheEntry) {
  6690. Tools.OnNewCacheEntry(entry);
  6691. }
  6692. };
  6693. Tools._FormatMessage = function (message) {
  6694. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6695. var date = new Date();
  6696. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6697. };
  6698. Tools._LogDisabled = function (message) {
  6699. // nothing to do
  6700. };
  6701. Tools._LogEnabled = function (message) {
  6702. var formattedMessage = Tools._FormatMessage(message);
  6703. console.log("BJS - " + formattedMessage);
  6704. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6705. Tools._AddLogEntry(entry);
  6706. };
  6707. Tools._WarnDisabled = function (message) {
  6708. // nothing to do
  6709. };
  6710. Tools._WarnEnabled = function (message) {
  6711. var formattedMessage = Tools._FormatMessage(message);
  6712. console.warn("BJS - " + formattedMessage);
  6713. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6714. Tools._AddLogEntry(entry);
  6715. };
  6716. Tools._ErrorDisabled = function (message) {
  6717. // nothing to do
  6718. };
  6719. Tools._ErrorEnabled = function (message) {
  6720. Tools.errorsCount++;
  6721. var formattedMessage = Tools._FormatMessage(message);
  6722. console.error("BJS - " + formattedMessage);
  6723. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6724. Tools._AddLogEntry(entry);
  6725. };
  6726. Object.defineProperty(Tools, "LogCache", {
  6727. get: function () {
  6728. return Tools._LogCache;
  6729. },
  6730. enumerable: true,
  6731. configurable: true
  6732. });
  6733. Tools.ClearLogCache = function () {
  6734. Tools._LogCache = "";
  6735. Tools.errorsCount = 0;
  6736. };
  6737. Object.defineProperty(Tools, "LogLevels", {
  6738. set: function (level) {
  6739. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6740. Tools.Log = Tools._LogEnabled;
  6741. }
  6742. else {
  6743. Tools.Log = Tools._LogDisabled;
  6744. }
  6745. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6746. Tools.Warn = Tools._WarnEnabled;
  6747. }
  6748. else {
  6749. Tools.Warn = Tools._WarnDisabled;
  6750. }
  6751. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6752. Tools.Error = Tools._ErrorEnabled;
  6753. }
  6754. else {
  6755. Tools.Error = Tools._ErrorDisabled;
  6756. }
  6757. },
  6758. enumerable: true,
  6759. configurable: true
  6760. });
  6761. Tools.IsWindowObjectExist = function () {
  6762. return (typeof window) !== "undefined";
  6763. };
  6764. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6765. get: function () {
  6766. return Tools._PerformanceNoneLogLevel;
  6767. },
  6768. enumerable: true,
  6769. configurable: true
  6770. });
  6771. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6772. get: function () {
  6773. return Tools._PerformanceUserMarkLogLevel;
  6774. },
  6775. enumerable: true,
  6776. configurable: true
  6777. });
  6778. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6779. get: function () {
  6780. return Tools._PerformanceConsoleLogLevel;
  6781. },
  6782. enumerable: true,
  6783. configurable: true
  6784. });
  6785. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6786. set: function (level) {
  6787. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6788. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6789. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6790. return;
  6791. }
  6792. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6793. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6794. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6795. return;
  6796. }
  6797. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6798. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6799. },
  6800. enumerable: true,
  6801. configurable: true
  6802. });
  6803. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6804. };
  6805. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6806. };
  6807. Tools._StartUserMark = function (counterName, condition) {
  6808. if (condition === void 0) { condition = true; }
  6809. if (!Tools._performance) {
  6810. if (!Tools.IsWindowObjectExist()) {
  6811. return;
  6812. }
  6813. Tools._performance = window.performance;
  6814. }
  6815. if (!condition || !Tools._performance.mark) {
  6816. return;
  6817. }
  6818. Tools._performance.mark(counterName + "-Begin");
  6819. };
  6820. Tools._EndUserMark = function (counterName, condition) {
  6821. if (condition === void 0) { condition = true; }
  6822. if (!condition || !Tools._performance.mark) {
  6823. return;
  6824. }
  6825. Tools._performance.mark(counterName + "-End");
  6826. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6827. };
  6828. Tools._StartPerformanceConsole = function (counterName, condition) {
  6829. if (condition === void 0) { condition = true; }
  6830. if (!condition) {
  6831. return;
  6832. }
  6833. Tools._StartUserMark(counterName, condition);
  6834. if (console.time) {
  6835. console.time(counterName);
  6836. }
  6837. };
  6838. Tools._EndPerformanceConsole = function (counterName, condition) {
  6839. if (condition === void 0) { condition = true; }
  6840. if (!condition) {
  6841. return;
  6842. }
  6843. Tools._EndUserMark(counterName, condition);
  6844. if (console.time) {
  6845. console.timeEnd(counterName);
  6846. }
  6847. };
  6848. Object.defineProperty(Tools, "Now", {
  6849. get: function () {
  6850. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6851. return window.performance.now();
  6852. }
  6853. return new Date().getTime();
  6854. },
  6855. enumerable: true,
  6856. configurable: true
  6857. });
  6858. /**
  6859. * This method will return the name of the class used to create the instance of the given object.
  6860. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6861. * @param object the object to get the class name from
  6862. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6863. */
  6864. Tools.GetClassName = function (object, isType) {
  6865. if (isType === void 0) { isType = false; }
  6866. var name = null;
  6867. if (!isType && object.getClassName) {
  6868. name = object.getClassName();
  6869. }
  6870. else {
  6871. if (object instanceof Object) {
  6872. var classObj = isType ? object : Object.getPrototypeOf(object);
  6873. name = classObj.constructor["__bjsclassName__"];
  6874. }
  6875. if (!name) {
  6876. name = typeof object;
  6877. }
  6878. }
  6879. return name;
  6880. };
  6881. Tools.First = function (array, predicate) {
  6882. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6883. var el = array_1[_i];
  6884. if (predicate(el)) {
  6885. return el;
  6886. }
  6887. }
  6888. return null;
  6889. };
  6890. /**
  6891. * This method will return the name of the full name of the class, including its owning module (if any).
  6892. * 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).
  6893. * @param object the object to get the class name from
  6894. * @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.
  6895. */
  6896. Tools.getFullClassName = function (object, isType) {
  6897. if (isType === void 0) { isType = false; }
  6898. var className = null;
  6899. var moduleName = null;
  6900. if (!isType && object.getClassName) {
  6901. className = object.getClassName();
  6902. }
  6903. else {
  6904. if (object instanceof Object) {
  6905. var classObj = isType ? object : Object.getPrototypeOf(object);
  6906. className = classObj.constructor["__bjsclassName__"];
  6907. moduleName = classObj.constructor["__bjsmoduleName__"];
  6908. }
  6909. if (!className) {
  6910. className = typeof object;
  6911. }
  6912. }
  6913. if (!className) {
  6914. return null;
  6915. }
  6916. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6917. };
  6918. /**
  6919. * 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.
  6920. * @param array
  6921. */
  6922. Tools.arrayOrStringFeeder = function (array) {
  6923. return function (index) {
  6924. if (index >= array.length) {
  6925. return null;
  6926. }
  6927. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6928. if (val && val.getHashCode) {
  6929. val = val.getHashCode();
  6930. }
  6931. if (typeof val === "string") {
  6932. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6933. }
  6934. return val;
  6935. };
  6936. };
  6937. /**
  6938. * Compute the hashCode of a stream of number
  6939. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6940. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6941. * @return the hash code computed
  6942. */
  6943. Tools.hashCodeFromStream = function (feeder) {
  6944. // Based from here: http://stackoverflow.com/a/7616484/802124
  6945. var hash = 0;
  6946. var index = 0;
  6947. var chr = feeder(index++);
  6948. while (chr != null) {
  6949. hash = ((hash << 5) - hash) + chr;
  6950. hash |= 0; // Convert to 32bit integer
  6951. chr = feeder(index++);
  6952. }
  6953. return hash;
  6954. };
  6955. Tools.BaseUrl = "";
  6956. Tools.CorsBehavior = "anonymous";
  6957. Tools.UseFallbackTexture = true;
  6958. /**
  6959. * Use this object to register external classes like custom textures or material
  6960. * to allow the laoders to instantiate them
  6961. */
  6962. Tools.RegisteredExternalClasses = {};
  6963. // Used in case of a texture loading problem
  6964. 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";
  6965. Tools.PreprocessUrl = function (url) {
  6966. return url;
  6967. };
  6968. // Logs
  6969. Tools._NoneLogLevel = 0;
  6970. Tools._MessageLogLevel = 1;
  6971. Tools._WarningLogLevel = 2;
  6972. Tools._ErrorLogLevel = 4;
  6973. Tools._LogCache = "";
  6974. Tools.errorsCount = 0;
  6975. Tools.Log = Tools._LogEnabled;
  6976. Tools.Warn = Tools._WarnEnabled;
  6977. Tools.Error = Tools._ErrorEnabled;
  6978. // Performances
  6979. Tools._PerformanceNoneLogLevel = 0;
  6980. Tools._PerformanceUserMarkLogLevel = 1;
  6981. Tools._PerformanceConsoleLogLevel = 2;
  6982. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6983. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6984. return Tools;
  6985. }());
  6986. BABYLON.Tools = Tools;
  6987. /**
  6988. * This class is used to track a performance counter which is number based.
  6989. * The user has access to many properties which give statistics of different nature
  6990. *
  6991. * The implementer can track two kinds of Performance Counter: time and count
  6992. * 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.
  6993. * 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.
  6994. */
  6995. var PerfCounter = /** @class */ (function () {
  6996. function PerfCounter() {
  6997. this._startMonitoringTime = 0;
  6998. this._min = 0;
  6999. this._max = 0;
  7000. this._average = 0;
  7001. this._lastSecAverage = 0;
  7002. this._current = 0;
  7003. this._totalValueCount = 0;
  7004. this._totalAccumulated = 0;
  7005. this._lastSecAccumulated = 0;
  7006. this._lastSecTime = 0;
  7007. this._lastSecValueCount = 0;
  7008. }
  7009. Object.defineProperty(PerfCounter.prototype, "min", {
  7010. /**
  7011. * Returns the smallest value ever
  7012. */
  7013. get: function () {
  7014. return this._min;
  7015. },
  7016. enumerable: true,
  7017. configurable: true
  7018. });
  7019. Object.defineProperty(PerfCounter.prototype, "max", {
  7020. /**
  7021. * Returns the biggest value ever
  7022. */
  7023. get: function () {
  7024. return this._max;
  7025. },
  7026. enumerable: true,
  7027. configurable: true
  7028. });
  7029. Object.defineProperty(PerfCounter.prototype, "average", {
  7030. /**
  7031. * Returns the average value since the performance counter is running
  7032. */
  7033. get: function () {
  7034. return this._average;
  7035. },
  7036. enumerable: true,
  7037. configurable: true
  7038. });
  7039. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7040. /**
  7041. * Returns the average value of the last second the counter was monitored
  7042. */
  7043. get: function () {
  7044. return this._lastSecAverage;
  7045. },
  7046. enumerable: true,
  7047. configurable: true
  7048. });
  7049. Object.defineProperty(PerfCounter.prototype, "current", {
  7050. /**
  7051. * Returns the current value
  7052. */
  7053. get: function () {
  7054. return this._current;
  7055. },
  7056. enumerable: true,
  7057. configurable: true
  7058. });
  7059. Object.defineProperty(PerfCounter.prototype, "total", {
  7060. get: function () {
  7061. return this._totalAccumulated;
  7062. },
  7063. enumerable: true,
  7064. configurable: true
  7065. });
  7066. Object.defineProperty(PerfCounter.prototype, "count", {
  7067. get: function () {
  7068. return this._totalValueCount;
  7069. },
  7070. enumerable: true,
  7071. configurable: true
  7072. });
  7073. /**
  7074. * Call this method to start monitoring a new frame.
  7075. * 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.
  7076. */
  7077. PerfCounter.prototype.fetchNewFrame = function () {
  7078. this._totalValueCount++;
  7079. this._current = 0;
  7080. this._lastSecValueCount++;
  7081. };
  7082. /**
  7083. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7084. * @param newCount the count value to add to the monitored count
  7085. * @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.
  7086. */
  7087. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7088. if (!PerfCounter.Enabled) {
  7089. return;
  7090. }
  7091. this._current += newCount;
  7092. if (fetchResult) {
  7093. this._fetchResult();
  7094. }
  7095. };
  7096. /**
  7097. * Start monitoring this performance counter
  7098. */
  7099. PerfCounter.prototype.beginMonitoring = function () {
  7100. if (!PerfCounter.Enabled) {
  7101. return;
  7102. }
  7103. this._startMonitoringTime = Tools.Now;
  7104. };
  7105. /**
  7106. * Compute the time lapsed since the previous beginMonitoring() call.
  7107. * @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
  7108. */
  7109. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7110. if (newFrame === void 0) { newFrame = true; }
  7111. if (!PerfCounter.Enabled) {
  7112. return;
  7113. }
  7114. if (newFrame) {
  7115. this.fetchNewFrame();
  7116. }
  7117. var currentTime = Tools.Now;
  7118. this._current = currentTime - this._startMonitoringTime;
  7119. if (newFrame) {
  7120. this._fetchResult();
  7121. }
  7122. };
  7123. PerfCounter.prototype._fetchResult = function () {
  7124. this._totalAccumulated += this._current;
  7125. this._lastSecAccumulated += this._current;
  7126. // Min/Max update
  7127. this._min = Math.min(this._min, this._current);
  7128. this._max = Math.max(this._max, this._current);
  7129. this._average = this._totalAccumulated / this._totalValueCount;
  7130. // Reset last sec?
  7131. var now = Tools.Now;
  7132. if ((now - this._lastSecTime) > 1000) {
  7133. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7134. this._lastSecTime = now;
  7135. this._lastSecAccumulated = 0;
  7136. this._lastSecValueCount = 0;
  7137. }
  7138. };
  7139. PerfCounter.Enabled = true;
  7140. return PerfCounter;
  7141. }());
  7142. BABYLON.PerfCounter = PerfCounter;
  7143. /**
  7144. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7145. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7146. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7147. * @param name The name of the class, case should be preserved
  7148. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7149. */
  7150. function className(name, module) {
  7151. return function (target) {
  7152. target["__bjsclassName__"] = name;
  7153. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7154. };
  7155. }
  7156. BABYLON.className = className;
  7157. /**
  7158. * An implementation of a loop for asynchronous functions.
  7159. */
  7160. var AsyncLoop = /** @class */ (function () {
  7161. /**
  7162. * Constroctor.
  7163. * @param iterations the number of iterations.
  7164. * @param _fn the function to run each iteration
  7165. * @param _successCallback the callback that will be called upon succesful execution
  7166. * @param offset starting offset.
  7167. */
  7168. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7169. if (offset === void 0) { offset = 0; }
  7170. this.iterations = iterations;
  7171. this._fn = _fn;
  7172. this._successCallback = _successCallback;
  7173. this.index = offset - 1;
  7174. this._done = false;
  7175. }
  7176. /**
  7177. * Execute the next iteration. Must be called after the last iteration was finished.
  7178. */
  7179. AsyncLoop.prototype.executeNext = function () {
  7180. if (!this._done) {
  7181. if (this.index + 1 < this.iterations) {
  7182. ++this.index;
  7183. this._fn(this);
  7184. }
  7185. else {
  7186. this.breakLoop();
  7187. }
  7188. }
  7189. };
  7190. /**
  7191. * Break the loop and run the success callback.
  7192. */
  7193. AsyncLoop.prototype.breakLoop = function () {
  7194. this._done = true;
  7195. this._successCallback();
  7196. };
  7197. /**
  7198. * Helper function
  7199. */
  7200. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7201. if (offset === void 0) { offset = 0; }
  7202. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7203. loop.executeNext();
  7204. return loop;
  7205. };
  7206. /**
  7207. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7208. * @param iterations total number of iterations
  7209. * @param syncedIterations number of synchronous iterations in each async iteration.
  7210. * @param fn the function to call each iteration.
  7211. * @param callback a success call back that will be called when iterating stops.
  7212. * @param breakFunction a break condition (optional)
  7213. * @param timeout timeout settings for the setTimeout function. default - 0.
  7214. * @constructor
  7215. */
  7216. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7217. if (timeout === void 0) { timeout = 0; }
  7218. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7219. if (breakFunction && breakFunction())
  7220. loop.breakLoop();
  7221. else {
  7222. setTimeout(function () {
  7223. for (var i = 0; i < syncedIterations; ++i) {
  7224. var iteration = (loop.index * syncedIterations) + i;
  7225. if (iteration >= iterations)
  7226. break;
  7227. fn(iteration);
  7228. if (breakFunction && breakFunction()) {
  7229. loop.breakLoop();
  7230. break;
  7231. }
  7232. }
  7233. loop.executeNext();
  7234. }, timeout);
  7235. }
  7236. }, callback);
  7237. };
  7238. return AsyncLoop;
  7239. }());
  7240. BABYLON.AsyncLoop = AsyncLoop;
  7241. })(BABYLON || (BABYLON = {}));
  7242. //# sourceMappingURL=babylon.tools.js.map
  7243. var BABYLON;
  7244. (function (BABYLON) {
  7245. var Internals;
  7246. (function (Internals) {
  7247. var _AlphaState = /** @class */ (function () {
  7248. /**
  7249. * Initializes the state.
  7250. */
  7251. function _AlphaState() {
  7252. this._isAlphaBlendDirty = false;
  7253. this._isBlendFunctionParametersDirty = false;
  7254. this._isBlendEquationParametersDirty = false;
  7255. this._isBlendConstantsDirty = false;
  7256. this._alphaBlend = false;
  7257. this._blendFunctionParameters = new Array(4);
  7258. this._blendEquationParameters = new Array(2);
  7259. this._blendConstants = new Array(4);
  7260. this.reset();
  7261. }
  7262. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7263. get: function () {
  7264. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7265. },
  7266. enumerable: true,
  7267. configurable: true
  7268. });
  7269. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7270. get: function () {
  7271. return this._alphaBlend;
  7272. },
  7273. set: function (value) {
  7274. if (this._alphaBlend === value) {
  7275. return;
  7276. }
  7277. this._alphaBlend = value;
  7278. this._isAlphaBlendDirty = true;
  7279. },
  7280. enumerable: true,
  7281. configurable: true
  7282. });
  7283. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7284. if (this._blendConstants[0] === r &&
  7285. this._blendConstants[1] === g &&
  7286. this._blendConstants[2] === b &&
  7287. this._blendConstants[3] === a) {
  7288. return;
  7289. }
  7290. this._blendConstants[0] = r;
  7291. this._blendConstants[1] = g;
  7292. this._blendConstants[2] = b;
  7293. this._blendConstants[3] = a;
  7294. this._isBlendConstantsDirty = true;
  7295. };
  7296. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7297. if (this._blendFunctionParameters[0] === value0 &&
  7298. this._blendFunctionParameters[1] === value1 &&
  7299. this._blendFunctionParameters[2] === value2 &&
  7300. this._blendFunctionParameters[3] === value3) {
  7301. return;
  7302. }
  7303. this._blendFunctionParameters[0] = value0;
  7304. this._blendFunctionParameters[1] = value1;
  7305. this._blendFunctionParameters[2] = value2;
  7306. this._blendFunctionParameters[3] = value3;
  7307. this._isBlendFunctionParametersDirty = true;
  7308. };
  7309. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7310. if (this._blendEquationParameters[0] === rgb &&
  7311. this._blendEquationParameters[1] === alpha) {
  7312. return;
  7313. }
  7314. this._blendEquationParameters[0] = rgb;
  7315. this._blendEquationParameters[1] = alpha;
  7316. this._isBlendEquationParametersDirty = true;
  7317. };
  7318. _AlphaState.prototype.reset = function () {
  7319. this._alphaBlend = false;
  7320. this._blendFunctionParameters[0] = null;
  7321. this._blendFunctionParameters[1] = null;
  7322. this._blendFunctionParameters[2] = null;
  7323. this._blendFunctionParameters[3] = null;
  7324. this._blendEquationParameters[0] = null;
  7325. this._blendEquationParameters[1] = null;
  7326. this._blendConstants[0] = null;
  7327. this._blendConstants[1] = null;
  7328. this._blendConstants[2] = null;
  7329. this._blendConstants[3] = null;
  7330. this._isAlphaBlendDirty = true;
  7331. this._isBlendFunctionParametersDirty = false;
  7332. this._isBlendEquationParametersDirty = false;
  7333. this._isBlendConstantsDirty = false;
  7334. };
  7335. _AlphaState.prototype.apply = function (gl) {
  7336. if (!this.isDirty) {
  7337. return;
  7338. }
  7339. // Alpha blend
  7340. if (this._isAlphaBlendDirty) {
  7341. if (this._alphaBlend) {
  7342. gl.enable(gl.BLEND);
  7343. }
  7344. else {
  7345. gl.disable(gl.BLEND);
  7346. }
  7347. this._isAlphaBlendDirty = false;
  7348. }
  7349. // Alpha function
  7350. if (this._isBlendFunctionParametersDirty) {
  7351. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7352. this._isBlendFunctionParametersDirty = false;
  7353. }
  7354. // Alpha equation
  7355. if (this._isBlendEquationParametersDirty) {
  7356. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7357. this._isBlendEquationParametersDirty = false;
  7358. }
  7359. // Constants
  7360. if (this._isBlendConstantsDirty) {
  7361. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7362. this._isBlendConstantsDirty = false;
  7363. }
  7364. };
  7365. return _AlphaState;
  7366. }());
  7367. Internals._AlphaState = _AlphaState;
  7368. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7369. })(BABYLON || (BABYLON = {}));
  7370. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7371. var BABYLON;
  7372. (function (BABYLON) {
  7373. var Internals;
  7374. (function (Internals) {
  7375. var _DepthCullingState = /** @class */ (function () {
  7376. /**
  7377. * Initializes the state.
  7378. */
  7379. function _DepthCullingState() {
  7380. this._isDepthTestDirty = false;
  7381. this._isDepthMaskDirty = false;
  7382. this._isDepthFuncDirty = false;
  7383. this._isCullFaceDirty = false;
  7384. this._isCullDirty = false;
  7385. this._isZOffsetDirty = false;
  7386. this.reset();
  7387. }
  7388. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7389. get: function () {
  7390. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7391. },
  7392. enumerable: true,
  7393. configurable: true
  7394. });
  7395. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7396. get: function () {
  7397. return this._zOffset;
  7398. },
  7399. set: function (value) {
  7400. if (this._zOffset === value) {
  7401. return;
  7402. }
  7403. this._zOffset = value;
  7404. this._isZOffsetDirty = true;
  7405. },
  7406. enumerable: true,
  7407. configurable: true
  7408. });
  7409. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7410. get: function () {
  7411. return this._cullFace;
  7412. },
  7413. set: function (value) {
  7414. if (this._cullFace === value) {
  7415. return;
  7416. }
  7417. this._cullFace = value;
  7418. this._isCullFaceDirty = true;
  7419. },
  7420. enumerable: true,
  7421. configurable: true
  7422. });
  7423. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7424. get: function () {
  7425. return this._cull;
  7426. },
  7427. set: function (value) {
  7428. if (this._cull === value) {
  7429. return;
  7430. }
  7431. this._cull = value;
  7432. this._isCullDirty = true;
  7433. },
  7434. enumerable: true,
  7435. configurable: true
  7436. });
  7437. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7438. get: function () {
  7439. return this._depthFunc;
  7440. },
  7441. set: function (value) {
  7442. if (this._depthFunc === value) {
  7443. return;
  7444. }
  7445. this._depthFunc = value;
  7446. this._isDepthFuncDirty = true;
  7447. },
  7448. enumerable: true,
  7449. configurable: true
  7450. });
  7451. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7452. get: function () {
  7453. return this._depthMask;
  7454. },
  7455. set: function (value) {
  7456. if (this._depthMask === value) {
  7457. return;
  7458. }
  7459. this._depthMask = value;
  7460. this._isDepthMaskDirty = true;
  7461. },
  7462. enumerable: true,
  7463. configurable: true
  7464. });
  7465. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7466. get: function () {
  7467. return this._depthTest;
  7468. },
  7469. set: function (value) {
  7470. if (this._depthTest === value) {
  7471. return;
  7472. }
  7473. this._depthTest = value;
  7474. this._isDepthTestDirty = true;
  7475. },
  7476. enumerable: true,
  7477. configurable: true
  7478. });
  7479. _DepthCullingState.prototype.reset = function () {
  7480. this._depthMask = true;
  7481. this._depthTest = true;
  7482. this._depthFunc = null;
  7483. this._cullFace = null;
  7484. this._cull = null;
  7485. this._zOffset = 0;
  7486. this._isDepthTestDirty = true;
  7487. this._isDepthMaskDirty = true;
  7488. this._isDepthFuncDirty = false;
  7489. this._isCullFaceDirty = false;
  7490. this._isCullDirty = false;
  7491. this._isZOffsetDirty = false;
  7492. };
  7493. _DepthCullingState.prototype.apply = function (gl) {
  7494. if (!this.isDirty) {
  7495. return;
  7496. }
  7497. // Cull
  7498. if (this._isCullDirty) {
  7499. if (this.cull) {
  7500. gl.enable(gl.CULL_FACE);
  7501. }
  7502. else {
  7503. gl.disable(gl.CULL_FACE);
  7504. }
  7505. this._isCullDirty = false;
  7506. }
  7507. // Cull face
  7508. if (this._isCullFaceDirty) {
  7509. gl.cullFace(this.cullFace);
  7510. this._isCullFaceDirty = false;
  7511. }
  7512. // Depth mask
  7513. if (this._isDepthMaskDirty) {
  7514. gl.depthMask(this.depthMask);
  7515. this._isDepthMaskDirty = false;
  7516. }
  7517. // Depth test
  7518. if (this._isDepthTestDirty) {
  7519. if (this.depthTest) {
  7520. gl.enable(gl.DEPTH_TEST);
  7521. }
  7522. else {
  7523. gl.disable(gl.DEPTH_TEST);
  7524. }
  7525. this._isDepthTestDirty = false;
  7526. }
  7527. // Depth func
  7528. if (this._isDepthFuncDirty) {
  7529. gl.depthFunc(this.depthFunc);
  7530. this._isDepthFuncDirty = false;
  7531. }
  7532. // zOffset
  7533. if (this._isZOffsetDirty) {
  7534. if (this.zOffset) {
  7535. gl.enable(gl.POLYGON_OFFSET_FILL);
  7536. gl.polygonOffset(this.zOffset, 0);
  7537. }
  7538. else {
  7539. gl.disable(gl.POLYGON_OFFSET_FILL);
  7540. }
  7541. this._isZOffsetDirty = false;
  7542. }
  7543. };
  7544. return _DepthCullingState;
  7545. }());
  7546. Internals._DepthCullingState = _DepthCullingState;
  7547. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7548. })(BABYLON || (BABYLON = {}));
  7549. //# sourceMappingURL=babylon.depthCullingState.js.map
  7550. var BABYLON;
  7551. (function (BABYLON) {
  7552. var Internals;
  7553. (function (Internals) {
  7554. var _StencilState = /** @class */ (function () {
  7555. function _StencilState() {
  7556. this._isStencilTestDirty = false;
  7557. this._isStencilMaskDirty = false;
  7558. this._isStencilFuncDirty = false;
  7559. this._isStencilOpDirty = false;
  7560. this.reset();
  7561. }
  7562. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7563. get: function () {
  7564. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7565. },
  7566. enumerable: true,
  7567. configurable: true
  7568. });
  7569. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7570. get: function () {
  7571. return this._stencilFunc;
  7572. },
  7573. set: function (value) {
  7574. if (this._stencilFunc === value) {
  7575. return;
  7576. }
  7577. this._stencilFunc = value;
  7578. this._isStencilFuncDirty = true;
  7579. },
  7580. enumerable: true,
  7581. configurable: true
  7582. });
  7583. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7584. get: function () {
  7585. return this._stencilFuncRef;
  7586. },
  7587. set: function (value) {
  7588. if (this._stencilFuncRef === value) {
  7589. return;
  7590. }
  7591. this._stencilFuncRef = value;
  7592. this._isStencilFuncDirty = true;
  7593. },
  7594. enumerable: true,
  7595. configurable: true
  7596. });
  7597. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7598. get: function () {
  7599. return this._stencilFuncMask;
  7600. },
  7601. set: function (value) {
  7602. if (this._stencilFuncMask === value) {
  7603. return;
  7604. }
  7605. this._stencilFuncMask = value;
  7606. this._isStencilFuncDirty = true;
  7607. },
  7608. enumerable: true,
  7609. configurable: true
  7610. });
  7611. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7612. get: function () {
  7613. return this._stencilOpStencilFail;
  7614. },
  7615. set: function (value) {
  7616. if (this._stencilOpStencilFail === value) {
  7617. return;
  7618. }
  7619. this._stencilOpStencilFail = value;
  7620. this._isStencilOpDirty = true;
  7621. },
  7622. enumerable: true,
  7623. configurable: true
  7624. });
  7625. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7626. get: function () {
  7627. return this._stencilOpDepthFail;
  7628. },
  7629. set: function (value) {
  7630. if (this._stencilOpDepthFail === value) {
  7631. return;
  7632. }
  7633. this._stencilOpDepthFail = value;
  7634. this._isStencilOpDirty = true;
  7635. },
  7636. enumerable: true,
  7637. configurable: true
  7638. });
  7639. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7640. get: function () {
  7641. return this._stencilOpStencilDepthPass;
  7642. },
  7643. set: function (value) {
  7644. if (this._stencilOpStencilDepthPass === value) {
  7645. return;
  7646. }
  7647. this._stencilOpStencilDepthPass = value;
  7648. this._isStencilOpDirty = true;
  7649. },
  7650. enumerable: true,
  7651. configurable: true
  7652. });
  7653. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7654. get: function () {
  7655. return this._stencilMask;
  7656. },
  7657. set: function (value) {
  7658. if (this._stencilMask === value) {
  7659. return;
  7660. }
  7661. this._stencilMask = value;
  7662. this._isStencilMaskDirty = true;
  7663. },
  7664. enumerable: true,
  7665. configurable: true
  7666. });
  7667. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7668. get: function () {
  7669. return this._stencilTest;
  7670. },
  7671. set: function (value) {
  7672. if (this._stencilTest === value) {
  7673. return;
  7674. }
  7675. this._stencilTest = value;
  7676. this._isStencilTestDirty = true;
  7677. },
  7678. enumerable: true,
  7679. configurable: true
  7680. });
  7681. _StencilState.prototype.reset = function () {
  7682. this._stencilTest = false;
  7683. this._stencilMask = 0xFF;
  7684. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7685. this._stencilFuncRef = 1;
  7686. this._stencilFuncMask = 0xFF;
  7687. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7688. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7689. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7690. this._isStencilTestDirty = true;
  7691. this._isStencilMaskDirty = true;
  7692. this._isStencilFuncDirty = true;
  7693. this._isStencilOpDirty = true;
  7694. };
  7695. _StencilState.prototype.apply = function (gl) {
  7696. if (!this.isDirty) {
  7697. return;
  7698. }
  7699. // Stencil test
  7700. if (this._isStencilTestDirty) {
  7701. if (this.stencilTest) {
  7702. gl.enable(gl.STENCIL_TEST);
  7703. }
  7704. else {
  7705. gl.disable(gl.STENCIL_TEST);
  7706. }
  7707. this._isStencilTestDirty = false;
  7708. }
  7709. // Stencil mask
  7710. if (this._isStencilMaskDirty) {
  7711. gl.stencilMask(this.stencilMask);
  7712. this._isStencilMaskDirty = false;
  7713. }
  7714. // Stencil func
  7715. if (this._isStencilFuncDirty) {
  7716. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7717. this._isStencilFuncDirty = false;
  7718. }
  7719. // Stencil op
  7720. if (this._isStencilOpDirty) {
  7721. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7722. this._isStencilOpDirty = false;
  7723. }
  7724. };
  7725. return _StencilState;
  7726. }());
  7727. Internals._StencilState = _StencilState;
  7728. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7729. })(BABYLON || (BABYLON = {}));
  7730. //# sourceMappingURL=babylon.stencilState.js.map
  7731. var BABYLON;
  7732. (function (BABYLON) {
  7733. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7734. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7735. };
  7736. var compileRawShader = function (gl, source, type) {
  7737. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7738. gl.shaderSource(shader, source);
  7739. gl.compileShader(shader);
  7740. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7741. var log = gl.getShaderInfoLog(shader);
  7742. if (log) {
  7743. throw new Error(log);
  7744. }
  7745. }
  7746. if (!shader) {
  7747. throw new Error("Something went wrong while compile the shader.");
  7748. }
  7749. return shader;
  7750. };
  7751. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7752. var magFilter = gl.NEAREST;
  7753. var minFilter = gl.NEAREST;
  7754. switch (samplingMode) {
  7755. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7756. magFilter = gl.LINEAR;
  7757. if (generateMipMaps) {
  7758. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7759. }
  7760. else {
  7761. minFilter = gl.LINEAR;
  7762. }
  7763. break;
  7764. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7765. magFilter = gl.LINEAR;
  7766. if (generateMipMaps) {
  7767. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7768. }
  7769. else {
  7770. minFilter = gl.LINEAR;
  7771. }
  7772. break;
  7773. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7774. magFilter = gl.NEAREST;
  7775. if (generateMipMaps) {
  7776. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7777. }
  7778. else {
  7779. minFilter = gl.NEAREST;
  7780. }
  7781. break;
  7782. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7783. magFilter = gl.NEAREST;
  7784. if (generateMipMaps) {
  7785. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7786. }
  7787. else {
  7788. minFilter = gl.NEAREST;
  7789. }
  7790. break;
  7791. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7792. magFilter = gl.NEAREST;
  7793. if (generateMipMaps) {
  7794. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7795. }
  7796. else {
  7797. minFilter = gl.LINEAR;
  7798. }
  7799. break;
  7800. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7801. magFilter = gl.NEAREST;
  7802. if (generateMipMaps) {
  7803. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7804. }
  7805. else {
  7806. minFilter = gl.LINEAR;
  7807. }
  7808. break;
  7809. case BABYLON.Texture.NEAREST_LINEAR:
  7810. magFilter = gl.NEAREST;
  7811. minFilter = gl.LINEAR;
  7812. break;
  7813. case BABYLON.Texture.NEAREST_NEAREST:
  7814. magFilter = gl.NEAREST;
  7815. minFilter = gl.NEAREST;
  7816. break;
  7817. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7818. magFilter = gl.LINEAR;
  7819. if (generateMipMaps) {
  7820. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7821. }
  7822. else {
  7823. minFilter = gl.NEAREST;
  7824. }
  7825. break;
  7826. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7827. magFilter = gl.LINEAR;
  7828. if (generateMipMaps) {
  7829. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7830. }
  7831. else {
  7832. minFilter = gl.NEAREST;
  7833. }
  7834. break;
  7835. case BABYLON.Texture.LINEAR_LINEAR:
  7836. magFilter = gl.LINEAR;
  7837. minFilter = gl.LINEAR;
  7838. break;
  7839. case BABYLON.Texture.LINEAR_NEAREST:
  7840. magFilter = gl.LINEAR;
  7841. minFilter = gl.NEAREST;
  7842. break;
  7843. }
  7844. return {
  7845. min: minFilter,
  7846. mag: magFilter
  7847. };
  7848. };
  7849. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7850. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7851. var img;
  7852. var onload = function () {
  7853. loadedImages[index] = img;
  7854. loadedImages._internalCount++;
  7855. if (scene) {
  7856. scene._removePendingData(img);
  7857. }
  7858. if (loadedImages._internalCount === 6) {
  7859. onfinish(loadedImages);
  7860. }
  7861. };
  7862. var onerror = function (message, exception) {
  7863. if (scene) {
  7864. scene._removePendingData(img);
  7865. }
  7866. if (onErrorCallBack) {
  7867. onErrorCallBack(message, exception);
  7868. }
  7869. };
  7870. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7871. if (scene) {
  7872. scene._addPendingData(img);
  7873. }
  7874. };
  7875. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7876. if (onError === void 0) { onError = null; }
  7877. var loadedImages = [];
  7878. loadedImages._internalCount = 0;
  7879. for (var index = 0; index < 6; index++) {
  7880. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7881. }
  7882. };
  7883. var BufferPointer = /** @class */ (function () {
  7884. function BufferPointer() {
  7885. }
  7886. return BufferPointer;
  7887. }());
  7888. var InstancingAttributeInfo = /** @class */ (function () {
  7889. function InstancingAttributeInfo() {
  7890. }
  7891. return InstancingAttributeInfo;
  7892. }());
  7893. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7894. /**
  7895. * Define options used to create a render target texture
  7896. */
  7897. var RenderTargetCreationOptions = /** @class */ (function () {
  7898. function RenderTargetCreationOptions() {
  7899. }
  7900. return RenderTargetCreationOptions;
  7901. }());
  7902. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7903. /**
  7904. * Regroup several parameters relative to the browser in use
  7905. */
  7906. var EngineCapabilities = /** @class */ (function () {
  7907. function EngineCapabilities() {
  7908. }
  7909. return EngineCapabilities;
  7910. }());
  7911. BABYLON.EngineCapabilities = EngineCapabilities;
  7912. /**
  7913. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7914. */
  7915. var Engine = /** @class */ (function () {
  7916. /**
  7917. * @constructor
  7918. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7919. * @param {boolean} [antialias] - enable antialias
  7920. * @param options - further options to be sent to the getContext function
  7921. */
  7922. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7923. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7924. var _this = this;
  7925. // Public members
  7926. this.forcePOTTextures = false;
  7927. this.isFullscreen = false;
  7928. this.isPointerLock = false;
  7929. this.cullBackFaces = true;
  7930. this.renderEvenInBackground = true;
  7931. this.preventCacheWipeBetweenFrames = false;
  7932. // To enable/disable IDB support and avoid XHR on .manifest
  7933. this.enableOfflineSupport = false;
  7934. this.scenes = new Array();
  7935. this.postProcesses = new Array();
  7936. // Observables
  7937. /**
  7938. * Observable event triggered each time the rendering canvas is resized
  7939. */
  7940. this.onResizeObservable = new BABYLON.Observable();
  7941. /**
  7942. * Observable event triggered each time the canvas loses focus
  7943. */
  7944. this.onCanvasBlurObservable = new BABYLON.Observable();
  7945. /**
  7946. * Observable event triggered each time the canvas gains focus
  7947. */
  7948. this.onCanvasFocusObservable = new BABYLON.Observable();
  7949. /**
  7950. * Observable event triggered each time the canvas receives pointerout event
  7951. */
  7952. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7953. /**
  7954. * Observable event triggered before each texture is initialized
  7955. */
  7956. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7957. //WebVR
  7958. this._vrDisplay = undefined;
  7959. this._vrSupported = false;
  7960. this._vrExclusivePointerMode = false;
  7961. // Uniform buffers list
  7962. this.disableUniformBuffers = false;
  7963. this._uniformBuffers = new Array();
  7964. // Observables
  7965. /**
  7966. * Observable raised when the engine begins a new frame
  7967. */
  7968. this.onBeginFrameObservable = new BABYLON.Observable();
  7969. /**
  7970. * Observable raised when the engine ends the current frame
  7971. */
  7972. this.onEndFrameObservable = new BABYLON.Observable();
  7973. /**
  7974. * Observable raised when the engine is about to compile a shader
  7975. */
  7976. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7977. /**
  7978. * Observable raised when the engine has jsut compiled a shader
  7979. */
  7980. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7981. this._windowIsBackground = false;
  7982. this._webGLVersion = 1.0;
  7983. this._badOS = false;
  7984. this._badDesktopOS = false;
  7985. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7986. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7987. this.onVRRequestPresentStart = new BABYLON.Observable();
  7988. this._colorWrite = true;
  7989. this._drawCalls = new BABYLON.PerfCounter();
  7990. this._renderingQueueLaunched = false;
  7991. this._activeRenderLoops = new Array();
  7992. // Deterministic lockstepMaxSteps
  7993. this._deterministicLockstep = false;
  7994. this._lockstepMaxSteps = 4;
  7995. // Lost context
  7996. this.onContextLostObservable = new BABYLON.Observable();
  7997. this.onContextRestoredObservable = new BABYLON.Observable();
  7998. this._contextWasLost = false;
  7999. this._doNotHandleContextLost = false;
  8000. // FPS
  8001. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8002. this._fps = 60;
  8003. this._deltaTime = 0;
  8004. /**
  8005. * Turn this value on if you want to pause FPS computation when in background
  8006. */
  8007. this.disablePerformanceMonitorInBackground = false;
  8008. // States
  8009. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8010. this._stencilState = new BABYLON.Internals._StencilState();
  8011. this._alphaState = new BABYLON.Internals._AlphaState();
  8012. this._alphaMode = Engine.ALPHA_DISABLE;
  8013. // Cache
  8014. this._internalTexturesCache = new Array();
  8015. this._activeTexturesCache = {};
  8016. this._compiledEffects = {};
  8017. this._vertexAttribArraysEnabled = [];
  8018. this._uintIndicesCurrentlySet = false;
  8019. this._currentBoundBuffer = new Array();
  8020. this._currentBufferPointers = new Array();
  8021. this._currentInstanceLocations = new Array();
  8022. this._currentInstanceBuffers = new Array();
  8023. this._vaoRecordInProgress = false;
  8024. this._mustWipeVertexAttributes = false;
  8025. // Hardware supported Compressed Textures
  8026. this._texturesSupported = new Array();
  8027. this._onVRFullScreenTriggered = function () {
  8028. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8029. //get the old size before we change
  8030. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8031. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8032. //get the width and height, change the render size
  8033. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8034. _this.setHardwareScalingLevel(1);
  8035. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8036. }
  8037. else {
  8038. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8039. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8040. }
  8041. };
  8042. var canvas = null;
  8043. Engine.Instances.push(this);
  8044. if (!canvasOrContext) {
  8045. return;
  8046. }
  8047. options = options || {};
  8048. if (canvasOrContext.getContext) {
  8049. canvas = canvasOrContext;
  8050. this._renderingCanvas = canvas;
  8051. if (antialias != null) {
  8052. options.antialias = antialias;
  8053. }
  8054. if (options.deterministicLockstep === undefined) {
  8055. options.deterministicLockstep = false;
  8056. }
  8057. if (options.lockstepMaxSteps === undefined) {
  8058. options.lockstepMaxSteps = 4;
  8059. }
  8060. if (options.preserveDrawingBuffer === undefined) {
  8061. options.preserveDrawingBuffer = false;
  8062. }
  8063. if (options.audioEngine === undefined) {
  8064. options.audioEngine = true;
  8065. }
  8066. if (options.stencil === undefined) {
  8067. options.stencil = true;
  8068. }
  8069. this._deterministicLockstep = options.deterministicLockstep;
  8070. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8071. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8072. // GL
  8073. if (!options.disableWebGL2Support) {
  8074. try {
  8075. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8076. if (this._gl) {
  8077. this._webGLVersion = 2.0;
  8078. }
  8079. }
  8080. catch (e) {
  8081. // Do nothing
  8082. }
  8083. }
  8084. if (!this._gl) {
  8085. if (!canvas) {
  8086. throw new Error("The provided canvas is null or undefined.");
  8087. }
  8088. try {
  8089. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8090. }
  8091. catch (e) {
  8092. throw new Error("WebGL not supported");
  8093. }
  8094. }
  8095. if (!this._gl) {
  8096. throw new Error("WebGL not supported");
  8097. }
  8098. this._onCanvasFocus = function () {
  8099. _this.onCanvasFocusObservable.notifyObservers(_this);
  8100. };
  8101. this._onCanvasBlur = function () {
  8102. _this.onCanvasBlurObservable.notifyObservers(_this);
  8103. };
  8104. canvas.addEventListener("focus", this._onCanvasFocus);
  8105. canvas.addEventListener("blur", this._onCanvasBlur);
  8106. this._onBlur = function () {
  8107. if (_this.disablePerformanceMonitorInBackground) {
  8108. _this._performanceMonitor.disable();
  8109. }
  8110. _this._windowIsBackground = true;
  8111. };
  8112. this._onFocus = function () {
  8113. if (_this.disablePerformanceMonitorInBackground) {
  8114. _this._performanceMonitor.enable();
  8115. }
  8116. _this._windowIsBackground = false;
  8117. };
  8118. this._onCanvasPointerOut = function () {
  8119. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8120. };
  8121. window.addEventListener("blur", this._onBlur);
  8122. window.addEventListener("focus", this._onFocus);
  8123. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8124. // Context lost
  8125. if (!this._doNotHandleContextLost) {
  8126. this._onContextLost = function (evt) {
  8127. evt.preventDefault();
  8128. _this._contextWasLost = true;
  8129. BABYLON.Tools.Warn("WebGL context lost.");
  8130. _this.onContextLostObservable.notifyObservers(_this);
  8131. };
  8132. this._onContextRestored = function (evt) {
  8133. // Adding a timeout to avoid race condition at browser level
  8134. setTimeout(function () {
  8135. // Rebuild gl context
  8136. _this._initGLContext();
  8137. // Rebuild effects
  8138. _this._rebuildEffects();
  8139. // Rebuild textures
  8140. _this._rebuildInternalTextures();
  8141. // Rebuild buffers
  8142. _this._rebuildBuffers();
  8143. // Cache
  8144. _this.wipeCaches(true);
  8145. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8146. _this.onContextRestoredObservable.notifyObservers(_this);
  8147. _this._contextWasLost = false;
  8148. }, 0);
  8149. };
  8150. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8151. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8152. }
  8153. }
  8154. else {
  8155. this._gl = canvasOrContext;
  8156. this._renderingCanvas = this._gl.canvas;
  8157. if (this._gl.renderbufferStorageMultisample) {
  8158. this._webGLVersion = 2.0;
  8159. }
  8160. options.stencil = this._gl.getContextAttributes().stencil;
  8161. }
  8162. // Viewport
  8163. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8164. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8165. this.resize();
  8166. this._isStencilEnable = options.stencil ? true : false;
  8167. this._initGLContext();
  8168. if (canvas) {
  8169. // Fullscreen
  8170. this._onFullscreenChange = function () {
  8171. if (document.fullscreen !== undefined) {
  8172. _this.isFullscreen = document.fullscreen;
  8173. }
  8174. else if (document.mozFullScreen !== undefined) {
  8175. _this.isFullscreen = document.mozFullScreen;
  8176. }
  8177. else if (document.webkitIsFullScreen !== undefined) {
  8178. _this.isFullscreen = document.webkitIsFullScreen;
  8179. }
  8180. else if (document.msIsFullScreen !== undefined) {
  8181. _this.isFullscreen = document.msIsFullScreen;
  8182. }
  8183. // Pointer lock
  8184. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8185. canvas.requestPointerLock = canvas.requestPointerLock ||
  8186. canvas.msRequestPointerLock ||
  8187. canvas.mozRequestPointerLock ||
  8188. canvas.webkitRequestPointerLock;
  8189. if (canvas.requestPointerLock) {
  8190. canvas.requestPointerLock();
  8191. }
  8192. }
  8193. };
  8194. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8195. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8196. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8197. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8198. // Pointer lock
  8199. this._onPointerLockChange = function () {
  8200. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8201. document.webkitPointerLockElement === canvas ||
  8202. document.msPointerLockElement === canvas ||
  8203. document.pointerLockElement === canvas);
  8204. };
  8205. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8206. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8207. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8208. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8209. this._onVRDisplayPointerRestricted = function () {
  8210. if (canvas) {
  8211. canvas.requestPointerLock();
  8212. }
  8213. };
  8214. this._onVRDisplayPointerUnrestricted = function () {
  8215. document.exitPointerLock();
  8216. };
  8217. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8218. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8219. }
  8220. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8221. Engine.audioEngine = new BABYLON.AudioEngine();
  8222. }
  8223. // Prepare buffer pointers
  8224. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8225. this._currentBufferPointers[i] = new BufferPointer();
  8226. }
  8227. // Load WebVR Devices
  8228. if (options.autoEnableWebVR) {
  8229. this.initWebVR();
  8230. }
  8231. // Detect if we are running on a faulty buggy OS.
  8232. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8233. // Detect if we are running on a faulty buggy desktop OS.
  8234. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8235. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8236. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8237. }
  8238. Object.defineProperty(Engine, "LastCreatedEngine", {
  8239. get: function () {
  8240. if (Engine.Instances.length === 0) {
  8241. return null;
  8242. }
  8243. return Engine.Instances[Engine.Instances.length - 1];
  8244. },
  8245. enumerable: true,
  8246. configurable: true
  8247. });
  8248. Object.defineProperty(Engine, "LastCreatedScene", {
  8249. get: function () {
  8250. var lastCreatedEngine = Engine.LastCreatedEngine;
  8251. if (!lastCreatedEngine) {
  8252. return null;
  8253. }
  8254. if (lastCreatedEngine.scenes.length === 0) {
  8255. return null;
  8256. }
  8257. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8258. },
  8259. enumerable: true,
  8260. configurable: true
  8261. });
  8262. /**
  8263. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8264. */
  8265. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8266. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8267. var engine = Engine.Instances[engineIndex];
  8268. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8269. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8270. }
  8271. }
  8272. };
  8273. Object.defineProperty(Engine, "NEVER", {
  8274. get: function () {
  8275. return Engine._NEVER;
  8276. },
  8277. enumerable: true,
  8278. configurable: true
  8279. });
  8280. Object.defineProperty(Engine, "ALWAYS", {
  8281. get: function () {
  8282. return Engine._ALWAYS;
  8283. },
  8284. enumerable: true,
  8285. configurable: true
  8286. });
  8287. Object.defineProperty(Engine, "LESS", {
  8288. get: function () {
  8289. return Engine._LESS;
  8290. },
  8291. enumerable: true,
  8292. configurable: true
  8293. });
  8294. Object.defineProperty(Engine, "EQUAL", {
  8295. get: function () {
  8296. return Engine._EQUAL;
  8297. },
  8298. enumerable: true,
  8299. configurable: true
  8300. });
  8301. Object.defineProperty(Engine, "LEQUAL", {
  8302. get: function () {
  8303. return Engine._LEQUAL;
  8304. },
  8305. enumerable: true,
  8306. configurable: true
  8307. });
  8308. Object.defineProperty(Engine, "GREATER", {
  8309. get: function () {
  8310. return Engine._GREATER;
  8311. },
  8312. enumerable: true,
  8313. configurable: true
  8314. });
  8315. Object.defineProperty(Engine, "GEQUAL", {
  8316. get: function () {
  8317. return Engine._GEQUAL;
  8318. },
  8319. enumerable: true,
  8320. configurable: true
  8321. });
  8322. Object.defineProperty(Engine, "NOTEQUAL", {
  8323. get: function () {
  8324. return Engine._NOTEQUAL;
  8325. },
  8326. enumerable: true,
  8327. configurable: true
  8328. });
  8329. Object.defineProperty(Engine, "KEEP", {
  8330. get: function () {
  8331. return Engine._KEEP;
  8332. },
  8333. enumerable: true,
  8334. configurable: true
  8335. });
  8336. Object.defineProperty(Engine, "REPLACE", {
  8337. get: function () {
  8338. return Engine._REPLACE;
  8339. },
  8340. enumerable: true,
  8341. configurable: true
  8342. });
  8343. Object.defineProperty(Engine, "INCR", {
  8344. get: function () {
  8345. return Engine._INCR;
  8346. },
  8347. enumerable: true,
  8348. configurable: true
  8349. });
  8350. Object.defineProperty(Engine, "DECR", {
  8351. get: function () {
  8352. return Engine._DECR;
  8353. },
  8354. enumerable: true,
  8355. configurable: true
  8356. });
  8357. Object.defineProperty(Engine, "INVERT", {
  8358. get: function () {
  8359. return Engine._INVERT;
  8360. },
  8361. enumerable: true,
  8362. configurable: true
  8363. });
  8364. Object.defineProperty(Engine, "INCR_WRAP", {
  8365. get: function () {
  8366. return Engine._INCR_WRAP;
  8367. },
  8368. enumerable: true,
  8369. configurable: true
  8370. });
  8371. Object.defineProperty(Engine, "DECR_WRAP", {
  8372. get: function () {
  8373. return Engine._DECR_WRAP;
  8374. },
  8375. enumerable: true,
  8376. configurable: true
  8377. });
  8378. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8379. get: function () {
  8380. return Engine._ALPHA_DISABLE;
  8381. },
  8382. enumerable: true,
  8383. configurable: true
  8384. });
  8385. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8386. get: function () {
  8387. return Engine._ALPHA_ONEONE;
  8388. },
  8389. enumerable: true,
  8390. configurable: true
  8391. });
  8392. Object.defineProperty(Engine, "ALPHA_ADD", {
  8393. get: function () {
  8394. return Engine._ALPHA_ADD;
  8395. },
  8396. enumerable: true,
  8397. configurable: true
  8398. });
  8399. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8400. get: function () {
  8401. return Engine._ALPHA_COMBINE;
  8402. },
  8403. enumerable: true,
  8404. configurable: true
  8405. });
  8406. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8407. get: function () {
  8408. return Engine._ALPHA_SUBTRACT;
  8409. },
  8410. enumerable: true,
  8411. configurable: true
  8412. });
  8413. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8414. get: function () {
  8415. return Engine._ALPHA_MULTIPLY;
  8416. },
  8417. enumerable: true,
  8418. configurable: true
  8419. });
  8420. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8421. get: function () {
  8422. return Engine._ALPHA_MAXIMIZED;
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8428. get: function () {
  8429. return Engine._ALPHA_PREMULTIPLIED;
  8430. },
  8431. enumerable: true,
  8432. configurable: true
  8433. });
  8434. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8435. get: function () {
  8436. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8437. },
  8438. enumerable: true,
  8439. configurable: true
  8440. });
  8441. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8442. get: function () {
  8443. return Engine._ALPHA_INTERPOLATE;
  8444. },
  8445. enumerable: true,
  8446. configurable: true
  8447. });
  8448. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8449. get: function () {
  8450. return Engine._ALPHA_SCREENMODE;
  8451. },
  8452. enumerable: true,
  8453. configurable: true
  8454. });
  8455. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8456. get: function () {
  8457. return Engine._DELAYLOADSTATE_NONE;
  8458. },
  8459. enumerable: true,
  8460. configurable: true
  8461. });
  8462. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8463. get: function () {
  8464. return Engine._DELAYLOADSTATE_LOADED;
  8465. },
  8466. enumerable: true,
  8467. configurable: true
  8468. });
  8469. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8470. get: function () {
  8471. return Engine._DELAYLOADSTATE_LOADING;
  8472. },
  8473. enumerable: true,
  8474. configurable: true
  8475. });
  8476. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8477. get: function () {
  8478. return Engine._DELAYLOADSTATE_NOTLOADED;
  8479. },
  8480. enumerable: true,
  8481. configurable: true
  8482. });
  8483. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8484. get: function () {
  8485. return Engine._TEXTUREFORMAT_ALPHA;
  8486. },
  8487. enumerable: true,
  8488. configurable: true
  8489. });
  8490. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8491. get: function () {
  8492. return Engine._TEXTUREFORMAT_LUMINANCE;
  8493. },
  8494. enumerable: true,
  8495. configurable: true
  8496. });
  8497. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8498. get: function () {
  8499. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8500. },
  8501. enumerable: true,
  8502. configurable: true
  8503. });
  8504. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8505. get: function () {
  8506. return Engine._TEXTUREFORMAT_RGB;
  8507. },
  8508. enumerable: true,
  8509. configurable: true
  8510. });
  8511. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8512. get: function () {
  8513. return Engine._TEXTUREFORMAT_RGBA;
  8514. },
  8515. enumerable: true,
  8516. configurable: true
  8517. });
  8518. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8519. get: function () {
  8520. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8521. },
  8522. enumerable: true,
  8523. configurable: true
  8524. });
  8525. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8526. get: function () {
  8527. return Engine._TEXTURETYPE_FLOAT;
  8528. },
  8529. enumerable: true,
  8530. configurable: true
  8531. });
  8532. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8533. get: function () {
  8534. return Engine._TEXTURETYPE_HALF_FLOAT;
  8535. },
  8536. enumerable: true,
  8537. configurable: true
  8538. });
  8539. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8540. get: function () {
  8541. return Engine._SCALEMODE_FLOOR;
  8542. },
  8543. enumerable: true,
  8544. configurable: true
  8545. });
  8546. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8547. get: function () {
  8548. return Engine._SCALEMODE_NEAREST;
  8549. },
  8550. enumerable: true,
  8551. configurable: true
  8552. });
  8553. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8554. get: function () {
  8555. return Engine._SCALEMODE_CEILING;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Object.defineProperty(Engine, "Version", {
  8561. get: function () {
  8562. return "3.1-beta-2";
  8563. },
  8564. enumerable: true,
  8565. configurable: true
  8566. });
  8567. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8568. get: function () {
  8569. return this._vrExclusivePointerMode;
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8575. get: function () {
  8576. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8577. },
  8578. enumerable: true,
  8579. configurable: true
  8580. });
  8581. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8582. get: function () {
  8583. return this._webGLVersion < 2 || this.forcePOTTextures;
  8584. },
  8585. enumerable: true,
  8586. configurable: true
  8587. });
  8588. Object.defineProperty(Engine.prototype, "badOS", {
  8589. get: function () {
  8590. return this._badOS;
  8591. },
  8592. enumerable: true,
  8593. configurable: true
  8594. });
  8595. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8596. get: function () {
  8597. return this._badDesktopOS;
  8598. },
  8599. enumerable: true,
  8600. configurable: true
  8601. });
  8602. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8603. get: function () {
  8604. return this._performanceMonitor;
  8605. },
  8606. enumerable: true,
  8607. configurable: true
  8608. });
  8609. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8610. get: function () {
  8611. return this._texturesSupported;
  8612. },
  8613. enumerable: true,
  8614. configurable: true
  8615. });
  8616. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8617. get: function () {
  8618. return this._textureFormatInUse;
  8619. },
  8620. enumerable: true,
  8621. configurable: true
  8622. });
  8623. Object.defineProperty(Engine.prototype, "currentViewport", {
  8624. get: function () {
  8625. return this._cachedViewport;
  8626. },
  8627. enumerable: true,
  8628. configurable: true
  8629. });
  8630. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8631. // Empty texture
  8632. get: function () {
  8633. if (!this._emptyTexture) {
  8634. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8635. }
  8636. return this._emptyTexture;
  8637. },
  8638. enumerable: true,
  8639. configurable: true
  8640. });
  8641. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8642. get: function () {
  8643. if (!this._emptyTexture3D) {
  8644. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8645. }
  8646. return this._emptyTexture3D;
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8652. get: function () {
  8653. if (!this._emptyCubeTexture) {
  8654. var faceData = new Uint8Array(4);
  8655. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8656. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8657. }
  8658. return this._emptyCubeTexture;
  8659. },
  8660. enumerable: true,
  8661. configurable: true
  8662. });
  8663. Engine.prototype._rebuildInternalTextures = function () {
  8664. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8665. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8666. var internalTexture = currentState_1[_i];
  8667. internalTexture._rebuild();
  8668. }
  8669. };
  8670. Engine.prototype._rebuildEffects = function () {
  8671. for (var key in this._compiledEffects) {
  8672. var effect = this._compiledEffects[key];
  8673. effect._prepareEffect();
  8674. }
  8675. BABYLON.Effect.ResetCache();
  8676. };
  8677. Engine.prototype._rebuildBuffers = function () {
  8678. // Index / Vertex
  8679. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8680. var scene = _a[_i];
  8681. scene.resetCachedMaterial();
  8682. scene._rebuildGeometries();
  8683. scene._rebuildTextures();
  8684. }
  8685. // Uniforms
  8686. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8687. var uniformBuffer = _c[_b];
  8688. uniformBuffer._rebuild();
  8689. }
  8690. };
  8691. Engine.prototype._initGLContext = function () {
  8692. // Caps
  8693. this._caps = new EngineCapabilities();
  8694. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8695. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8696. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8697. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8698. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8699. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8700. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8701. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8702. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8703. // Infos
  8704. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8705. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8706. if (rendererInfo != null) {
  8707. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8708. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8709. }
  8710. if (!this._glVendor) {
  8711. this._glVendor = "Unknown vendor";
  8712. }
  8713. if (!this._glRenderer) {
  8714. this._glRenderer = "Unknown renderer";
  8715. }
  8716. // Constants
  8717. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8718. if (this._gl.RGBA16F !== 0x881A) {
  8719. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8720. }
  8721. if (this._gl.RGBA32F !== 0x8814) {
  8722. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8723. }
  8724. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8725. this._gl.DEPTH24_STENCIL8 = 35056;
  8726. }
  8727. // Extensions
  8728. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8729. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8730. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8731. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8732. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8733. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8734. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8735. 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');
  8736. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8737. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8738. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8739. this._caps.highPrecisionShaderSupported = true;
  8740. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8741. if (this._caps.timerQuery) {
  8742. if (this._webGLVersion === 1) {
  8743. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8744. }
  8745. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8746. }
  8747. // Checks if some of the format renders first to allow the use of webgl inspector.
  8748. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8749. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8750. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8751. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8752. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8753. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8754. if (this._webGLVersion > 1) {
  8755. this._gl.HALF_FLOAT_OES = 0x140B;
  8756. }
  8757. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8758. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8759. // Draw buffers
  8760. if (this._webGLVersion > 1) {
  8761. this._caps.drawBuffersExtension = true;
  8762. }
  8763. else {
  8764. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8765. if (drawBuffersExtension !== null) {
  8766. this._caps.drawBuffersExtension = true;
  8767. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8768. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8769. for (var i = 0; i < 16; i++) {
  8770. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8771. }
  8772. }
  8773. else {
  8774. this._caps.drawBuffersExtension = false;
  8775. }
  8776. }
  8777. // Depth Texture
  8778. if (this._webGLVersion > 1) {
  8779. this._caps.depthTextureExtension = true;
  8780. }
  8781. else {
  8782. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8783. if (depthTextureExtension != null) {
  8784. this._caps.depthTextureExtension = true;
  8785. }
  8786. }
  8787. // Vertex array object
  8788. if (this._webGLVersion > 1) {
  8789. this._caps.vertexArrayObject = true;
  8790. }
  8791. else {
  8792. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8793. if (vertexArrayObjectExtension != null) {
  8794. this._caps.vertexArrayObject = true;
  8795. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8796. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8797. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8798. }
  8799. else {
  8800. this._caps.vertexArrayObject = false;
  8801. }
  8802. }
  8803. // Instances count
  8804. if (this._webGLVersion > 1) {
  8805. this._caps.instancedArrays = true;
  8806. }
  8807. else {
  8808. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8809. if (instanceExtension != null) {
  8810. this._caps.instancedArrays = true;
  8811. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8812. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8813. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8814. }
  8815. else {
  8816. this._caps.instancedArrays = false;
  8817. }
  8818. }
  8819. // Intelligently add supported compressed formats in order to check for.
  8820. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8821. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8822. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8823. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8824. if (this._caps.astc)
  8825. this.texturesSupported.push('-astc.ktx');
  8826. if (this._caps.s3tc)
  8827. this.texturesSupported.push('-dxt.ktx');
  8828. if (this._caps.pvrtc)
  8829. this.texturesSupported.push('-pvrtc.ktx');
  8830. if (this._caps.etc2)
  8831. this.texturesSupported.push('-etc2.ktx');
  8832. if (this._caps.etc1)
  8833. this.texturesSupported.push('-etc1.ktx');
  8834. if (this._gl.getShaderPrecisionFormat) {
  8835. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8836. if (highp) {
  8837. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8838. }
  8839. }
  8840. // Depth buffer
  8841. this.setDepthBuffer(true);
  8842. this.setDepthFunctionToLessOrEqual();
  8843. this.setDepthWrite(true);
  8844. };
  8845. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8846. get: function () {
  8847. return this._webGLVersion;
  8848. },
  8849. enumerable: true,
  8850. configurable: true
  8851. });
  8852. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8853. /**
  8854. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8855. */
  8856. get: function () {
  8857. return this._isStencilEnable;
  8858. },
  8859. enumerable: true,
  8860. configurable: true
  8861. });
  8862. Engine.prototype._prepareWorkingCanvas = function () {
  8863. if (this._workingCanvas) {
  8864. return;
  8865. }
  8866. this._workingCanvas = document.createElement("canvas");
  8867. var context = this._workingCanvas.getContext("2d");
  8868. if (context) {
  8869. this._workingContext = context;
  8870. }
  8871. };
  8872. Engine.prototype.resetTextureCache = function () {
  8873. for (var key in this._activeTexturesCache) {
  8874. this._activeTexturesCache[key] = null;
  8875. }
  8876. };
  8877. Engine.prototype.isDeterministicLockStep = function () {
  8878. return this._deterministicLockstep;
  8879. };
  8880. Engine.prototype.getLockstepMaxSteps = function () {
  8881. return this._lockstepMaxSteps;
  8882. };
  8883. Engine.prototype.getGlInfo = function () {
  8884. return {
  8885. vendor: this._glVendor,
  8886. renderer: this._glRenderer,
  8887. version: this._glVersion
  8888. };
  8889. };
  8890. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8891. if (useScreen === void 0) { useScreen = false; }
  8892. var viewport = camera.viewport;
  8893. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8894. };
  8895. Engine.prototype.getRenderWidth = function (useScreen) {
  8896. if (useScreen === void 0) { useScreen = false; }
  8897. if (!useScreen && this._currentRenderTarget) {
  8898. return this._currentRenderTarget.width;
  8899. }
  8900. return this._gl.drawingBufferWidth;
  8901. };
  8902. Engine.prototype.getRenderHeight = function (useScreen) {
  8903. if (useScreen === void 0) { useScreen = false; }
  8904. if (!useScreen && this._currentRenderTarget) {
  8905. return this._currentRenderTarget.height;
  8906. }
  8907. return this._gl.drawingBufferHeight;
  8908. };
  8909. Engine.prototype.getRenderingCanvas = function () {
  8910. return this._renderingCanvas;
  8911. };
  8912. Engine.prototype.getRenderingCanvasClientRect = function () {
  8913. if (!this._renderingCanvas) {
  8914. return null;
  8915. }
  8916. return this._renderingCanvas.getBoundingClientRect();
  8917. };
  8918. Engine.prototype.setHardwareScalingLevel = function (level) {
  8919. this._hardwareScalingLevel = level;
  8920. this.resize();
  8921. };
  8922. Engine.prototype.getHardwareScalingLevel = function () {
  8923. return this._hardwareScalingLevel;
  8924. };
  8925. Engine.prototype.getLoadedTexturesCache = function () {
  8926. return this._internalTexturesCache;
  8927. };
  8928. Engine.prototype.getCaps = function () {
  8929. return this._caps;
  8930. };
  8931. Object.defineProperty(Engine.prototype, "drawCalls", {
  8932. /** The number of draw calls submitted last frame */
  8933. get: function () {
  8934. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8935. return 0;
  8936. },
  8937. enumerable: true,
  8938. configurable: true
  8939. });
  8940. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8941. get: function () {
  8942. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8943. return null;
  8944. },
  8945. enumerable: true,
  8946. configurable: true
  8947. });
  8948. Engine.prototype.getDepthFunction = function () {
  8949. return this._depthCullingState.depthFunc;
  8950. };
  8951. Engine.prototype.setDepthFunction = function (depthFunc) {
  8952. this._depthCullingState.depthFunc = depthFunc;
  8953. };
  8954. Engine.prototype.setDepthFunctionToGreater = function () {
  8955. this._depthCullingState.depthFunc = this._gl.GREATER;
  8956. };
  8957. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8958. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8959. };
  8960. Engine.prototype.setDepthFunctionToLess = function () {
  8961. this._depthCullingState.depthFunc = this._gl.LESS;
  8962. };
  8963. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8964. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8965. };
  8966. Engine.prototype.getStencilBuffer = function () {
  8967. return this._stencilState.stencilTest;
  8968. };
  8969. Engine.prototype.setStencilBuffer = function (enable) {
  8970. this._stencilState.stencilTest = enable;
  8971. };
  8972. Engine.prototype.getStencilMask = function () {
  8973. return this._stencilState.stencilMask;
  8974. };
  8975. Engine.prototype.setStencilMask = function (mask) {
  8976. this._stencilState.stencilMask = mask;
  8977. };
  8978. Engine.prototype.getStencilFunction = function () {
  8979. return this._stencilState.stencilFunc;
  8980. };
  8981. Engine.prototype.getStencilFunctionReference = function () {
  8982. return this._stencilState.stencilFuncRef;
  8983. };
  8984. Engine.prototype.getStencilFunctionMask = function () {
  8985. return this._stencilState.stencilFuncMask;
  8986. };
  8987. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8988. this._stencilState.stencilFunc = stencilFunc;
  8989. };
  8990. Engine.prototype.setStencilFunctionReference = function (reference) {
  8991. this._stencilState.stencilFuncRef = reference;
  8992. };
  8993. Engine.prototype.setStencilFunctionMask = function (mask) {
  8994. this._stencilState.stencilFuncMask = mask;
  8995. };
  8996. Engine.prototype.getStencilOperationFail = function () {
  8997. return this._stencilState.stencilOpStencilFail;
  8998. };
  8999. Engine.prototype.getStencilOperationDepthFail = function () {
  9000. return this._stencilState.stencilOpDepthFail;
  9001. };
  9002. Engine.prototype.getStencilOperationPass = function () {
  9003. return this._stencilState.stencilOpStencilDepthPass;
  9004. };
  9005. Engine.prototype.setStencilOperationFail = function (operation) {
  9006. this._stencilState.stencilOpStencilFail = operation;
  9007. };
  9008. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9009. this._stencilState.stencilOpDepthFail = operation;
  9010. };
  9011. Engine.prototype.setStencilOperationPass = function (operation) {
  9012. this._stencilState.stencilOpStencilDepthPass = operation;
  9013. };
  9014. Engine.prototype.setDitheringState = function (value) {
  9015. if (value) {
  9016. this._gl.enable(this._gl.DITHER);
  9017. }
  9018. else {
  9019. this._gl.disable(this._gl.DITHER);
  9020. }
  9021. };
  9022. Engine.prototype.setRasterizerState = function (value) {
  9023. if (value) {
  9024. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9025. }
  9026. else {
  9027. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9028. }
  9029. };
  9030. /**
  9031. * stop executing a render loop function and remove it from the execution array
  9032. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9033. */
  9034. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9035. if (!renderFunction) {
  9036. this._activeRenderLoops = [];
  9037. return;
  9038. }
  9039. var index = this._activeRenderLoops.indexOf(renderFunction);
  9040. if (index >= 0) {
  9041. this._activeRenderLoops.splice(index, 1);
  9042. }
  9043. };
  9044. Engine.prototype._renderLoop = function () {
  9045. if (!this._contextWasLost) {
  9046. var shouldRender = true;
  9047. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9048. shouldRender = false;
  9049. }
  9050. if (shouldRender) {
  9051. // Start new frame
  9052. this.beginFrame();
  9053. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9054. var renderFunction = this._activeRenderLoops[index];
  9055. renderFunction();
  9056. }
  9057. // Present
  9058. this.endFrame();
  9059. }
  9060. }
  9061. if (this._activeRenderLoops.length > 0) {
  9062. // Register new frame
  9063. var requester = null;
  9064. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9065. requester = this._vrDisplay;
  9066. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9067. }
  9068. else {
  9069. this._renderingQueueLaunched = false;
  9070. }
  9071. };
  9072. /**
  9073. * Register and execute a render loop. The engine can have more than one render function.
  9074. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9075. * @example
  9076. * engine.runRenderLoop(function () {
  9077. * scene.render()
  9078. * })
  9079. */
  9080. Engine.prototype.runRenderLoop = function (renderFunction) {
  9081. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9082. return;
  9083. }
  9084. this._activeRenderLoops.push(renderFunction);
  9085. if (!this._renderingQueueLaunched) {
  9086. this._renderingQueueLaunched = true;
  9087. this._bindedRenderFunction = this._renderLoop.bind(this);
  9088. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9089. }
  9090. };
  9091. /**
  9092. * Toggle full screen mode.
  9093. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9094. * @param {any} options - an options object to be sent to the requestFullscreen function
  9095. */
  9096. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9097. if (this.isFullscreen) {
  9098. BABYLON.Tools.ExitFullscreen();
  9099. }
  9100. else {
  9101. this._pointerLockRequested = requestPointerLock;
  9102. if (this._renderingCanvas) {
  9103. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9104. }
  9105. }
  9106. };
  9107. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9108. if (stencil === void 0) { stencil = false; }
  9109. this.applyStates();
  9110. var mode = 0;
  9111. if (backBuffer && color) {
  9112. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9113. mode |= this._gl.COLOR_BUFFER_BIT;
  9114. }
  9115. if (depth) {
  9116. this._gl.clearDepth(1.0);
  9117. mode |= this._gl.DEPTH_BUFFER_BIT;
  9118. }
  9119. if (stencil) {
  9120. this._gl.clearStencil(0);
  9121. mode |= this._gl.STENCIL_BUFFER_BIT;
  9122. }
  9123. this._gl.clear(mode);
  9124. };
  9125. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9126. var gl = this._gl;
  9127. // Save state
  9128. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9129. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9130. // Change state
  9131. gl.enable(gl.SCISSOR_TEST);
  9132. gl.scissor(x, y, width, height);
  9133. // Clear
  9134. this.clear(clearColor, true, true, true);
  9135. // Restore state
  9136. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9137. if (curScissor === true) {
  9138. gl.enable(gl.SCISSOR_TEST);
  9139. }
  9140. else {
  9141. gl.disable(gl.SCISSOR_TEST);
  9142. }
  9143. };
  9144. /**
  9145. * Set the WebGL's viewport
  9146. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9147. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9148. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9149. */
  9150. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9151. var width = requiredWidth || this.getRenderWidth();
  9152. var height = requiredHeight || this.getRenderHeight();
  9153. var x = viewport.x || 0;
  9154. var y = viewport.y || 0;
  9155. this._cachedViewport = viewport;
  9156. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9157. };
  9158. /**
  9159. * Directly set the WebGL Viewport
  9160. * The x, y, width & height are directly passed to the WebGL call
  9161. * @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.
  9162. */
  9163. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9164. var currentViewport = this._cachedViewport;
  9165. this._cachedViewport = null;
  9166. this._gl.viewport(x, y, width, height);
  9167. return currentViewport;
  9168. };
  9169. Engine.prototype.beginFrame = function () {
  9170. this.onBeginFrameObservable.notifyObservers(this);
  9171. this._measureFps();
  9172. };
  9173. Engine.prototype.endFrame = function () {
  9174. //force a flush in case we are using a bad OS.
  9175. if (this._badOS) {
  9176. this.flushFramebuffer();
  9177. }
  9178. //submit frame to the vr device, if enabled
  9179. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9180. // TODO: We should only submit the frame if we read frameData successfully.
  9181. this._vrDisplay.submitFrame();
  9182. }
  9183. this.onEndFrameObservable.notifyObservers(this);
  9184. };
  9185. /**
  9186. * resize the view according to the canvas' size.
  9187. * @example
  9188. * window.addEventListener("resize", function () {
  9189. * engine.resize();
  9190. * });
  9191. */
  9192. Engine.prototype.resize = function () {
  9193. // We're not resizing the size of the canvas while in VR mode & presenting
  9194. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9195. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9196. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9197. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9198. }
  9199. };
  9200. /**
  9201. * force a specific size of the canvas
  9202. * @param {number} width - the new canvas' width
  9203. * @param {number} height - the new canvas' height
  9204. */
  9205. Engine.prototype.setSize = function (width, height) {
  9206. if (!this._renderingCanvas) {
  9207. return;
  9208. }
  9209. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9210. return;
  9211. }
  9212. this._renderingCanvas.width = width;
  9213. this._renderingCanvas.height = height;
  9214. for (var index = 0; index < this.scenes.length; index++) {
  9215. var scene = this.scenes[index];
  9216. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9217. var cam = scene.cameras[camIndex];
  9218. cam._currentRenderId = 0;
  9219. }
  9220. }
  9221. if (this.onResizeObservable.hasObservers) {
  9222. this.onResizeObservable.notifyObservers(this);
  9223. }
  9224. };
  9225. // WebVR functions
  9226. Engine.prototype.isVRDevicePresent = function () {
  9227. return !!this._vrDisplay;
  9228. };
  9229. Engine.prototype.getVRDevice = function () {
  9230. return this._vrDisplay;
  9231. };
  9232. Engine.prototype.initWebVR = function () {
  9233. var _this = this;
  9234. var notifyObservers = function () {
  9235. var eventArgs = {
  9236. vrDisplay: _this._vrDisplay,
  9237. vrSupported: _this._vrSupported
  9238. };
  9239. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9240. };
  9241. if (!this._onVrDisplayConnect) {
  9242. this._onVrDisplayConnect = function (event) {
  9243. _this._vrDisplay = event.display;
  9244. notifyObservers();
  9245. };
  9246. this._onVrDisplayDisconnect = function () {
  9247. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9248. _this._vrDisplay = undefined;
  9249. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9250. notifyObservers();
  9251. };
  9252. this._onVrDisplayPresentChange = function () {
  9253. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9254. };
  9255. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9256. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9257. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9258. }
  9259. this._getVRDisplays(notifyObservers);
  9260. return this.onVRDisplayChangedObservable;
  9261. };
  9262. Engine.prototype.enableVR = function () {
  9263. var _this = this;
  9264. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9265. var onResolved = function () {
  9266. _this.onVRRequestPresentComplete.notifyObservers(true);
  9267. _this._onVRFullScreenTriggered();
  9268. };
  9269. var onRejected = function () {
  9270. _this.onVRRequestPresentComplete.notifyObservers(false);
  9271. };
  9272. this.onVRRequestPresentStart.notifyObservers(this);
  9273. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9274. }
  9275. };
  9276. Engine.prototype.disableVR = function () {
  9277. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9278. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9279. }
  9280. };
  9281. Engine.prototype._getVRDisplays = function (callback) {
  9282. var _this = this;
  9283. var getWebVRDevices = function (devices) {
  9284. _this._vrSupported = true;
  9285. // note that devices may actually be an empty array. This is fine;
  9286. // we expect this._vrDisplay to be undefined in this case.
  9287. return _this._vrDisplay = devices[0];
  9288. };
  9289. if (navigator.getVRDisplays) {
  9290. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9291. // TODO: System CANNOT support WebVR, despite API presence.
  9292. _this._vrSupported = false;
  9293. callback();
  9294. });
  9295. }
  9296. else {
  9297. // TODO: Browser does not support WebVR
  9298. this._vrDisplay = undefined;
  9299. this._vrSupported = false;
  9300. callback();
  9301. }
  9302. };
  9303. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9304. if (this._currentRenderTarget) {
  9305. this.unBindFramebuffer(this._currentRenderTarget);
  9306. }
  9307. this._currentRenderTarget = texture;
  9308. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9309. var gl = this._gl;
  9310. if (texture.isCube) {
  9311. if (faceIndex === undefined) {
  9312. faceIndex = 0;
  9313. }
  9314. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9315. }
  9316. if (this._cachedViewport && !forceFullscreenViewport) {
  9317. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9318. }
  9319. else {
  9320. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9321. }
  9322. this.wipeCaches();
  9323. };
  9324. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9325. if (this._currentFramebuffer !== framebuffer) {
  9326. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9327. this._currentFramebuffer = framebuffer;
  9328. }
  9329. };
  9330. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9331. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9332. this._currentRenderTarget = null;
  9333. // If MSAA, we need to bitblt back to main texture
  9334. var gl = this._gl;
  9335. if (texture._MSAAFramebuffer) {
  9336. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9337. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9338. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9339. }
  9340. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9341. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9342. gl.generateMipmap(gl.TEXTURE_2D);
  9343. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9344. }
  9345. if (onBeforeUnbind) {
  9346. if (texture._MSAAFramebuffer) {
  9347. // Bind the correct framebuffer
  9348. this.bindUnboundFramebuffer(texture._framebuffer);
  9349. }
  9350. onBeforeUnbind();
  9351. }
  9352. this.bindUnboundFramebuffer(null);
  9353. };
  9354. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9355. if (texture.generateMipMaps) {
  9356. var gl = this._gl;
  9357. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9358. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9359. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9360. }
  9361. };
  9362. Engine.prototype.flushFramebuffer = function () {
  9363. this._gl.flush();
  9364. };
  9365. Engine.prototype.restoreDefaultFramebuffer = function () {
  9366. if (this._currentRenderTarget) {
  9367. this.unBindFramebuffer(this._currentRenderTarget);
  9368. }
  9369. else {
  9370. this.bindUnboundFramebuffer(null);
  9371. }
  9372. if (this._cachedViewport) {
  9373. this.setViewport(this._cachedViewport);
  9374. }
  9375. this.wipeCaches();
  9376. };
  9377. // UBOs
  9378. Engine.prototype.createUniformBuffer = function (elements) {
  9379. var ubo = this._gl.createBuffer();
  9380. if (!ubo) {
  9381. throw new Error("Unable to create uniform buffer");
  9382. }
  9383. this.bindUniformBuffer(ubo);
  9384. if (elements instanceof Float32Array) {
  9385. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9386. }
  9387. else {
  9388. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9389. }
  9390. this.bindUniformBuffer(null);
  9391. ubo.references = 1;
  9392. return ubo;
  9393. };
  9394. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9395. var ubo = this._gl.createBuffer();
  9396. if (!ubo) {
  9397. throw new Error("Unable to create dynamic uniform buffer");
  9398. }
  9399. this.bindUniformBuffer(ubo);
  9400. if (elements instanceof Float32Array) {
  9401. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9402. }
  9403. else {
  9404. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9405. }
  9406. this.bindUniformBuffer(null);
  9407. ubo.references = 1;
  9408. return ubo;
  9409. };
  9410. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9411. this.bindUniformBuffer(uniformBuffer);
  9412. if (offset === undefined) {
  9413. offset = 0;
  9414. }
  9415. if (count === undefined) {
  9416. if (elements instanceof Float32Array) {
  9417. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9418. }
  9419. else {
  9420. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9421. }
  9422. }
  9423. else {
  9424. if (elements instanceof Float32Array) {
  9425. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9426. }
  9427. else {
  9428. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9429. }
  9430. }
  9431. this.bindUniformBuffer(null);
  9432. };
  9433. // VBOs
  9434. Engine.prototype._resetVertexBufferBinding = function () {
  9435. this.bindArrayBuffer(null);
  9436. this._cachedVertexBuffers = null;
  9437. };
  9438. Engine.prototype.createVertexBuffer = function (vertices) {
  9439. var vbo = this._gl.createBuffer();
  9440. if (!vbo) {
  9441. throw new Error("Unable to create vertex buffer");
  9442. }
  9443. this.bindArrayBuffer(vbo);
  9444. if (vertices instanceof Float32Array) {
  9445. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9446. }
  9447. else {
  9448. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9449. }
  9450. this._resetVertexBufferBinding();
  9451. vbo.references = 1;
  9452. return vbo;
  9453. };
  9454. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9455. var vbo = this._gl.createBuffer();
  9456. if (!vbo) {
  9457. throw new Error("Unable to create dynamic vertex buffer");
  9458. }
  9459. this.bindArrayBuffer(vbo);
  9460. if (vertices instanceof Float32Array) {
  9461. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9462. }
  9463. else {
  9464. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9465. }
  9466. this._resetVertexBufferBinding();
  9467. vbo.references = 1;
  9468. return vbo;
  9469. };
  9470. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9471. if (offset === void 0) { offset = 0; }
  9472. // Force cache update
  9473. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9474. this.bindIndexBuffer(indexBuffer);
  9475. var arrayBuffer;
  9476. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9477. arrayBuffer = indices;
  9478. }
  9479. else {
  9480. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9481. }
  9482. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9483. this._resetIndexBufferBinding();
  9484. };
  9485. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9486. this.bindArrayBuffer(vertexBuffer);
  9487. if (offset === undefined) {
  9488. offset = 0;
  9489. }
  9490. if (count === undefined) {
  9491. if (vertices instanceof Float32Array) {
  9492. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9493. }
  9494. else {
  9495. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9496. }
  9497. }
  9498. else {
  9499. if (vertices instanceof Float32Array) {
  9500. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9501. }
  9502. else {
  9503. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9504. }
  9505. }
  9506. this._resetVertexBufferBinding();
  9507. };
  9508. Engine.prototype._resetIndexBufferBinding = function () {
  9509. this.bindIndexBuffer(null);
  9510. this._cachedIndexBuffer = null;
  9511. };
  9512. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9513. var vbo = this._gl.createBuffer();
  9514. if (!vbo) {
  9515. throw new Error("Unable to create index buffer");
  9516. }
  9517. this.bindIndexBuffer(vbo);
  9518. // Check for 32 bits indices
  9519. var arrayBuffer;
  9520. var need32Bits = false;
  9521. if (indices instanceof Uint16Array) {
  9522. arrayBuffer = indices;
  9523. }
  9524. else {
  9525. //check 32 bit support
  9526. if (this._caps.uintIndices) {
  9527. if (indices instanceof Uint32Array) {
  9528. arrayBuffer = indices;
  9529. need32Bits = true;
  9530. }
  9531. else {
  9532. //number[] or Int32Array, check if 32 bit is necessary
  9533. for (var index = 0; index < indices.length; index++) {
  9534. if (indices[index] > 65535) {
  9535. need32Bits = true;
  9536. break;
  9537. }
  9538. }
  9539. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9540. }
  9541. }
  9542. else {
  9543. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9544. arrayBuffer = new Uint16Array(indices);
  9545. }
  9546. }
  9547. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9548. this._resetIndexBufferBinding();
  9549. vbo.references = 1;
  9550. vbo.is32Bits = need32Bits;
  9551. return vbo;
  9552. };
  9553. Engine.prototype.bindArrayBuffer = function (buffer) {
  9554. if (!this._vaoRecordInProgress) {
  9555. this._unbindVertexArrayObject();
  9556. }
  9557. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9558. };
  9559. Engine.prototype.bindUniformBuffer = function (buffer) {
  9560. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9561. };
  9562. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9563. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9564. };
  9565. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9566. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9567. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9568. };
  9569. ;
  9570. Engine.prototype.bindIndexBuffer = function (buffer) {
  9571. if (!this._vaoRecordInProgress) {
  9572. this._unbindVertexArrayObject();
  9573. }
  9574. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9575. };
  9576. Engine.prototype.bindBuffer = function (buffer, target) {
  9577. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9578. this._gl.bindBuffer(target, buffer);
  9579. this._currentBoundBuffer[target] = buffer;
  9580. }
  9581. };
  9582. Engine.prototype.updateArrayBuffer = function (data) {
  9583. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9584. };
  9585. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9586. var pointer = this._currentBufferPointers[indx];
  9587. var changed = false;
  9588. if (!pointer.active) {
  9589. changed = true;
  9590. pointer.active = true;
  9591. pointer.index = indx;
  9592. pointer.size = size;
  9593. pointer.type = type;
  9594. pointer.normalized = normalized;
  9595. pointer.stride = stride;
  9596. pointer.offset = offset;
  9597. pointer.buffer = buffer;
  9598. }
  9599. else {
  9600. if (pointer.buffer !== buffer) {
  9601. pointer.buffer = buffer;
  9602. changed = true;
  9603. }
  9604. if (pointer.size !== size) {
  9605. pointer.size = size;
  9606. changed = true;
  9607. }
  9608. if (pointer.type !== type) {
  9609. pointer.type = type;
  9610. changed = true;
  9611. }
  9612. if (pointer.normalized !== normalized) {
  9613. pointer.normalized = normalized;
  9614. changed = true;
  9615. }
  9616. if (pointer.stride !== stride) {
  9617. pointer.stride = stride;
  9618. changed = true;
  9619. }
  9620. if (pointer.offset !== offset) {
  9621. pointer.offset = offset;
  9622. changed = true;
  9623. }
  9624. }
  9625. if (changed || this._vaoRecordInProgress) {
  9626. this.bindArrayBuffer(buffer);
  9627. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9628. }
  9629. };
  9630. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9631. if (indexBuffer == null) {
  9632. return;
  9633. }
  9634. if (this._cachedIndexBuffer !== indexBuffer) {
  9635. this._cachedIndexBuffer = indexBuffer;
  9636. this.bindIndexBuffer(indexBuffer);
  9637. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9638. }
  9639. };
  9640. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9641. var attributes = effect.getAttributesNames();
  9642. if (!this._vaoRecordInProgress) {
  9643. this._unbindVertexArrayObject();
  9644. }
  9645. this.unbindAllAttributes();
  9646. for (var index = 0; index < attributes.length; index++) {
  9647. var order = effect.getAttributeLocation(index);
  9648. if (order >= 0) {
  9649. var vertexBuffer = vertexBuffers[attributes[index]];
  9650. if (!vertexBuffer) {
  9651. continue;
  9652. }
  9653. this._gl.enableVertexAttribArray(order);
  9654. if (!this._vaoRecordInProgress) {
  9655. this._vertexAttribArraysEnabled[order] = true;
  9656. }
  9657. var buffer = vertexBuffer.getBuffer();
  9658. if (buffer) {
  9659. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9660. if (vertexBuffer.getIsInstanced()) {
  9661. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9662. if (!this._vaoRecordInProgress) {
  9663. this._currentInstanceLocations.push(order);
  9664. this._currentInstanceBuffers.push(buffer);
  9665. }
  9666. }
  9667. }
  9668. }
  9669. }
  9670. };
  9671. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9672. var vao = this._gl.createVertexArray();
  9673. this._vaoRecordInProgress = true;
  9674. this._gl.bindVertexArray(vao);
  9675. this._mustWipeVertexAttributes = true;
  9676. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9677. this.bindIndexBuffer(indexBuffer);
  9678. this._vaoRecordInProgress = false;
  9679. this._gl.bindVertexArray(null);
  9680. return vao;
  9681. };
  9682. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9683. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9684. this._cachedVertexArrayObject = vertexArrayObject;
  9685. this._gl.bindVertexArray(vertexArrayObject);
  9686. this._cachedVertexBuffers = null;
  9687. this._cachedIndexBuffer = null;
  9688. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9689. this._mustWipeVertexAttributes = true;
  9690. }
  9691. };
  9692. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9693. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9694. this._cachedVertexBuffers = vertexBuffer;
  9695. this._cachedEffectForVertexBuffers = effect;
  9696. var attributesCount = effect.getAttributesCount();
  9697. this._unbindVertexArrayObject();
  9698. this.unbindAllAttributes();
  9699. var offset = 0;
  9700. for (var index = 0; index < attributesCount; index++) {
  9701. if (index < vertexDeclaration.length) {
  9702. var order = effect.getAttributeLocation(index);
  9703. if (order >= 0) {
  9704. this._gl.enableVertexAttribArray(order);
  9705. this._vertexAttribArraysEnabled[order] = true;
  9706. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9707. }
  9708. offset += vertexDeclaration[index] * 4;
  9709. }
  9710. }
  9711. }
  9712. this._bindIndexBufferWithCache(indexBuffer);
  9713. };
  9714. Engine.prototype._unbindVertexArrayObject = function () {
  9715. if (!this._cachedVertexArrayObject) {
  9716. return;
  9717. }
  9718. this._cachedVertexArrayObject = null;
  9719. this._gl.bindVertexArray(null);
  9720. };
  9721. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9722. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9723. this._cachedVertexBuffers = vertexBuffers;
  9724. this._cachedEffectForVertexBuffers = effect;
  9725. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9726. }
  9727. this._bindIndexBufferWithCache(indexBuffer);
  9728. };
  9729. Engine.prototype.unbindInstanceAttributes = function () {
  9730. var boundBuffer;
  9731. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9732. var instancesBuffer = this._currentInstanceBuffers[i];
  9733. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9734. boundBuffer = instancesBuffer;
  9735. this.bindArrayBuffer(instancesBuffer);
  9736. }
  9737. var offsetLocation = this._currentInstanceLocations[i];
  9738. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9739. }
  9740. this._currentInstanceBuffers.length = 0;
  9741. this._currentInstanceLocations.length = 0;
  9742. };
  9743. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9744. this._gl.deleteVertexArray(vao);
  9745. };
  9746. Engine.prototype._releaseBuffer = function (buffer) {
  9747. buffer.references--;
  9748. if (buffer.references === 0) {
  9749. this._gl.deleteBuffer(buffer);
  9750. return true;
  9751. }
  9752. return false;
  9753. };
  9754. Engine.prototype.createInstancesBuffer = function (capacity) {
  9755. var buffer = this._gl.createBuffer();
  9756. if (!buffer) {
  9757. throw new Error("Unable to create instance buffer");
  9758. }
  9759. buffer.capacity = capacity;
  9760. this.bindArrayBuffer(buffer);
  9761. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9762. return buffer;
  9763. };
  9764. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9765. this._gl.deleteBuffer(buffer);
  9766. };
  9767. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9768. this.bindArrayBuffer(instancesBuffer);
  9769. if (data) {
  9770. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9771. }
  9772. if (offsetLocations[0].index !== undefined) {
  9773. var stride = 0;
  9774. for (var i = 0; i < offsetLocations.length; i++) {
  9775. var ai = offsetLocations[i];
  9776. stride += ai.attributeSize * 4;
  9777. }
  9778. for (var i = 0; i < offsetLocations.length; i++) {
  9779. var ai = offsetLocations[i];
  9780. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9781. this._gl.enableVertexAttribArray(ai.index);
  9782. this._vertexAttribArraysEnabled[ai.index] = true;
  9783. }
  9784. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9785. this._gl.vertexAttribDivisor(ai.index, 1);
  9786. this._currentInstanceLocations.push(ai.index);
  9787. this._currentInstanceBuffers.push(instancesBuffer);
  9788. }
  9789. }
  9790. else {
  9791. for (var index = 0; index < 4; index++) {
  9792. var offsetLocation = offsetLocations[index];
  9793. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9794. this._gl.enableVertexAttribArray(offsetLocation);
  9795. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9796. }
  9797. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9798. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9799. this._currentInstanceLocations.push(offsetLocation);
  9800. this._currentInstanceBuffers.push(instancesBuffer);
  9801. }
  9802. }
  9803. };
  9804. Engine.prototype.applyStates = function () {
  9805. this._depthCullingState.apply(this._gl);
  9806. this._stencilState.apply(this._gl);
  9807. this._alphaState.apply(this._gl);
  9808. };
  9809. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9810. // Apply states
  9811. this.applyStates();
  9812. this._drawCalls.addCount(1, false);
  9813. // Render
  9814. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9815. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9816. if (instancesCount) {
  9817. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9818. return;
  9819. }
  9820. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9821. };
  9822. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9823. // Apply states
  9824. this.applyStates();
  9825. this._drawCalls.addCount(1, false);
  9826. if (instancesCount) {
  9827. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9828. return;
  9829. }
  9830. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9831. };
  9832. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9833. // Apply states
  9834. this.applyStates();
  9835. this._drawCalls.addCount(1, false);
  9836. if (instancesCount) {
  9837. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9838. return;
  9839. }
  9840. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9841. };
  9842. // Shaders
  9843. Engine.prototype._releaseEffect = function (effect) {
  9844. if (this._compiledEffects[effect._key]) {
  9845. delete this._compiledEffects[effect._key];
  9846. this._deleteProgram(effect.getProgram());
  9847. }
  9848. };
  9849. Engine.prototype._deleteProgram = function (program) {
  9850. if (program) {
  9851. program.__SPECTOR_rebuildProgram = null;
  9852. if (program.transformFeedback) {
  9853. this.deleteTransformFeedback(program.transformFeedback);
  9854. program.transformFeedback = null;
  9855. }
  9856. this._gl.deleteProgram(program);
  9857. }
  9858. };
  9859. /**
  9860. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9861. * @param samplers An array of string used to represent textures
  9862. */
  9863. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9864. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9865. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9866. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9867. if (this._compiledEffects[name]) {
  9868. var compiledEffect = this._compiledEffects[name];
  9869. if (onCompiled && compiledEffect.isReady()) {
  9870. onCompiled(compiledEffect);
  9871. }
  9872. return compiledEffect;
  9873. }
  9874. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9875. effect._key = name;
  9876. this._compiledEffects[name] = effect;
  9877. return effect;
  9878. };
  9879. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9880. if (uniformsNames === void 0) { uniformsNames = []; }
  9881. if (samplers === void 0) { samplers = []; }
  9882. if (defines === void 0) { defines = ""; }
  9883. return this.createEffect({
  9884. vertex: "particles",
  9885. fragmentElement: fragmentName
  9886. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9887. };
  9888. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9889. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9890. context = context || this._gl;
  9891. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9892. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9893. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9894. };
  9895. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9896. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9897. context = context || this._gl;
  9898. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9899. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9900. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9901. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9902. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9903. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9904. return program;
  9905. };
  9906. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9907. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9908. var shaderProgram = context.createProgram();
  9909. if (!shaderProgram) {
  9910. throw new Error("Unable to create program");
  9911. }
  9912. context.attachShader(shaderProgram, vertexShader);
  9913. context.attachShader(shaderProgram, fragmentShader);
  9914. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9915. var transformFeedback = this.createTransformFeedback();
  9916. this.bindTransformFeedback(transformFeedback);
  9917. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9918. shaderProgram.transformFeedback = transformFeedback;
  9919. }
  9920. context.linkProgram(shaderProgram);
  9921. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9922. this.bindTransformFeedback(null);
  9923. }
  9924. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9925. if (!linked) {
  9926. context.validateProgram(shaderProgram);
  9927. var error = context.getProgramInfoLog(shaderProgram);
  9928. if (error) {
  9929. throw new Error(error);
  9930. }
  9931. }
  9932. context.deleteShader(vertexShader);
  9933. context.deleteShader(fragmentShader);
  9934. return shaderProgram;
  9935. };
  9936. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9937. var results = new Array();
  9938. for (var index = 0; index < uniformsNames.length; index++) {
  9939. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9940. }
  9941. return results;
  9942. };
  9943. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9944. var results = [];
  9945. for (var index = 0; index < attributesNames.length; index++) {
  9946. try {
  9947. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9948. }
  9949. catch (e) {
  9950. results.push(-1);
  9951. }
  9952. }
  9953. return results;
  9954. };
  9955. Engine.prototype.enableEffect = function (effect) {
  9956. if (!effect) {
  9957. return;
  9958. }
  9959. // Use program
  9960. this.setProgram(effect.getProgram());
  9961. this._currentEffect = effect;
  9962. if (effect.onBind) {
  9963. effect.onBind(effect);
  9964. }
  9965. effect.onBindObservable.notifyObservers(effect);
  9966. };
  9967. Engine.prototype.setIntArray = function (uniform, array) {
  9968. if (!uniform)
  9969. return;
  9970. this._gl.uniform1iv(uniform, array);
  9971. };
  9972. Engine.prototype.setIntArray2 = function (uniform, array) {
  9973. if (!uniform || array.length % 2 !== 0)
  9974. return;
  9975. this._gl.uniform2iv(uniform, array);
  9976. };
  9977. Engine.prototype.setIntArray3 = function (uniform, array) {
  9978. if (!uniform || array.length % 3 !== 0)
  9979. return;
  9980. this._gl.uniform3iv(uniform, array);
  9981. };
  9982. Engine.prototype.setIntArray4 = function (uniform, array) {
  9983. if (!uniform || array.length % 4 !== 0)
  9984. return;
  9985. this._gl.uniform4iv(uniform, array);
  9986. };
  9987. Engine.prototype.setFloatArray = function (uniform, array) {
  9988. if (!uniform)
  9989. return;
  9990. this._gl.uniform1fv(uniform, array);
  9991. };
  9992. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9993. if (!uniform || array.length % 2 !== 0)
  9994. return;
  9995. this._gl.uniform2fv(uniform, array);
  9996. };
  9997. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9998. if (!uniform || array.length % 3 !== 0)
  9999. return;
  10000. this._gl.uniform3fv(uniform, array);
  10001. };
  10002. Engine.prototype.setFloatArray4 = function (uniform, array) {
  10003. if (!uniform || array.length % 4 !== 0)
  10004. return;
  10005. this._gl.uniform4fv(uniform, array);
  10006. };
  10007. Engine.prototype.setArray = function (uniform, array) {
  10008. if (!uniform)
  10009. return;
  10010. this._gl.uniform1fv(uniform, array);
  10011. };
  10012. Engine.prototype.setArray2 = function (uniform, array) {
  10013. if (!uniform || array.length % 2 !== 0)
  10014. return;
  10015. this._gl.uniform2fv(uniform, array);
  10016. };
  10017. Engine.prototype.setArray3 = function (uniform, array) {
  10018. if (!uniform || array.length % 3 !== 0)
  10019. return;
  10020. this._gl.uniform3fv(uniform, array);
  10021. };
  10022. Engine.prototype.setArray4 = function (uniform, array) {
  10023. if (!uniform || array.length % 4 !== 0)
  10024. return;
  10025. this._gl.uniform4fv(uniform, array);
  10026. };
  10027. Engine.prototype.setMatrices = function (uniform, matrices) {
  10028. if (!uniform)
  10029. return;
  10030. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10031. };
  10032. Engine.prototype.setMatrix = function (uniform, matrix) {
  10033. if (!uniform)
  10034. return;
  10035. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10036. };
  10037. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10038. if (!uniform)
  10039. return;
  10040. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10041. };
  10042. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10043. if (!uniform)
  10044. return;
  10045. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10046. };
  10047. Engine.prototype.setFloat = function (uniform, value) {
  10048. if (!uniform)
  10049. return;
  10050. this._gl.uniform1f(uniform, value);
  10051. };
  10052. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10053. if (!uniform)
  10054. return;
  10055. this._gl.uniform2f(uniform, x, y);
  10056. };
  10057. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10058. if (!uniform)
  10059. return;
  10060. this._gl.uniform3f(uniform, x, y, z);
  10061. };
  10062. Engine.prototype.setBool = function (uniform, bool) {
  10063. if (!uniform)
  10064. return;
  10065. this._gl.uniform1i(uniform, bool);
  10066. };
  10067. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10068. if (!uniform)
  10069. return;
  10070. this._gl.uniform4f(uniform, x, y, z, w);
  10071. };
  10072. Engine.prototype.setColor3 = function (uniform, color3) {
  10073. if (!uniform)
  10074. return;
  10075. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10076. };
  10077. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10078. if (!uniform)
  10079. return;
  10080. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10081. };
  10082. // States
  10083. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10084. if (zOffset === void 0) { zOffset = 0; }
  10085. if (reverseSide === void 0) { reverseSide = false; }
  10086. // Culling
  10087. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  10088. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  10089. var cullFace = this.cullBackFaces ? showSide : hideSide;
  10090. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  10091. if (culling) {
  10092. this._depthCullingState.cullFace = cullFace;
  10093. this._depthCullingState.cull = true;
  10094. }
  10095. else {
  10096. this._depthCullingState.cull = false;
  10097. }
  10098. }
  10099. // Z offset
  10100. this.setZOffset(zOffset);
  10101. };
  10102. Engine.prototype.setZOffset = function (value) {
  10103. this._depthCullingState.zOffset = value;
  10104. };
  10105. Engine.prototype.getZOffset = function () {
  10106. return this._depthCullingState.zOffset;
  10107. };
  10108. Engine.prototype.setDepthBuffer = function (enable) {
  10109. this._depthCullingState.depthTest = enable;
  10110. };
  10111. Engine.prototype.getDepthWrite = function () {
  10112. return this._depthCullingState.depthMask;
  10113. };
  10114. Engine.prototype.setDepthWrite = function (enable) {
  10115. this._depthCullingState.depthMask = enable;
  10116. };
  10117. Engine.prototype.setColorWrite = function (enable) {
  10118. this._gl.colorMask(enable, enable, enable, enable);
  10119. this._colorWrite = enable;
  10120. };
  10121. Engine.prototype.getColorWrite = function () {
  10122. return this._colorWrite;
  10123. };
  10124. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10125. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10126. };
  10127. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10128. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10129. if (this._alphaMode === mode) {
  10130. return;
  10131. }
  10132. switch (mode) {
  10133. case Engine.ALPHA_DISABLE:
  10134. this._alphaState.alphaBlend = false;
  10135. break;
  10136. case Engine.ALPHA_PREMULTIPLIED:
  10137. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10138. this._alphaState.alphaBlend = true;
  10139. break;
  10140. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10141. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10142. this._alphaState.alphaBlend = true;
  10143. break;
  10144. case Engine.ALPHA_COMBINE:
  10145. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10146. this._alphaState.alphaBlend = true;
  10147. break;
  10148. case Engine.ALPHA_ONEONE:
  10149. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10150. this._alphaState.alphaBlend = true;
  10151. break;
  10152. case Engine.ALPHA_ADD:
  10153. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10154. this._alphaState.alphaBlend = true;
  10155. break;
  10156. case Engine.ALPHA_SUBTRACT:
  10157. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10158. this._alphaState.alphaBlend = true;
  10159. break;
  10160. case Engine.ALPHA_MULTIPLY:
  10161. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10162. this._alphaState.alphaBlend = true;
  10163. break;
  10164. case Engine.ALPHA_MAXIMIZED:
  10165. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10166. this._alphaState.alphaBlend = true;
  10167. break;
  10168. case Engine.ALPHA_INTERPOLATE:
  10169. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10170. this._alphaState.alphaBlend = true;
  10171. break;
  10172. case Engine.ALPHA_SCREENMODE:
  10173. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10174. this._alphaState.alphaBlend = true;
  10175. break;
  10176. }
  10177. if (!noDepthWriteChange) {
  10178. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10179. }
  10180. this._alphaMode = mode;
  10181. };
  10182. Engine.prototype.getAlphaMode = function () {
  10183. return this._alphaMode;
  10184. };
  10185. Engine.prototype.setAlphaTesting = function (enable) {
  10186. this._alphaTest = enable;
  10187. };
  10188. Engine.prototype.getAlphaTesting = function () {
  10189. return !!this._alphaTest;
  10190. };
  10191. // Textures
  10192. Engine.prototype.wipeCaches = function (bruteForce) {
  10193. if (this.preventCacheWipeBetweenFrames) {
  10194. return;
  10195. }
  10196. this.resetTextureCache();
  10197. this._currentEffect = null;
  10198. // 6/8/2017: deltakosh: Should not be required anymore.
  10199. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10200. if (bruteForce) {
  10201. this._currentProgram = null;
  10202. this._stencilState.reset();
  10203. this._depthCullingState.reset();
  10204. this.setDepthFunctionToLessOrEqual();
  10205. this._alphaState.reset();
  10206. }
  10207. this._cachedVertexBuffers = null;
  10208. this._cachedIndexBuffer = null;
  10209. this._cachedEffectForVertexBuffers = null;
  10210. this._unbindVertexArrayObject();
  10211. this.bindIndexBuffer(null);
  10212. this.bindArrayBuffer(null);
  10213. };
  10214. /**
  10215. * Set the compressed texture format to use, based on the formats you have, and the formats
  10216. * supported by the hardware / browser.
  10217. *
  10218. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10219. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10220. * to API arguments needed to compressed textures. This puts the burden on the container
  10221. * generator to house the arcane code for determining these for current & future formats.
  10222. *
  10223. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10224. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10225. *
  10226. * Note: The result of this call is not taken into account when a texture is base64.
  10227. *
  10228. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10229. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10230. *
  10231. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10232. * @returns The extension selected.
  10233. */
  10234. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10235. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10236. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10237. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10238. return this._textureFormatInUse = this._texturesSupported[i];
  10239. }
  10240. }
  10241. }
  10242. // actively set format to nothing, to allow this to be called more than once
  10243. // and possibly fail the 2nd time
  10244. this._textureFormatInUse = null;
  10245. return null;
  10246. };
  10247. Engine.prototype._createTexture = function () {
  10248. var texture = this._gl.createTexture();
  10249. if (!texture) {
  10250. throw new Error("Unable to create texture");
  10251. }
  10252. return texture;
  10253. };
  10254. /**
  10255. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10256. * @param {string} urlArg- This contains one of the following:
  10257. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10258. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10259. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10260. *
  10261. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10262. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10263. * @param {Scene} scene- Needed for loading to the correct scene.
  10264. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10265. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10266. * @param {callback} onError- Optional callback to be called upon failure.
  10267. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10268. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10269. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10270. *
  10271. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10272. */
  10273. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10274. var _this = this;
  10275. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10276. if (onLoad === void 0) { onLoad = null; }
  10277. if (onError === void 0) { onError = null; }
  10278. if (buffer === void 0) { buffer = null; }
  10279. if (fallBack === void 0) { fallBack = null; }
  10280. if (format === void 0) { format = null; }
  10281. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10282. var fromData = url.substr(0, 5) === "data:";
  10283. var fromBlob = url.substr(0, 5) === "blob:";
  10284. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10285. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10286. // establish the file extension, if possible
  10287. var lastDot = url.lastIndexOf('.');
  10288. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10289. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10290. var isTGA = (extension === ".tga");
  10291. // determine if a ktx file should be substituted
  10292. var isKTX = false;
  10293. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10294. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10295. isKTX = true;
  10296. }
  10297. if (scene) {
  10298. scene._addPendingData(texture);
  10299. }
  10300. texture.url = url;
  10301. texture.generateMipMaps = !noMipmap;
  10302. texture.samplingMode = samplingMode;
  10303. texture.invertY = invertY;
  10304. if (!this._doNotHandleContextLost) {
  10305. // Keep a link to the buffer only if we plan to handle context lost
  10306. texture._buffer = buffer;
  10307. }
  10308. if (onLoad) {
  10309. texture.onLoadedObservable.add(onLoad);
  10310. }
  10311. if (!fallBack)
  10312. this._internalTexturesCache.push(texture);
  10313. var onerror = function () {
  10314. if (scene) {
  10315. scene._removePendingData(texture);
  10316. }
  10317. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10318. if (isKTX) {
  10319. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10320. }
  10321. else if ((isTGA || isDDS) && BABYLON.Tools.UseFallbackTexture) {
  10322. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10323. }
  10324. else if (onError) {
  10325. onError();
  10326. }
  10327. };
  10328. var callback = null;
  10329. // processing for non-image formats
  10330. if (isKTX || isTGA || isDDS) {
  10331. if (isKTX) {
  10332. callback = function (data) {
  10333. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10334. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10335. ktx.uploadLevels(_this._gl, !noMipmap);
  10336. return false;
  10337. }, samplingMode);
  10338. };
  10339. }
  10340. else if (isTGA) {
  10341. callback = function (arrayBuffer) {
  10342. var data = new Uint8Array(arrayBuffer);
  10343. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10344. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10345. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10346. return false;
  10347. }, samplingMode);
  10348. };
  10349. }
  10350. else if (isDDS) {
  10351. callback = function (data) {
  10352. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10353. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10354. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10355. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10356. return false;
  10357. }, samplingMode);
  10358. };
  10359. }
  10360. if (!buffer) {
  10361. BABYLON.Tools.LoadFile(url, function (data) {
  10362. if (callback) {
  10363. callback(data);
  10364. }
  10365. }, undefined, scene ? scene.database : undefined, true, onerror);
  10366. }
  10367. else {
  10368. if (callback) {
  10369. callback(buffer);
  10370. }
  10371. }
  10372. // image format processing
  10373. }
  10374. else {
  10375. var onload = function (img) {
  10376. if (fromBlob && !_this._doNotHandleContextLost) {
  10377. // We need to store the image if we need to rebuild the texture
  10378. // in case of a webgl context lost
  10379. texture._buffer = img;
  10380. }
  10381. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10382. var gl = _this._gl;
  10383. var isPot = (img.width === potWidth && img.height === potHeight);
  10384. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10385. if (isPot) {
  10386. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10387. return false;
  10388. }
  10389. // Using shaders to rescale because canvas.drawImage is lossy
  10390. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10391. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10392. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10394. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10395. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10396. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10397. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10398. _this._releaseTexture(source);
  10399. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10400. continuationCallback();
  10401. });
  10402. return true;
  10403. }, samplingMode);
  10404. };
  10405. if (!fromData || isBase64)
  10406. if (buffer instanceof HTMLImageElement) {
  10407. onload(buffer);
  10408. }
  10409. else {
  10410. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10411. }
  10412. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10413. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10414. else
  10415. onload(buffer);
  10416. }
  10417. return texture;
  10418. };
  10419. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10420. var _this = this;
  10421. var rtt = this.createRenderTargetTexture({
  10422. width: destination.width,
  10423. height: destination.height,
  10424. }, {
  10425. generateMipMaps: false,
  10426. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10427. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10428. generateDepthBuffer: false,
  10429. generateStencilBuffer: false
  10430. });
  10431. if (!this._rescalePostProcess) {
  10432. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10433. }
  10434. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10435. _this._rescalePostProcess.onApply = function (effect) {
  10436. effect._bindTexture("textureSampler", source);
  10437. };
  10438. var hostingScene = scene;
  10439. if (!hostingScene) {
  10440. hostingScene = _this.scenes[_this.scenes.length - 1];
  10441. }
  10442. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10443. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10444. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10445. _this.unBindFramebuffer(rtt);
  10446. _this._releaseTexture(rtt);
  10447. if (onComplete) {
  10448. onComplete();
  10449. }
  10450. });
  10451. };
  10452. Engine.prototype._getInternalFormat = function (format) {
  10453. var internalFormat = this._gl.RGBA;
  10454. switch (format) {
  10455. case Engine.TEXTUREFORMAT_ALPHA:
  10456. internalFormat = this._gl.ALPHA;
  10457. break;
  10458. case Engine.TEXTUREFORMAT_LUMINANCE:
  10459. internalFormat = this._gl.LUMINANCE;
  10460. break;
  10461. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10462. internalFormat = this._gl.LUMINANCE_ALPHA;
  10463. break;
  10464. case Engine.TEXTUREFORMAT_RGB:
  10465. internalFormat = this._gl.RGB;
  10466. break;
  10467. case Engine.TEXTUREFORMAT_RGBA:
  10468. internalFormat = this._gl.RGBA;
  10469. break;
  10470. }
  10471. return internalFormat;
  10472. };
  10473. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10474. if (compression === void 0) { compression = null; }
  10475. if (!texture) {
  10476. return;
  10477. }
  10478. var internalFormat = this._getInternalFormat(format);
  10479. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10480. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10481. if (!this._doNotHandleContextLost) {
  10482. texture._bufferView = data;
  10483. texture.format = format;
  10484. texture.invertY = invertY;
  10485. texture._compression = compression;
  10486. }
  10487. if (texture.width % 4 !== 0) {
  10488. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10489. }
  10490. if (compression && data) {
  10491. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10492. }
  10493. else {
  10494. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10495. }
  10496. if (texture.generateMipMaps) {
  10497. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10498. }
  10499. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10500. this.resetTextureCache();
  10501. texture.isReady = true;
  10502. };
  10503. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10504. if (compression === void 0) { compression = null; }
  10505. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10506. texture.baseWidth = width;
  10507. texture.baseHeight = height;
  10508. texture.width = width;
  10509. texture.height = height;
  10510. texture.format = format;
  10511. texture.generateMipMaps = generateMipMaps;
  10512. texture.samplingMode = samplingMode;
  10513. texture.invertY = invertY;
  10514. texture._compression = compression;
  10515. if (!this._doNotHandleContextLost) {
  10516. texture._bufferView = data;
  10517. }
  10518. this.updateRawTexture(texture, data, format, invertY, compression);
  10519. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10520. // Filters
  10521. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10522. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10523. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10524. if (generateMipMaps) {
  10525. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10526. }
  10527. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10528. this._internalTexturesCache.push(texture);
  10529. return texture;
  10530. };
  10531. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10532. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10533. texture.baseWidth = width;
  10534. texture.baseHeight = height;
  10535. if (generateMipMaps) {
  10536. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10537. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10538. }
  10539. this.resetTextureCache();
  10540. texture.width = width;
  10541. texture.height = height;
  10542. texture.isReady = false;
  10543. texture.generateMipMaps = generateMipMaps;
  10544. texture.samplingMode = samplingMode;
  10545. this.updateTextureSamplingMode(samplingMode, texture);
  10546. this._internalTexturesCache.push(texture);
  10547. return texture;
  10548. };
  10549. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10550. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10551. if (texture.isCube) {
  10552. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10553. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10554. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10555. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10556. }
  10557. else if (texture.is3D) {
  10558. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10559. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10560. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10561. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10562. }
  10563. else {
  10564. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10565. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10566. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10567. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10568. }
  10569. texture.samplingMode = samplingMode;
  10570. };
  10571. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10572. if (premulAlpha === void 0) { premulAlpha = false; }
  10573. if (!texture) {
  10574. return;
  10575. }
  10576. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10577. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10578. if (premulAlpha) {
  10579. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10580. }
  10581. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10582. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10583. if (texture.generateMipMaps) {
  10584. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10585. }
  10586. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10587. if (premulAlpha) {
  10588. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10589. }
  10590. this.resetTextureCache();
  10591. texture.isReady = true;
  10592. };
  10593. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10594. if (!texture || texture._isDisabled) {
  10595. return;
  10596. }
  10597. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10598. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10599. try {
  10600. // Testing video texture support
  10601. if (this._videoTextureSupported === undefined) {
  10602. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10603. if (this._gl.getError() !== 0) {
  10604. this._videoTextureSupported = false;
  10605. }
  10606. else {
  10607. this._videoTextureSupported = true;
  10608. }
  10609. }
  10610. // Copy video through the current working canvas if video texture is not supported
  10611. if (!this._videoTextureSupported) {
  10612. if (!texture._workingCanvas) {
  10613. texture._workingCanvas = document.createElement("canvas");
  10614. var context = texture._workingCanvas.getContext("2d");
  10615. if (!context) {
  10616. throw new Error("Unable to get 2d context");
  10617. }
  10618. texture._workingContext = context;
  10619. texture._workingCanvas.width = texture.width;
  10620. texture._workingCanvas.height = texture.height;
  10621. }
  10622. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10623. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10624. }
  10625. else {
  10626. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10627. }
  10628. if (texture.generateMipMaps) {
  10629. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10630. }
  10631. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10632. this.resetTextureCache();
  10633. texture.isReady = true;
  10634. }
  10635. catch (ex) {
  10636. // Something unexpected
  10637. // Let's disable the texture
  10638. texture._isDisabled = true;
  10639. }
  10640. };
  10641. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10642. var fullOptions = new RenderTargetCreationOptions();
  10643. if (options !== undefined && typeof options === "object") {
  10644. fullOptions.generateMipMaps = options.generateMipMaps;
  10645. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10646. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10647. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10648. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10649. }
  10650. else {
  10651. fullOptions.generateMipMaps = options;
  10652. fullOptions.generateDepthBuffer = true;
  10653. fullOptions.generateStencilBuffer = false;
  10654. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10655. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10656. }
  10657. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10658. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10659. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10660. }
  10661. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10662. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10663. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10664. }
  10665. var gl = this._gl;
  10666. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10667. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10668. var width = size.width || size;
  10669. var height = size.height || size;
  10670. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10671. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10672. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10673. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10674. }
  10675. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10676. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10677. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10678. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10679. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10680. // Create the framebuffer
  10681. var framebuffer = gl.createFramebuffer();
  10682. this.bindUnboundFramebuffer(framebuffer);
  10683. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10684. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10685. if (fullOptions.generateMipMaps) {
  10686. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10687. }
  10688. // Unbind
  10689. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10690. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10691. this.bindUnboundFramebuffer(null);
  10692. texture._framebuffer = framebuffer;
  10693. texture.baseWidth = width;
  10694. texture.baseHeight = height;
  10695. texture.width = width;
  10696. texture.height = height;
  10697. texture.isReady = true;
  10698. texture.samples = 1;
  10699. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10700. texture.samplingMode = fullOptions.samplingMode;
  10701. texture.type = fullOptions.type;
  10702. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10703. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10704. this.resetTextureCache();
  10705. this._internalTexturesCache.push(texture);
  10706. return texture;
  10707. };
  10708. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10709. var generateMipMaps = false;
  10710. var generateDepthBuffer = true;
  10711. var generateStencilBuffer = false;
  10712. var generateDepthTexture = false;
  10713. var textureCount = 1;
  10714. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10715. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10716. var types = [], samplingModes = [];
  10717. if (options !== undefined) {
  10718. generateMipMaps = options.generateMipMaps;
  10719. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10720. generateStencilBuffer = options.generateStencilBuffer;
  10721. generateDepthTexture = options.generateDepthTexture;
  10722. textureCount = options.textureCount || 1;
  10723. if (options.types) {
  10724. types = options.types;
  10725. }
  10726. if (options.samplingModes) {
  10727. samplingModes = options.samplingModes;
  10728. }
  10729. }
  10730. var gl = this._gl;
  10731. // Create the framebuffer
  10732. var framebuffer = gl.createFramebuffer();
  10733. this.bindUnboundFramebuffer(framebuffer);
  10734. var width = size.width || size;
  10735. var height = size.height || size;
  10736. var textures = [];
  10737. var attachments = [];
  10738. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10739. for (var i = 0; i < textureCount; i++) {
  10740. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10741. var type = types[i] || defaultType;
  10742. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10743. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10744. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10745. }
  10746. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10747. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10748. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10749. }
  10750. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10751. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10752. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10753. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10754. }
  10755. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10756. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10757. textures.push(texture);
  10758. attachments.push(attachment);
  10759. gl.activeTexture(gl["TEXTURE" + i]);
  10760. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10765. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10766. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10767. if (generateMipMaps) {
  10768. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10769. }
  10770. // Unbind
  10771. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10772. texture._framebuffer = framebuffer;
  10773. texture._depthStencilBuffer = depthStencilBuffer;
  10774. texture.baseWidth = width;
  10775. texture.baseHeight = height;
  10776. texture.width = width;
  10777. texture.height = height;
  10778. texture.isReady = true;
  10779. texture.samples = 1;
  10780. texture.generateMipMaps = generateMipMaps;
  10781. texture.samplingMode = samplingMode;
  10782. texture.type = type;
  10783. texture._generateDepthBuffer = generateDepthBuffer;
  10784. texture._generateStencilBuffer = generateStencilBuffer;
  10785. this._internalTexturesCache.push(texture);
  10786. }
  10787. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10788. // Depth texture
  10789. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10790. gl.activeTexture(gl.TEXTURE0);
  10791. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10792. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10793. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10794. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10795. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10796. 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);
  10797. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10798. depthTexture._framebuffer = framebuffer;
  10799. depthTexture.baseWidth = width;
  10800. depthTexture.baseHeight = height;
  10801. depthTexture.width = width;
  10802. depthTexture.height = height;
  10803. depthTexture.isReady = true;
  10804. depthTexture.samples = 1;
  10805. depthTexture.generateMipMaps = generateMipMaps;
  10806. depthTexture.samplingMode = gl.NEAREST;
  10807. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10808. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10809. textures.push(depthTexture);
  10810. this._internalTexturesCache.push(depthTexture);
  10811. }
  10812. gl.drawBuffers(attachments);
  10813. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10814. this.bindUnboundFramebuffer(null);
  10815. this.resetTextureCache();
  10816. return textures;
  10817. };
  10818. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10819. if (samples === void 0) { samples = 1; }
  10820. var depthStencilBuffer = null;
  10821. var gl = this._gl;
  10822. // Create the depth/stencil buffer
  10823. if (generateStencilBuffer) {
  10824. depthStencilBuffer = gl.createRenderbuffer();
  10825. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10826. if (samples > 1) {
  10827. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10828. }
  10829. else {
  10830. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10831. }
  10832. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10833. }
  10834. else if (generateDepthBuffer) {
  10835. depthStencilBuffer = gl.createRenderbuffer();
  10836. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10837. if (samples > 1) {
  10838. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10839. }
  10840. else {
  10841. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10842. }
  10843. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10844. }
  10845. return depthStencilBuffer;
  10846. };
  10847. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10848. if (this.webGLVersion < 2 || !texture) {
  10849. return 1;
  10850. }
  10851. if (texture.samples === samples) {
  10852. return samples;
  10853. }
  10854. var gl = this._gl;
  10855. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10856. // Dispose previous render buffers
  10857. if (texture._depthStencilBuffer) {
  10858. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10859. }
  10860. if (texture._MSAAFramebuffer) {
  10861. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10862. }
  10863. if (texture._MSAARenderBuffer) {
  10864. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10865. }
  10866. if (samples > 1) {
  10867. var framebuffer = gl.createFramebuffer();
  10868. if (!framebuffer) {
  10869. throw new Error("Unable to create multi sampled framebuffer");
  10870. }
  10871. texture._MSAAFramebuffer = framebuffer;
  10872. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10873. var colorRenderbuffer = gl.createRenderbuffer();
  10874. if (!colorRenderbuffer) {
  10875. throw new Error("Unable to create multi sampled framebuffer");
  10876. }
  10877. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10878. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10879. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10880. texture._MSAARenderBuffer = colorRenderbuffer;
  10881. }
  10882. else {
  10883. this.bindUnboundFramebuffer(texture._framebuffer);
  10884. }
  10885. texture.samples = samples;
  10886. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10887. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10888. this.bindUnboundFramebuffer(null);
  10889. return samples;
  10890. };
  10891. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10892. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10893. };
  10894. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10895. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10896. };
  10897. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10898. var gl = this._gl;
  10899. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10900. var generateMipMaps = true;
  10901. var generateDepthBuffer = true;
  10902. var generateStencilBuffer = false;
  10903. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10904. if (options !== undefined) {
  10905. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10906. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10907. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10908. if (options.samplingMode !== undefined) {
  10909. samplingMode = options.samplingMode;
  10910. }
  10911. }
  10912. texture.isCube = true;
  10913. texture.generateMipMaps = generateMipMaps;
  10914. texture.samples = 1;
  10915. texture.samplingMode = samplingMode;
  10916. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10917. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10918. for (var face = 0; face < 6; face++) {
  10919. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10920. }
  10921. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10922. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10923. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10924. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10925. // Create the framebuffer
  10926. var framebuffer = gl.createFramebuffer();
  10927. this.bindUnboundFramebuffer(framebuffer);
  10928. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10929. // Mipmaps
  10930. if (texture.generateMipMaps) {
  10931. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10932. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10933. }
  10934. // Unbind
  10935. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10936. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10937. this.bindUnboundFramebuffer(null);
  10938. texture._framebuffer = framebuffer;
  10939. texture.width = size;
  10940. texture.height = size;
  10941. texture.isReady = true;
  10942. this.resetTextureCache();
  10943. this._internalTexturesCache.push(texture);
  10944. return texture;
  10945. };
  10946. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10947. var _this = this;
  10948. if (onLoad === void 0) { onLoad = null; }
  10949. if (onError === void 0) { onError = null; }
  10950. if (forcedExtension === void 0) { forcedExtension = null; }
  10951. var callback = function (loadData) {
  10952. if (!loadData) {
  10953. if (onLoad) {
  10954. onLoad(null);
  10955. }
  10956. return;
  10957. }
  10958. var texture = loadData.texture;
  10959. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10960. texture._lodGenerationScale = scale;
  10961. texture._lodGenerationOffset = offset;
  10962. if (_this._caps.textureLOD) {
  10963. // Do not add extra process if texture lod is supported.
  10964. if (onLoad) {
  10965. onLoad(texture);
  10966. }
  10967. return;
  10968. }
  10969. var mipSlices = 3;
  10970. var gl = _this._gl;
  10971. var width = loadData.width;
  10972. if (!width) {
  10973. return;
  10974. }
  10975. var textures = [];
  10976. for (var i = 0; i < mipSlices; i++) {
  10977. //compute LOD from even spacing in smoothness (matching shader calculation)
  10978. var smoothness = i / (mipSlices - 1);
  10979. var roughness = 1 - smoothness;
  10980. var minLODIndex = offset; // roughness = 0
  10981. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10982. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10983. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10984. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10985. glTextureFromLod.isCube = true;
  10986. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10987. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10988. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10990. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10991. if (loadData.isDDS) {
  10992. var info = loadData.info;
  10993. var data = loadData.data;
  10994. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10995. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10996. }
  10997. else {
  10998. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10999. }
  11000. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11001. // Wrap in a base texture for easy binding.
  11002. var lodTexture = new BABYLON.BaseTexture(scene);
  11003. lodTexture.isCube = true;
  11004. lodTexture._texture = glTextureFromLod;
  11005. glTextureFromLod.isReady = true;
  11006. textures.push(lodTexture);
  11007. }
  11008. texture._lodTextureHigh = textures[2];
  11009. texture._lodTextureMid = textures[1];
  11010. texture._lodTextureLow = textures[0];
  11011. if (onLoad) {
  11012. onLoad(texture);
  11013. }
  11014. };
  11015. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  11016. };
  11017. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  11018. var _this = this;
  11019. if (onLoad === void 0) { onLoad = null; }
  11020. if (onError === void 0) { onError = null; }
  11021. if (forcedExtension === void 0) { forcedExtension = null; }
  11022. var gl = this._gl;
  11023. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  11024. texture.isCube = true;
  11025. texture.url = rootUrl;
  11026. texture.generateMipMaps = !noMipmap;
  11027. if (!this._doNotHandleContextLost) {
  11028. texture._extension = forcedExtension;
  11029. texture._files = files;
  11030. }
  11031. var isKTX = false;
  11032. var isDDS = false;
  11033. var lastDot = rootUrl.lastIndexOf('.');
  11034. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11035. if (this._textureFormatInUse) {
  11036. extension = this._textureFormatInUse;
  11037. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11038. isKTX = true;
  11039. }
  11040. else {
  11041. isDDS = (extension === ".dds");
  11042. }
  11043. var onerror = function (request, exception) {
  11044. if (onError) {
  11045. onError(request.status + " " + request.statusText, exception);
  11046. }
  11047. };
  11048. if (isKTX) {
  11049. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11050. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11051. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11052. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11053. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11054. ktx.uploadLevels(_this._gl, !noMipmap);
  11055. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11056. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11057. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11058. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11059. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11060. _this.resetTextureCache();
  11061. texture.width = ktx.pixelWidth;
  11062. texture.height = ktx.pixelHeight;
  11063. texture.isReady = true;
  11064. }, undefined, undefined, true, onerror);
  11065. }
  11066. else if (isDDS) {
  11067. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11068. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11069. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11070. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11071. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11072. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11073. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11074. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11075. }
  11076. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11077. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11080. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11081. _this.resetTextureCache();
  11082. texture.width = info.width;
  11083. texture.height = info.height;
  11084. texture.isReady = true;
  11085. texture.type = info.textureType;
  11086. if (onLoad) {
  11087. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11088. }
  11089. }, undefined, undefined, true, onerror);
  11090. }
  11091. else {
  11092. if (!files) {
  11093. throw new Error("Cannot load cubemap because files were not defined");
  11094. }
  11095. cascadeLoad(rootUrl, scene, function (imgs) {
  11096. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11097. var height = width;
  11098. _this._prepareWorkingCanvas();
  11099. if (!_this._workingCanvas || !_this._workingContext) {
  11100. return;
  11101. }
  11102. _this._workingCanvas.width = width;
  11103. _this._workingCanvas.height = height;
  11104. var faces = [
  11105. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11106. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11107. ];
  11108. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11109. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11110. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11111. for (var index = 0; index < faces.length; index++) {
  11112. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11113. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11114. }
  11115. if (!noMipmap) {
  11116. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11117. }
  11118. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11119. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  11120. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11122. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11123. _this.resetTextureCache();
  11124. texture.width = width;
  11125. texture.height = height;
  11126. texture.isReady = true;
  11127. if (format) {
  11128. texture.format = format;
  11129. }
  11130. texture.onLoadedObservable.notifyObservers(texture);
  11131. texture.onLoadedObservable.clear();
  11132. if (onLoad) {
  11133. onLoad();
  11134. }
  11135. }, files, onError);
  11136. }
  11137. this._internalTexturesCache.push(texture);
  11138. return texture;
  11139. };
  11140. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11141. if (compression === void 0) { compression = null; }
  11142. if (level === void 0) { level = 0; }
  11143. texture._bufferViewArray = data;
  11144. texture.format = format;
  11145. texture.type = type;
  11146. texture.invertY = invertY;
  11147. texture._compression = compression;
  11148. var gl = this._gl;
  11149. var textureType = this._getWebGLTextureType(type);
  11150. var internalFormat = this._getInternalFormat(format);
  11151. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11152. var needConversion = false;
  11153. if (internalFormat === gl.RGB) {
  11154. internalFormat = gl.RGBA;
  11155. needConversion = true;
  11156. }
  11157. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11158. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11159. if (texture.width % 4 !== 0) {
  11160. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11161. }
  11162. // Data are known to be in +X +Y +Z -X -Y -Z
  11163. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11164. var faceData = data[faceIndex];
  11165. if (compression) {
  11166. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11167. }
  11168. else {
  11169. if (needConversion) {
  11170. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11171. }
  11172. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11173. }
  11174. }
  11175. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11176. if (isPot && texture.generateMipMaps && level === 0) {
  11177. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11178. }
  11179. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11180. this.resetTextureCache();
  11181. texture.isReady = true;
  11182. };
  11183. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11184. if (compression === void 0) { compression = null; }
  11185. var gl = this._gl;
  11186. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11187. texture.isCube = true;
  11188. texture.generateMipMaps = generateMipMaps;
  11189. texture.format = format;
  11190. texture.type = type;
  11191. if (!this._doNotHandleContextLost) {
  11192. texture._bufferViewArray = data;
  11193. }
  11194. var textureType = this._getWebGLTextureType(type);
  11195. var internalFormat = this._getInternalFormat(format);
  11196. var needConversion = false;
  11197. if (internalFormat === gl.RGB) {
  11198. internalFormat = gl.RGBA;
  11199. needConversion = true;
  11200. }
  11201. var width = size;
  11202. var height = width;
  11203. texture.width = width;
  11204. texture.height = height;
  11205. // Double check on POT to generate Mips.
  11206. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11207. if (!isPot) {
  11208. generateMipMaps = false;
  11209. }
  11210. // Upload data if needed. The texture won't be ready until then.
  11211. if (data) {
  11212. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11213. }
  11214. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11215. // Filters
  11216. if (data && generateMipMaps) {
  11217. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11218. }
  11219. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11221. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11222. }
  11223. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11224. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11226. }
  11227. else {
  11228. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11229. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11230. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11231. }
  11232. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11233. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11234. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11235. return texture;
  11236. };
  11237. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11238. var _this = this;
  11239. if (onLoad === void 0) { onLoad = null; }
  11240. if (onError === void 0) { onError = null; }
  11241. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11242. if (invertY === void 0) { invertY = false; }
  11243. var gl = this._gl;
  11244. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11245. scene._addPendingData(texture);
  11246. texture.url = url;
  11247. this._internalTexturesCache.push(texture);
  11248. var onerror = function (request, exception) {
  11249. scene._removePendingData(texture);
  11250. if (onError) {
  11251. onError(request.status + " " + request.statusText, exception);
  11252. }
  11253. };
  11254. var internalCallback = function (data) {
  11255. var width = texture.width;
  11256. var faceDataArrays = callback(data);
  11257. if (!faceDataArrays) {
  11258. return;
  11259. }
  11260. if (mipmmapGenerator) {
  11261. var textureType = _this._getWebGLTextureType(type);
  11262. var internalFormat = _this._getInternalFormat(format);
  11263. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11264. var needConversion = false;
  11265. if (internalFormat === gl.RGB) {
  11266. internalFormat = gl.RGBA;
  11267. needConversion = true;
  11268. }
  11269. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11270. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11271. var mipData = mipmmapGenerator(faceDataArrays);
  11272. for (var level = 0; level < mipData.length; level++) {
  11273. var mipSize = width >> level;
  11274. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11275. var mipFaceData = mipData[level][faceIndex];
  11276. if (needConversion) {
  11277. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11278. }
  11279. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11280. }
  11281. }
  11282. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11283. }
  11284. else {
  11285. texture.generateMipMaps = !noMipmap;
  11286. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11287. }
  11288. texture.isReady = true;
  11289. _this.resetTextureCache();
  11290. scene._removePendingData(texture);
  11291. if (onLoad) {
  11292. onLoad();
  11293. }
  11294. };
  11295. BABYLON.Tools.LoadFile(url, function (data) {
  11296. internalCallback(data);
  11297. }, undefined, scene.database, true, onerror);
  11298. return texture;
  11299. };
  11300. ;
  11301. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11302. if (compression === void 0) { compression = null; }
  11303. var internalFormat = this._getInternalFormat(format);
  11304. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11305. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11306. if (!this._doNotHandleContextLost) {
  11307. texture._bufferView = data;
  11308. texture.format = format;
  11309. texture.invertY = invertY;
  11310. texture._compression = compression;
  11311. }
  11312. if (texture.width % 4 !== 0) {
  11313. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11314. }
  11315. if (compression && data) {
  11316. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11317. }
  11318. else {
  11319. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11320. }
  11321. if (texture.generateMipMaps) {
  11322. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11323. }
  11324. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11325. this.resetTextureCache();
  11326. texture.isReady = true;
  11327. };
  11328. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11329. if (compression === void 0) { compression = null; }
  11330. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11331. texture.baseWidth = width;
  11332. texture.baseHeight = height;
  11333. texture.baseDepth = depth;
  11334. texture.width = width;
  11335. texture.height = height;
  11336. texture.depth = depth;
  11337. texture.format = format;
  11338. texture.generateMipMaps = generateMipMaps;
  11339. texture.samplingMode = samplingMode;
  11340. texture.is3D = true;
  11341. if (!this._doNotHandleContextLost) {
  11342. texture._bufferView = data;
  11343. }
  11344. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11345. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11346. // Filters
  11347. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11348. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11349. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11350. if (generateMipMaps) {
  11351. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11352. }
  11353. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11354. this._internalTexturesCache.push(texture);
  11355. return texture;
  11356. };
  11357. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11358. var gl = this._gl;
  11359. if (!gl) {
  11360. return;
  11361. }
  11362. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11363. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11364. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11365. if (!noMipmap && !isCompressed) {
  11366. gl.generateMipmap(gl.TEXTURE_2D);
  11367. }
  11368. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11369. this.resetTextureCache();
  11370. if (scene) {
  11371. scene._removePendingData(texture);
  11372. }
  11373. texture.onLoadedObservable.notifyObservers(texture);
  11374. texture.onLoadedObservable.clear();
  11375. };
  11376. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11377. var _this = this;
  11378. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11379. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11380. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11381. var gl = this._gl;
  11382. if (!gl) {
  11383. return;
  11384. }
  11385. if (!texture._webGLTexture) {
  11386. this.resetTextureCache();
  11387. if (scene) {
  11388. scene._removePendingData(texture);
  11389. }
  11390. return;
  11391. }
  11392. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11393. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11394. texture.baseWidth = width;
  11395. texture.baseHeight = height;
  11396. texture.width = potWidth;
  11397. texture.height = potHeight;
  11398. texture.isReady = true;
  11399. if (processFunction(potWidth, potHeight, function () {
  11400. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11401. })) {
  11402. // Returning as texture needs extra async steps
  11403. return;
  11404. }
  11405. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11406. };
  11407. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11408. // Create new RGBA data container.
  11409. var rgbaData;
  11410. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11411. rgbaData = new Float32Array(width * height * 4);
  11412. }
  11413. else {
  11414. rgbaData = new Uint32Array(width * height * 4);
  11415. }
  11416. // Convert each pixel.
  11417. for (var x = 0; x < width; x++) {
  11418. for (var y = 0; y < height; y++) {
  11419. var index = (y * width + x) * 3;
  11420. var newIndex = (y * width + x) * 4;
  11421. // Map Old Value to new value.
  11422. rgbaData[newIndex + 0] = rgbData[index + 0];
  11423. rgbaData[newIndex + 1] = rgbData[index + 1];
  11424. rgbaData[newIndex + 2] = rgbData[index + 2];
  11425. // Add fully opaque alpha channel.
  11426. rgbaData[newIndex + 3] = 1;
  11427. }
  11428. }
  11429. return rgbaData;
  11430. };
  11431. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11432. var gl = this._gl;
  11433. if (texture._framebuffer) {
  11434. gl.deleteFramebuffer(texture._framebuffer);
  11435. texture._framebuffer = null;
  11436. }
  11437. if (texture._depthStencilBuffer) {
  11438. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11439. texture._depthStencilBuffer = null;
  11440. }
  11441. if (texture._MSAAFramebuffer) {
  11442. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11443. texture._MSAAFramebuffer = null;
  11444. }
  11445. if (texture._MSAARenderBuffer) {
  11446. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11447. texture._MSAARenderBuffer = null;
  11448. }
  11449. };
  11450. Engine.prototype._releaseTexture = function (texture) {
  11451. var gl = this._gl;
  11452. this._releaseFramebufferObjects(texture);
  11453. gl.deleteTexture(texture._webGLTexture);
  11454. // Unbind channels
  11455. this.unbindAllTextures();
  11456. var index = this._internalTexturesCache.indexOf(texture);
  11457. if (index !== -1) {
  11458. this._internalTexturesCache.splice(index, 1);
  11459. }
  11460. // Integrated fixed lod samplers.
  11461. if (texture._lodTextureHigh) {
  11462. texture._lodTextureHigh.dispose();
  11463. }
  11464. if (texture._lodTextureMid) {
  11465. texture._lodTextureMid.dispose();
  11466. }
  11467. if (texture._lodTextureLow) {
  11468. texture._lodTextureLow.dispose();
  11469. }
  11470. };
  11471. Engine.prototype.setProgram = function (program) {
  11472. if (this._currentProgram !== program) {
  11473. this._gl.useProgram(program);
  11474. this._currentProgram = program;
  11475. }
  11476. };
  11477. Engine.prototype.bindSamplers = function (effect) {
  11478. this.setProgram(effect.getProgram());
  11479. var samplers = effect.getSamplers();
  11480. for (var index = 0; index < samplers.length; index++) {
  11481. var uniform = effect.getUniform(samplers[index]);
  11482. this._gl.uniform1i(uniform, index);
  11483. }
  11484. this._currentEffect = null;
  11485. };
  11486. Engine.prototype.activateTextureChannel = function (textureChannel) {
  11487. if (this._activeTextureChannel !== textureChannel) {
  11488. this._gl.activeTexture(textureChannel);
  11489. this._activeTextureChannel = textureChannel;
  11490. }
  11491. };
  11492. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11493. if (this._activeTexturesCache[this._activeTextureChannel] !== texture) {
  11494. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11495. this._activeTexturesCache[this._activeTextureChannel] = texture;
  11496. }
  11497. };
  11498. Engine.prototype._bindTexture = function (channel, texture) {
  11499. if (channel < 0) {
  11500. return;
  11501. }
  11502. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11503. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11504. };
  11505. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11506. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11507. };
  11508. Engine.prototype.unbindAllTextures = function () {
  11509. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11510. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11511. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11512. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11513. if (this.webGLVersion > 1) {
  11514. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11515. }
  11516. }
  11517. };
  11518. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11519. if (channel < 0) {
  11520. return;
  11521. }
  11522. if (this._setTexture(channel, texture)) {
  11523. this._gl.uniform1i(uniform, channel);
  11524. }
  11525. };
  11526. Engine.prototype._setTexture = function (channel, texture) {
  11527. // Not ready?
  11528. if (!texture) {
  11529. if (this._activeTexturesCache[channel] != null) {
  11530. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11531. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11532. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11533. if (this.webGLVersion > 1) {
  11534. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11535. }
  11536. }
  11537. return false;
  11538. }
  11539. // Video
  11540. var alreadyActivated = false;
  11541. if (texture.video) {
  11542. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11543. alreadyActivated = true;
  11544. texture.update();
  11545. }
  11546. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11547. texture.delayLoad();
  11548. return false;
  11549. }
  11550. var internalTexture;
  11551. if (texture.isReady()) {
  11552. internalTexture = texture.getInternalTexture();
  11553. }
  11554. else if (texture.isCube) {
  11555. internalTexture = this.emptyCubeTexture;
  11556. }
  11557. else if (texture.is3D) {
  11558. internalTexture = this.emptyTexture3D;
  11559. }
  11560. else {
  11561. internalTexture = this.emptyTexture;
  11562. }
  11563. if (!alreadyActivated) {
  11564. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11565. }
  11566. if (this._activeTexturesCache[this._activeTextureChannel] === internalTexture) {
  11567. return false;
  11568. }
  11569. if (internalTexture && internalTexture.is3D) {
  11570. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11571. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11572. internalTexture._cachedWrapU = texture.wrapU;
  11573. switch (texture.wrapU) {
  11574. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11575. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11576. break;
  11577. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11578. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11579. break;
  11580. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11581. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11582. break;
  11583. }
  11584. }
  11585. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11586. internalTexture._cachedWrapV = texture.wrapV;
  11587. switch (texture.wrapV) {
  11588. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11589. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11590. break;
  11591. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11592. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11593. break;
  11594. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11595. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11596. break;
  11597. }
  11598. }
  11599. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11600. internalTexture._cachedWrapR = texture.wrapR;
  11601. switch (texture.wrapV) {
  11602. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11603. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11604. break;
  11605. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11606. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11607. break;
  11608. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11609. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11610. break;
  11611. }
  11612. }
  11613. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11614. }
  11615. else if (internalTexture && internalTexture.isCube) {
  11616. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11617. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11618. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11619. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11620. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11621. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11622. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11623. }
  11624. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11625. }
  11626. else {
  11627. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11628. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11629. internalTexture._cachedWrapU = texture.wrapU;
  11630. switch (texture.wrapU) {
  11631. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11632. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11633. break;
  11634. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11635. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11636. break;
  11637. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11638. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11639. break;
  11640. }
  11641. }
  11642. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11643. internalTexture._cachedWrapV = texture.wrapV;
  11644. switch (texture.wrapV) {
  11645. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11646. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11647. break;
  11648. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11649. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11650. break;
  11651. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11652. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11653. break;
  11654. }
  11655. }
  11656. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11657. }
  11658. return true;
  11659. };
  11660. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11661. if (channel < 0 || !uniform) {
  11662. return;
  11663. }
  11664. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11665. this._textureUnits = new Int32Array(textures.length);
  11666. }
  11667. for (var i = 0; i < textures.length; i++) {
  11668. this._textureUnits[i] = channel + i;
  11669. }
  11670. this._gl.uniform1iv(uniform, this._textureUnits);
  11671. for (var index = 0; index < textures.length; index++) {
  11672. this._setTexture(channel + index, textures[index]);
  11673. }
  11674. };
  11675. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11676. var internalTexture = texture.getInternalTexture();
  11677. if (!internalTexture) {
  11678. return;
  11679. }
  11680. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11681. var value = texture.anisotropicFilteringLevel;
  11682. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11683. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11684. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11685. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11686. }
  11687. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11688. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11689. internalTexture._cachedAnisotropicFilteringLevel = value;
  11690. }
  11691. };
  11692. Engine.prototype.readPixels = function (x, y, width, height) {
  11693. var data = new Uint8Array(height * width * 4);
  11694. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11695. return data;
  11696. };
  11697. /**
  11698. * Add an externaly attached data from its key.
  11699. * This method call will fail and return false, if such key already exists.
  11700. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11701. * @param key the unique key that identifies the data
  11702. * @param data the data object to associate to the key for this Engine instance
  11703. * @return true if no such key were already present and the data was added successfully, false otherwise
  11704. */
  11705. Engine.prototype.addExternalData = function (key, data) {
  11706. if (!this._externalData) {
  11707. this._externalData = new BABYLON.StringDictionary();
  11708. }
  11709. return this._externalData.add(key, data);
  11710. };
  11711. /**
  11712. * Get an externaly attached data from its key
  11713. * @param key the unique key that identifies the data
  11714. * @return the associated data, if present (can be null), or undefined if not present
  11715. */
  11716. Engine.prototype.getExternalData = function (key) {
  11717. if (!this._externalData) {
  11718. this._externalData = new BABYLON.StringDictionary();
  11719. }
  11720. return this._externalData.get(key);
  11721. };
  11722. /**
  11723. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11724. * @param key the unique key that identifies the data
  11725. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11726. * @return the associated data, can be null if the factory returned null.
  11727. */
  11728. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11729. if (!this._externalData) {
  11730. this._externalData = new BABYLON.StringDictionary();
  11731. }
  11732. return this._externalData.getOrAddWithFactory(key, factory);
  11733. };
  11734. /**
  11735. * Remove an externaly attached data from the Engine instance
  11736. * @param key the unique key that identifies the data
  11737. * @return true if the data was successfully removed, false if it doesn't exist
  11738. */
  11739. Engine.prototype.removeExternalData = function (key) {
  11740. if (!this._externalData) {
  11741. this._externalData = new BABYLON.StringDictionary();
  11742. }
  11743. return this._externalData.remove(key);
  11744. };
  11745. Engine.prototype.unbindAllAttributes = function () {
  11746. if (this._mustWipeVertexAttributes) {
  11747. this._mustWipeVertexAttributes = false;
  11748. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11749. this._gl.disableVertexAttribArray(i);
  11750. this._vertexAttribArraysEnabled[i] = false;
  11751. this._currentBufferPointers[i].active = false;
  11752. }
  11753. return;
  11754. }
  11755. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11756. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11757. continue;
  11758. }
  11759. this._gl.disableVertexAttribArray(i);
  11760. this._vertexAttribArraysEnabled[i] = false;
  11761. this._currentBufferPointers[i].active = false;
  11762. }
  11763. };
  11764. Engine.prototype.releaseEffects = function () {
  11765. for (var name in this._compiledEffects) {
  11766. this._deleteProgram(this._compiledEffects[name]._program);
  11767. }
  11768. this._compiledEffects = {};
  11769. };
  11770. // Dispose
  11771. Engine.prototype.dispose = function () {
  11772. this.hideLoadingUI();
  11773. this.stopRenderLoop();
  11774. // Release postProcesses
  11775. while (this.postProcesses.length) {
  11776. this.postProcesses[0].dispose();
  11777. }
  11778. // Empty texture
  11779. if (this._emptyTexture) {
  11780. this._releaseTexture(this._emptyTexture);
  11781. this._emptyTexture = null;
  11782. }
  11783. if (this._emptyCubeTexture) {
  11784. this._releaseTexture(this._emptyCubeTexture);
  11785. this._emptyCubeTexture = null;
  11786. }
  11787. // Rescale PP
  11788. if (this._rescalePostProcess) {
  11789. this._rescalePostProcess.dispose();
  11790. }
  11791. // Release scenes
  11792. while (this.scenes.length) {
  11793. this.scenes[0].dispose();
  11794. }
  11795. // Release audio engine
  11796. if (Engine.audioEngine) {
  11797. Engine.audioEngine.dispose();
  11798. }
  11799. // Release effects
  11800. this.releaseEffects();
  11801. // Unbind
  11802. this.unbindAllAttributes();
  11803. if (this._dummyFramebuffer) {
  11804. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11805. }
  11806. //WebVR
  11807. this.disableVR();
  11808. // Events
  11809. window.removeEventListener("blur", this._onBlur);
  11810. window.removeEventListener("focus", this._onFocus);
  11811. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11812. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11813. if (this._renderingCanvas) {
  11814. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11815. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11816. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11817. if (!this._doNotHandleContextLost) {
  11818. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11819. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11820. }
  11821. }
  11822. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11823. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11824. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11825. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11826. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11827. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11828. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11829. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11830. if (this._onVrDisplayConnect) {
  11831. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11832. if (this._onVrDisplayDisconnect) {
  11833. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11834. }
  11835. if (this._onVrDisplayPresentChange) {
  11836. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11837. }
  11838. this._onVrDisplayConnect = null;
  11839. this._onVrDisplayDisconnect = null;
  11840. }
  11841. // Remove from Instances
  11842. var index = Engine.Instances.indexOf(this);
  11843. if (index >= 0) {
  11844. Engine.Instances.splice(index, 1);
  11845. }
  11846. this._workingCanvas = null;
  11847. this._workingContext = null;
  11848. this._currentBufferPointers = [];
  11849. this._renderingCanvas = null;
  11850. this._currentProgram = null;
  11851. this.onResizeObservable.clear();
  11852. this.onCanvasBlurObservable.clear();
  11853. this.onCanvasFocusObservable.clear();
  11854. this.onCanvasPointerOutObservable.clear();
  11855. this.onBeginFrameObservable.clear();
  11856. this.onEndFrameObservable.clear();
  11857. BABYLON.Effect.ResetCache();
  11858. };
  11859. // Loading screen
  11860. Engine.prototype.displayLoadingUI = function () {
  11861. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11862. return;
  11863. }
  11864. var loadingScreen = this.loadingScreen;
  11865. if (loadingScreen) {
  11866. loadingScreen.displayLoadingUI();
  11867. }
  11868. };
  11869. Engine.prototype.hideLoadingUI = function () {
  11870. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11871. return;
  11872. }
  11873. var loadingScreen = this.loadingScreen;
  11874. if (loadingScreen) {
  11875. loadingScreen.hideLoadingUI();
  11876. }
  11877. };
  11878. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11879. get: function () {
  11880. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11881. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11882. return this._loadingScreen;
  11883. },
  11884. set: function (loadingScreen) {
  11885. this._loadingScreen = loadingScreen;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11891. set: function (text) {
  11892. this.loadingScreen.loadingUIText = text;
  11893. },
  11894. enumerable: true,
  11895. configurable: true
  11896. });
  11897. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11898. set: function (color) {
  11899. this.loadingScreen.loadingUIBackgroundColor = color;
  11900. },
  11901. enumerable: true,
  11902. configurable: true
  11903. });
  11904. Engine.prototype.attachContextLostEvent = function (callback) {
  11905. if (this._renderingCanvas) {
  11906. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11907. }
  11908. };
  11909. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11910. if (this._renderingCanvas) {
  11911. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11912. }
  11913. };
  11914. Engine.prototype.getVertexShaderSource = function (program) {
  11915. var shaders = this._gl.getAttachedShaders(program);
  11916. if (!shaders) {
  11917. return null;
  11918. }
  11919. return this._gl.getShaderSource(shaders[0]);
  11920. };
  11921. Engine.prototype.getFragmentShaderSource = function (program) {
  11922. var shaders = this._gl.getAttachedShaders(program);
  11923. if (!shaders) {
  11924. return null;
  11925. }
  11926. return this._gl.getShaderSource(shaders[1]);
  11927. };
  11928. Engine.prototype.getError = function () {
  11929. return this._gl.getError();
  11930. };
  11931. // FPS
  11932. Engine.prototype.getFps = function () {
  11933. return this._fps;
  11934. };
  11935. Engine.prototype.getDeltaTime = function () {
  11936. return this._deltaTime;
  11937. };
  11938. Engine.prototype._measureFps = function () {
  11939. this._performanceMonitor.sampleFrame();
  11940. this._fps = this._performanceMonitor.averageFPS;
  11941. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11942. };
  11943. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11944. if (faceIndex === void 0) { faceIndex = -1; }
  11945. var gl = this._gl;
  11946. if (!this._dummyFramebuffer) {
  11947. var dummy = gl.createFramebuffer();
  11948. if (!dummy) {
  11949. throw new Error("Unable to create dummy framebuffer");
  11950. }
  11951. this._dummyFramebuffer = dummy;
  11952. }
  11953. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11954. if (faceIndex > -1) {
  11955. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11956. }
  11957. else {
  11958. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11959. }
  11960. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11961. var buffer;
  11962. switch (readType) {
  11963. case gl.UNSIGNED_BYTE:
  11964. buffer = new Uint8Array(4 * width * height);
  11965. readType = gl.UNSIGNED_BYTE;
  11966. break;
  11967. default:
  11968. buffer = new Float32Array(4 * width * height);
  11969. readType = gl.FLOAT;
  11970. break;
  11971. }
  11972. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11973. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11974. return buffer;
  11975. };
  11976. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11977. if (this._webGLVersion > 1) {
  11978. return this._caps.colorBufferFloat;
  11979. }
  11980. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11981. };
  11982. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11983. if (this._webGLVersion > 1) {
  11984. return this._caps.colorBufferFloat;
  11985. }
  11986. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11987. };
  11988. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11989. Engine.prototype._canRenderToFramebuffer = function (type) {
  11990. var gl = this._gl;
  11991. //clear existing errors
  11992. while (gl.getError() !== gl.NO_ERROR) { }
  11993. var successful = true;
  11994. var texture = gl.createTexture();
  11995. gl.bindTexture(gl.TEXTURE_2D, texture);
  11996. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11999. var fb = gl.createFramebuffer();
  12000. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  12001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  12002. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12003. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12004. successful = successful && (gl.getError() === gl.NO_ERROR);
  12005. //try render by clearing frame buffer's color buffer
  12006. if (successful) {
  12007. gl.clear(gl.COLOR_BUFFER_BIT);
  12008. successful = successful && (gl.getError() === gl.NO_ERROR);
  12009. }
  12010. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12011. if (successful) {
  12012. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12013. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12014. var readFormat = gl.RGBA;
  12015. var readType = gl.UNSIGNED_BYTE;
  12016. var buffer = new Uint8Array(4);
  12017. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12018. successful = successful && (gl.getError() === gl.NO_ERROR);
  12019. }
  12020. //clean up
  12021. gl.deleteTexture(texture);
  12022. gl.deleteFramebuffer(fb);
  12023. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12024. //clear accumulated errors
  12025. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12026. return successful;
  12027. };
  12028. Engine.prototype._getWebGLTextureType = function (type) {
  12029. if (type === Engine.TEXTURETYPE_FLOAT) {
  12030. return this._gl.FLOAT;
  12031. }
  12032. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12033. // Add Half Float Constant.
  12034. return this._gl.HALF_FLOAT_OES;
  12035. }
  12036. return this._gl.UNSIGNED_BYTE;
  12037. };
  12038. ;
  12039. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12040. if (this._webGLVersion === 1) {
  12041. return this._gl.RGBA;
  12042. }
  12043. if (type === Engine.TEXTURETYPE_FLOAT) {
  12044. return this._gl.RGBA32F;
  12045. }
  12046. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12047. return this._gl.RGBA16F;
  12048. }
  12049. return this._gl.RGBA;
  12050. };
  12051. ;
  12052. Engine.prototype.createQuery = function () {
  12053. return this._gl.createQuery();
  12054. };
  12055. Engine.prototype.deleteQuery = function (query) {
  12056. this._gl.deleteQuery(query);
  12057. return this;
  12058. };
  12059. Engine.prototype.isQueryResultAvailable = function (query) {
  12060. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12061. };
  12062. Engine.prototype.getQueryResult = function (query) {
  12063. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12064. };
  12065. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12066. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12067. this._gl.beginQuery(glAlgorithm, query);
  12068. return this;
  12069. };
  12070. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12071. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12072. this._gl.endQuery(glAlgorithm);
  12073. return this;
  12074. };
  12075. /* Time queries */
  12076. Engine.prototype._createTimeQuery = function () {
  12077. var timerQuery = this._caps.timerQuery;
  12078. if (timerQuery.createQueryEXT) {
  12079. return timerQuery.createQueryEXT();
  12080. }
  12081. return this.createQuery();
  12082. };
  12083. Engine.prototype._deleteTimeQuery = function (query) {
  12084. var timerQuery = this._caps.timerQuery;
  12085. if (timerQuery.deleteQueryEXT) {
  12086. timerQuery.deleteQueryEXT(query);
  12087. return;
  12088. }
  12089. this.deleteQuery(query);
  12090. };
  12091. Engine.prototype._getTimeQueryResult = function (query) {
  12092. var timerQuery = this._caps.timerQuery;
  12093. if (timerQuery.getQueryObjectEXT) {
  12094. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12095. }
  12096. return this.getQueryResult(query);
  12097. };
  12098. Engine.prototype._getTimeQueryAvailability = function (query) {
  12099. var timerQuery = this._caps.timerQuery;
  12100. if (timerQuery.getQueryObjectEXT) {
  12101. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12102. }
  12103. return this.isQueryResultAvailable(query);
  12104. };
  12105. Engine.prototype.startTimeQuery = function () {
  12106. var timerQuery = this._caps.timerQuery;
  12107. if (!timerQuery) {
  12108. return null;
  12109. }
  12110. var token = new BABYLON._TimeToken();
  12111. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12112. if (this._caps.canUseTimestampForTimerQuery) {
  12113. token._startTimeQuery = this._createTimeQuery();
  12114. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12115. }
  12116. else {
  12117. if (this._currentNonTimestampToken) {
  12118. return this._currentNonTimestampToken;
  12119. }
  12120. token._timeElapsedQuery = this._createTimeQuery();
  12121. if (timerQuery.beginQueryEXT) {
  12122. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12123. }
  12124. else {
  12125. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12126. }
  12127. this._currentNonTimestampToken = token;
  12128. }
  12129. return token;
  12130. };
  12131. Engine.prototype.endTimeQuery = function (token) {
  12132. var timerQuery = this._caps.timerQuery;
  12133. if (!timerQuery || !token) {
  12134. return -1;
  12135. }
  12136. if (this._caps.canUseTimestampForTimerQuery) {
  12137. if (!token._startTimeQuery) {
  12138. return -1;
  12139. }
  12140. if (!token._endTimeQuery) {
  12141. token._endTimeQuery = this._createTimeQuery();
  12142. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12143. }
  12144. }
  12145. else if (!token._timeElapsedQueryEnded) {
  12146. if (!token._timeElapsedQuery) {
  12147. return -1;
  12148. }
  12149. if (timerQuery.endQueryEXT) {
  12150. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12151. }
  12152. else {
  12153. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12154. }
  12155. token._timeElapsedQueryEnded = true;
  12156. }
  12157. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12158. var available = false;
  12159. if (token._endTimeQuery) {
  12160. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12161. }
  12162. else if (token._timeElapsedQuery) {
  12163. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12164. }
  12165. if (available && !disjoint) {
  12166. var result = 0;
  12167. if (this._caps.canUseTimestampForTimerQuery) {
  12168. if (!token._startTimeQuery || !token._endTimeQuery) {
  12169. return -1;
  12170. }
  12171. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12172. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12173. result = timeEnd - timeStart;
  12174. this._deleteTimeQuery(token._startTimeQuery);
  12175. this._deleteTimeQuery(token._endTimeQuery);
  12176. token._startTimeQuery = null;
  12177. token._endTimeQuery = null;
  12178. }
  12179. else {
  12180. if (!token._timeElapsedQuery) {
  12181. return -1;
  12182. }
  12183. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12184. this._deleteTimeQuery(token._timeElapsedQuery);
  12185. token._timeElapsedQuery = null;
  12186. token._timeElapsedQueryEnded = false;
  12187. this._currentNonTimestampToken = null;
  12188. }
  12189. return result;
  12190. }
  12191. return -1;
  12192. };
  12193. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12194. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12195. };
  12196. // Transform feedback
  12197. Engine.prototype.createTransformFeedback = function () {
  12198. return this._gl.createTransformFeedback();
  12199. };
  12200. Engine.prototype.deleteTransformFeedback = function (value) {
  12201. this._gl.deleteTransformFeedback(value);
  12202. };
  12203. Engine.prototype.bindTransformFeedback = function (value) {
  12204. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12205. };
  12206. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12207. if (usePoints === void 0) { usePoints = true; }
  12208. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12209. };
  12210. Engine.prototype.endTransformFeedback = function () {
  12211. this._gl.endTransformFeedback();
  12212. };
  12213. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12214. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12215. };
  12216. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12217. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12218. };
  12219. // Statics
  12220. Engine.isSupported = function () {
  12221. try {
  12222. var tempcanvas = document.createElement("canvas");
  12223. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12224. return gl != null && !!window.WebGLRenderingContext;
  12225. }
  12226. catch (e) {
  12227. return false;
  12228. }
  12229. };
  12230. Engine.Instances = new Array();
  12231. // Const statics
  12232. Engine._ALPHA_DISABLE = 0;
  12233. Engine._ALPHA_ADD = 1;
  12234. Engine._ALPHA_COMBINE = 2;
  12235. Engine._ALPHA_SUBTRACT = 3;
  12236. Engine._ALPHA_MULTIPLY = 4;
  12237. Engine._ALPHA_MAXIMIZED = 5;
  12238. Engine._ALPHA_ONEONE = 6;
  12239. Engine._ALPHA_PREMULTIPLIED = 7;
  12240. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12241. Engine._ALPHA_INTERPOLATE = 9;
  12242. Engine._ALPHA_SCREENMODE = 10;
  12243. Engine._DELAYLOADSTATE_NONE = 0;
  12244. Engine._DELAYLOADSTATE_LOADED = 1;
  12245. Engine._DELAYLOADSTATE_LOADING = 2;
  12246. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12247. Engine._TEXTUREFORMAT_ALPHA = 0;
  12248. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12249. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12250. Engine._TEXTUREFORMAT_RGB = 4;
  12251. Engine._TEXTUREFORMAT_RGBA = 5;
  12252. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12253. Engine._TEXTURETYPE_FLOAT = 1;
  12254. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12255. // Depht or Stencil test Constants.
  12256. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12257. 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.
  12258. 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.
  12259. 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.
  12260. 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.
  12261. 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.
  12262. 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.
  12263. 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.
  12264. // Stencil Actions Constants.
  12265. Engine._KEEP = 0x1E00;
  12266. Engine._REPLACE = 0x1E01;
  12267. Engine._INCR = 0x1E02;
  12268. Engine._DECR = 0x1E03;
  12269. Engine._INVERT = 0x150A;
  12270. Engine._INCR_WRAP = 0x8507;
  12271. Engine._DECR_WRAP = 0x8508;
  12272. // Texture rescaling mode
  12273. Engine._SCALEMODE_FLOOR = 1;
  12274. Engine._SCALEMODE_NEAREST = 2;
  12275. Engine._SCALEMODE_CEILING = 3;
  12276. // Updatable statics so stick with vars here
  12277. Engine.CollisionsEpsilon = 0.001;
  12278. Engine.CodeRepository = "src/";
  12279. Engine.ShadersRepository = "src/Shaders/";
  12280. return Engine;
  12281. }());
  12282. BABYLON.Engine = Engine;
  12283. })(BABYLON || (BABYLON = {}));
  12284. //# sourceMappingURL=babylon.engine.js.map
  12285. var BABYLON;
  12286. (function (BABYLON) {
  12287. /**
  12288. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12289. */
  12290. var Node = /** @class */ (function () {
  12291. /**
  12292. * @constructor
  12293. * @param {string} name - the name and id to be given to this node
  12294. * @param {BABYLON.Scene} the scene this node will be added to
  12295. */
  12296. function Node(name, scene) {
  12297. if (scene === void 0) { scene = null; }
  12298. this.state = "";
  12299. this.metadata = null;
  12300. this.doNotSerialize = false;
  12301. this.animations = new Array();
  12302. this._ranges = {};
  12303. this._isEnabled = true;
  12304. this._isReady = true;
  12305. this._currentRenderId = -1;
  12306. this._parentRenderId = -1;
  12307. /**
  12308. * An event triggered when the mesh is disposed.
  12309. * @type {BABYLON.Observable}
  12310. */
  12311. this.onDisposeObservable = new BABYLON.Observable();
  12312. // Behaviors
  12313. this._behaviors = new Array();
  12314. this.name = name;
  12315. this.id = name;
  12316. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12317. this.uniqueId = this._scene.getUniqueId();
  12318. this._initCache();
  12319. }
  12320. Object.defineProperty(Node.prototype, "parent", {
  12321. get: function () {
  12322. return this._parentNode;
  12323. },
  12324. set: function (parent) {
  12325. if (this._parentNode === parent) {
  12326. return;
  12327. }
  12328. if (this._parentNode) {
  12329. var index = this._parentNode._children.indexOf(this);
  12330. if (index !== -1) {
  12331. this._parentNode._children.splice(index, 1);
  12332. }
  12333. }
  12334. this._parentNode = parent;
  12335. if (this._parentNode) {
  12336. if (!this._parentNode._children) {
  12337. this._parentNode._children = new Array();
  12338. }
  12339. this._parentNode._children.push(this);
  12340. }
  12341. },
  12342. enumerable: true,
  12343. configurable: true
  12344. });
  12345. Node.prototype.getClassName = function () {
  12346. return "Node";
  12347. };
  12348. Object.defineProperty(Node.prototype, "onDispose", {
  12349. set: function (callback) {
  12350. if (this._onDisposeObserver) {
  12351. this.onDisposeObservable.remove(this._onDisposeObserver);
  12352. }
  12353. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12354. },
  12355. enumerable: true,
  12356. configurable: true
  12357. });
  12358. Node.prototype.getScene = function () {
  12359. return this._scene;
  12360. };
  12361. Node.prototype.getEngine = function () {
  12362. return this._scene.getEngine();
  12363. };
  12364. Node.prototype.addBehavior = function (behavior) {
  12365. var _this = this;
  12366. var index = this._behaviors.indexOf(behavior);
  12367. if (index !== -1) {
  12368. return this;
  12369. }
  12370. behavior.init();
  12371. if (this._scene.isLoading) {
  12372. // We defer the attach when the scene will be loaded
  12373. var observer = this._scene.onDataLoadedObservable.add(function () {
  12374. behavior.attach(_this);
  12375. _this._scene.onDataLoadedObservable.remove(observer);
  12376. });
  12377. }
  12378. else {
  12379. behavior.attach(this);
  12380. }
  12381. this._behaviors.push(behavior);
  12382. return this;
  12383. };
  12384. Node.prototype.removeBehavior = function (behavior) {
  12385. var index = this._behaviors.indexOf(behavior);
  12386. if (index === -1) {
  12387. return this;
  12388. }
  12389. this._behaviors[index].detach();
  12390. this._behaviors.splice(index, 1);
  12391. return this;
  12392. };
  12393. Object.defineProperty(Node.prototype, "behaviors", {
  12394. get: function () {
  12395. return this._behaviors;
  12396. },
  12397. enumerable: true,
  12398. configurable: true
  12399. });
  12400. Node.prototype.getBehaviorByName = function (name) {
  12401. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12402. var behavior = _a[_i];
  12403. if (behavior.name === name) {
  12404. return behavior;
  12405. }
  12406. }
  12407. return null;
  12408. };
  12409. // override it in derived class
  12410. Node.prototype.getWorldMatrix = function () {
  12411. return BABYLON.Matrix.Identity();
  12412. };
  12413. // override it in derived class if you add new variables to the cache
  12414. // and call the parent class method
  12415. Node.prototype._initCache = function () {
  12416. this._cache = {};
  12417. this._cache.parent = undefined;
  12418. };
  12419. Node.prototype.updateCache = function (force) {
  12420. if (!force && this.isSynchronized())
  12421. return;
  12422. this._cache.parent = this.parent;
  12423. this._updateCache();
  12424. };
  12425. // override it in derived class if you add new variables to the cache
  12426. // and call the parent class method if !ignoreParentClass
  12427. Node.prototype._updateCache = function (ignoreParentClass) {
  12428. };
  12429. // override it in derived class if you add new variables to the cache
  12430. Node.prototype._isSynchronized = function () {
  12431. return true;
  12432. };
  12433. Node.prototype._markSyncedWithParent = function () {
  12434. if (this.parent) {
  12435. this._parentRenderId = this.parent._currentRenderId;
  12436. }
  12437. };
  12438. Node.prototype.isSynchronizedWithParent = function () {
  12439. if (!this.parent) {
  12440. return true;
  12441. }
  12442. if (this._parentRenderId !== this.parent._currentRenderId) {
  12443. return false;
  12444. }
  12445. return this.parent.isSynchronized();
  12446. };
  12447. Node.prototype.isSynchronized = function (updateCache) {
  12448. var check = this.hasNewParent();
  12449. check = check || !this.isSynchronizedWithParent();
  12450. check = check || !this._isSynchronized();
  12451. if (updateCache)
  12452. this.updateCache(true);
  12453. return !check;
  12454. };
  12455. Node.prototype.hasNewParent = function (update) {
  12456. if (this._cache.parent === this.parent)
  12457. return false;
  12458. if (update)
  12459. this._cache.parent = this.parent;
  12460. return true;
  12461. };
  12462. /**
  12463. * Is this node ready to be used/rendered
  12464. * @return {boolean} is it ready
  12465. */
  12466. Node.prototype.isReady = function () {
  12467. return this._isReady;
  12468. };
  12469. /**
  12470. * Is this node enabled.
  12471. * If the node has a parent and is enabled, the parent will be inspected as well.
  12472. * @return {boolean} whether this node (and its parent) is enabled.
  12473. * @see setEnabled
  12474. */
  12475. Node.prototype.isEnabled = function () {
  12476. if (!this._isEnabled) {
  12477. return false;
  12478. }
  12479. if (this.parent) {
  12480. return this.parent.isEnabled();
  12481. }
  12482. return true;
  12483. };
  12484. /**
  12485. * Set the enabled state of this node.
  12486. * @param {boolean} value - the new enabled state
  12487. * @see isEnabled
  12488. */
  12489. Node.prototype.setEnabled = function (value) {
  12490. this._isEnabled = value;
  12491. };
  12492. /**
  12493. * Is this node a descendant of the given node.
  12494. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12495. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12496. * @see parent
  12497. */
  12498. Node.prototype.isDescendantOf = function (ancestor) {
  12499. if (this.parent) {
  12500. if (this.parent === ancestor) {
  12501. return true;
  12502. }
  12503. return this.parent.isDescendantOf(ancestor);
  12504. }
  12505. return false;
  12506. };
  12507. /**
  12508. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12509. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12510. * @param {boolean} directDescendantsOnly 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.
  12511. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12512. */
  12513. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12514. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12515. if (!this._children) {
  12516. return;
  12517. }
  12518. for (var index = 0; index < this._children.length; index++) {
  12519. var item = this._children[index];
  12520. if (!predicate || predicate(item)) {
  12521. results.push(item);
  12522. }
  12523. if (!directDescendantsOnly) {
  12524. item._getDescendants(results, false, predicate);
  12525. }
  12526. }
  12527. };
  12528. /**
  12529. * Will return all nodes that have this node as ascendant.
  12530. * @param {boolean} directDescendantsOnly 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.
  12531. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12532. * @return {BABYLON.Node[]} all children nodes of all types.
  12533. */
  12534. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12535. var results = new Array();
  12536. this._getDescendants(results, directDescendantsOnly, predicate);
  12537. return results;
  12538. };
  12539. /**
  12540. * Get all child-meshes of this node.
  12541. */
  12542. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12543. var results = [];
  12544. this._getDescendants(results, directDecendantsOnly, function (node) {
  12545. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12546. });
  12547. return results;
  12548. };
  12549. /**
  12550. * Get all direct children of this node.
  12551. */
  12552. Node.prototype.getChildren = function (predicate) {
  12553. return this.getDescendants(true, predicate);
  12554. };
  12555. Node.prototype._setReady = function (state) {
  12556. if (state === this._isReady) {
  12557. return;
  12558. }
  12559. if (!state) {
  12560. this._isReady = false;
  12561. return;
  12562. }
  12563. this._isReady = true;
  12564. if (this.onReady) {
  12565. this.onReady(this);
  12566. }
  12567. };
  12568. Node.prototype.getAnimationByName = function (name) {
  12569. for (var i = 0; i < this.animations.length; i++) {
  12570. var animation = this.animations[i];
  12571. if (animation.name === name) {
  12572. return animation;
  12573. }
  12574. }
  12575. return null;
  12576. };
  12577. Node.prototype.createAnimationRange = function (name, from, to) {
  12578. // check name not already in use
  12579. if (!this._ranges[name]) {
  12580. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12581. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12582. if (this.animations[i]) {
  12583. this.animations[i].createRange(name, from, to);
  12584. }
  12585. }
  12586. }
  12587. };
  12588. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12589. if (deleteFrames === void 0) { deleteFrames = true; }
  12590. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12591. if (this.animations[i]) {
  12592. this.animations[i].deleteRange(name, deleteFrames);
  12593. }
  12594. }
  12595. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12596. };
  12597. Node.prototype.getAnimationRange = function (name) {
  12598. return this._ranges[name];
  12599. };
  12600. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12601. var range = this.getAnimationRange(name);
  12602. if (!range) {
  12603. return;
  12604. }
  12605. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12606. };
  12607. Node.prototype.serializeAnimationRanges = function () {
  12608. var serializationRanges = [];
  12609. for (var name in this._ranges) {
  12610. var localRange = this._ranges[name];
  12611. if (!localRange) {
  12612. continue;
  12613. }
  12614. var range = {};
  12615. range.name = name;
  12616. range.from = localRange.from;
  12617. range.to = localRange.to;
  12618. serializationRanges.push(range);
  12619. }
  12620. return serializationRanges;
  12621. };
  12622. Node.prototype.dispose = function () {
  12623. this.parent = null;
  12624. // Callback
  12625. this.onDisposeObservable.notifyObservers(this);
  12626. this.onDisposeObservable.clear();
  12627. // Behaviors
  12628. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12629. var behavior = _a[_i];
  12630. behavior.detach();
  12631. }
  12632. this._behaviors = [];
  12633. };
  12634. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12635. if (parsedNode.ranges) {
  12636. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12637. var data = parsedNode.ranges[index];
  12638. node.createAnimationRange(data.name, data.from, data.to);
  12639. }
  12640. }
  12641. };
  12642. __decorate([
  12643. BABYLON.serialize()
  12644. ], Node.prototype, "name", void 0);
  12645. __decorate([
  12646. BABYLON.serialize()
  12647. ], Node.prototype, "id", void 0);
  12648. __decorate([
  12649. BABYLON.serialize()
  12650. ], Node.prototype, "uniqueId", void 0);
  12651. __decorate([
  12652. BABYLON.serialize()
  12653. ], Node.prototype, "state", void 0);
  12654. __decorate([
  12655. BABYLON.serialize()
  12656. ], Node.prototype, "metadata", void 0);
  12657. return Node;
  12658. }());
  12659. BABYLON.Node = Node;
  12660. })(BABYLON || (BABYLON = {}));
  12661. //# sourceMappingURL=babylon.node.js.map
  12662. var BABYLON;
  12663. (function (BABYLON) {
  12664. var BoundingSphere = /** @class */ (function () {
  12665. function BoundingSphere(minimum, maximum) {
  12666. this.minimum = minimum;
  12667. this.maximum = maximum;
  12668. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12669. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12670. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12671. this.radius = distance * 0.5;
  12672. this.centerWorld = BABYLON.Vector3.Zero();
  12673. this._update(BABYLON.Matrix.Identity());
  12674. }
  12675. // Methods
  12676. BoundingSphere.prototype._update = function (world) {
  12677. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12678. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12679. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12680. };
  12681. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12682. for (var i = 0; i < 6; i++) {
  12683. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12684. return false;
  12685. }
  12686. return true;
  12687. };
  12688. BoundingSphere.prototype.intersectsPoint = function (point) {
  12689. var x = this.centerWorld.x - point.x;
  12690. var y = this.centerWorld.y - point.y;
  12691. var z = this.centerWorld.z - point.z;
  12692. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12693. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12694. return false;
  12695. return true;
  12696. };
  12697. // Statics
  12698. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12699. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12700. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12701. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12702. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12703. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12704. return false;
  12705. return true;
  12706. };
  12707. return BoundingSphere;
  12708. }());
  12709. BABYLON.BoundingSphere = BoundingSphere;
  12710. })(BABYLON || (BABYLON = {}));
  12711. //# sourceMappingURL=babylon.boundingSphere.js.map
  12712. var BABYLON;
  12713. (function (BABYLON) {
  12714. var BoundingBox = /** @class */ (function () {
  12715. function BoundingBox(minimum, maximum) {
  12716. this.minimum = minimum;
  12717. this.maximum = maximum;
  12718. this.vectors = new Array();
  12719. this.vectorsWorld = new Array();
  12720. // Bounding vectors
  12721. this.vectors.push(this.minimum.clone());
  12722. this.vectors.push(this.maximum.clone());
  12723. this.vectors.push(this.minimum.clone());
  12724. this.vectors[2].x = this.maximum.x;
  12725. this.vectors.push(this.minimum.clone());
  12726. this.vectors[3].y = this.maximum.y;
  12727. this.vectors.push(this.minimum.clone());
  12728. this.vectors[4].z = this.maximum.z;
  12729. this.vectors.push(this.maximum.clone());
  12730. this.vectors[5].z = this.minimum.z;
  12731. this.vectors.push(this.maximum.clone());
  12732. this.vectors[6].x = this.minimum.x;
  12733. this.vectors.push(this.maximum.clone());
  12734. this.vectors[7].y = this.minimum.y;
  12735. // OBB
  12736. this.center = this.maximum.add(this.minimum).scale(0.5);
  12737. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12738. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12739. // World
  12740. for (var index = 0; index < this.vectors.length; index++) {
  12741. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12742. }
  12743. this.minimumWorld = BABYLON.Vector3.Zero();
  12744. this.maximumWorld = BABYLON.Vector3.Zero();
  12745. this.centerWorld = BABYLON.Vector3.Zero();
  12746. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12747. this._update(BABYLON.Matrix.Identity());
  12748. }
  12749. // Methods
  12750. BoundingBox.prototype.getWorldMatrix = function () {
  12751. return this._worldMatrix;
  12752. };
  12753. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12754. this._worldMatrix.copyFrom(matrix);
  12755. return this;
  12756. };
  12757. BoundingBox.prototype._update = function (world) {
  12758. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12759. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12760. for (var index = 0; index < this.vectors.length; index++) {
  12761. var v = this.vectorsWorld[index];
  12762. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12763. if (v.x < this.minimumWorld.x)
  12764. this.minimumWorld.x = v.x;
  12765. if (v.y < this.minimumWorld.y)
  12766. this.minimumWorld.y = v.y;
  12767. if (v.z < this.minimumWorld.z)
  12768. this.minimumWorld.z = v.z;
  12769. if (v.x > this.maximumWorld.x)
  12770. this.maximumWorld.x = v.x;
  12771. if (v.y > this.maximumWorld.y)
  12772. this.maximumWorld.y = v.y;
  12773. if (v.z > this.maximumWorld.z)
  12774. this.maximumWorld.z = v.z;
  12775. }
  12776. // Extend
  12777. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12778. this.extendSizeWorld.scaleInPlace(0.5);
  12779. // OBB
  12780. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12781. this.centerWorld.scaleInPlace(0.5);
  12782. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12783. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12784. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12785. this._worldMatrix = world;
  12786. };
  12787. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12788. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12789. };
  12790. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12791. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12792. };
  12793. BoundingBox.prototype.intersectsPoint = function (point) {
  12794. var delta = -BABYLON.Epsilon;
  12795. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12796. return false;
  12797. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12798. return false;
  12799. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12800. return false;
  12801. return true;
  12802. };
  12803. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12804. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12805. };
  12806. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12807. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12808. return false;
  12809. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12810. return false;
  12811. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12812. return false;
  12813. return true;
  12814. };
  12815. // Statics
  12816. BoundingBox.Intersects = function (box0, box1) {
  12817. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12818. return false;
  12819. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12820. return false;
  12821. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12822. return false;
  12823. return true;
  12824. };
  12825. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12826. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12827. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12828. return (num <= (sphereRadius * sphereRadius));
  12829. };
  12830. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12831. for (var p = 0; p < 6; p++) {
  12832. for (var i = 0; i < 8; i++) {
  12833. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12834. return false;
  12835. }
  12836. }
  12837. }
  12838. return true;
  12839. };
  12840. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12841. for (var p = 0; p < 6; p++) {
  12842. var inCount = 8;
  12843. for (var i = 0; i < 8; i++) {
  12844. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12845. --inCount;
  12846. }
  12847. else {
  12848. break;
  12849. }
  12850. }
  12851. if (inCount === 0)
  12852. return false;
  12853. }
  12854. return true;
  12855. };
  12856. return BoundingBox;
  12857. }());
  12858. BABYLON.BoundingBox = BoundingBox;
  12859. })(BABYLON || (BABYLON = {}));
  12860. //# sourceMappingURL=babylon.boundingBox.js.map
  12861. var BABYLON;
  12862. (function (BABYLON) {
  12863. var computeBoxExtents = function (axis, box) {
  12864. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12865. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12866. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12867. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12868. var r = r0 + r1 + r2;
  12869. return {
  12870. min: p - r,
  12871. max: p + r
  12872. };
  12873. };
  12874. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12875. var axisOverlap = function (axis, box0, box1) {
  12876. var result0 = computeBoxExtents(axis, box0);
  12877. var result1 = computeBoxExtents(axis, box1);
  12878. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12879. };
  12880. var BoundingInfo = /** @class */ (function () {
  12881. function BoundingInfo(minimum, maximum) {
  12882. this.minimum = minimum;
  12883. this.maximum = maximum;
  12884. this._isLocked = false;
  12885. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12886. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12887. }
  12888. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12889. get: function () {
  12890. return this._isLocked;
  12891. },
  12892. set: function (value) {
  12893. this._isLocked = value;
  12894. },
  12895. enumerable: true,
  12896. configurable: true
  12897. });
  12898. // Methods
  12899. BoundingInfo.prototype.update = function (world) {
  12900. if (this._isLocked) {
  12901. return;
  12902. }
  12903. this.boundingBox._update(world);
  12904. this.boundingSphere._update(world);
  12905. };
  12906. /**
  12907. * Recreate the bounding info to be centered around a specific point given a specific extend.
  12908. * @param center New center of the bounding info
  12909. * @param extend New extend of the bounding info
  12910. */
  12911. BoundingInfo.prototype.centerOn = function (center, extend) {
  12912. this.minimum = center.subtract(extend);
  12913. this.maximum = center.add(extend);
  12914. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  12915. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  12916. return this;
  12917. };
  12918. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12919. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12920. return false;
  12921. return this.boundingBox.isInFrustum(frustumPlanes);
  12922. };
  12923. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12924. /**
  12925. * Gets the world distance between the min and max points of the bounding box
  12926. */
  12927. get: function () {
  12928. var boundingBox = this.boundingBox;
  12929. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12930. return size.length();
  12931. },
  12932. enumerable: true,
  12933. configurable: true
  12934. });
  12935. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12936. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12937. };
  12938. BoundingInfo.prototype._checkCollision = function (collider) {
  12939. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12940. };
  12941. BoundingInfo.prototype.intersectsPoint = function (point) {
  12942. if (!this.boundingSphere.centerWorld) {
  12943. return false;
  12944. }
  12945. if (!this.boundingSphere.intersectsPoint(point)) {
  12946. return false;
  12947. }
  12948. if (!this.boundingBox.intersectsPoint(point)) {
  12949. return false;
  12950. }
  12951. return true;
  12952. };
  12953. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12954. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12955. return false;
  12956. }
  12957. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12958. return false;
  12959. }
  12960. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12961. return false;
  12962. }
  12963. if (!precise) {
  12964. return true;
  12965. }
  12966. var box0 = this.boundingBox;
  12967. var box1 = boundingInfo.boundingBox;
  12968. if (!axisOverlap(box0.directions[0], box0, box1))
  12969. return false;
  12970. if (!axisOverlap(box0.directions[1], box0, box1))
  12971. return false;
  12972. if (!axisOverlap(box0.directions[2], box0, box1))
  12973. return false;
  12974. if (!axisOverlap(box1.directions[0], box0, box1))
  12975. return false;
  12976. if (!axisOverlap(box1.directions[1], box0, box1))
  12977. return false;
  12978. if (!axisOverlap(box1.directions[2], box0, box1))
  12979. return false;
  12980. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12981. return false;
  12982. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12983. return false;
  12984. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12985. return false;
  12986. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12987. return false;
  12988. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12989. return false;
  12990. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12991. return false;
  12992. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12993. return false;
  12994. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12995. return false;
  12996. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12997. return false;
  12998. return true;
  12999. };
  13000. return BoundingInfo;
  13001. }());
  13002. BABYLON.BoundingInfo = BoundingInfo;
  13003. })(BABYLON || (BABYLON = {}));
  13004. //# sourceMappingURL=babylon.boundingInfo.js.map
  13005. var BABYLON;
  13006. (function (BABYLON) {
  13007. var AbstractMesh = /** @class */ (function (_super) {
  13008. __extends(AbstractMesh, _super);
  13009. // Constructor
  13010. function AbstractMesh(name, scene) {
  13011. if (scene === void 0) { scene = null; }
  13012. var _this = _super.call(this, name, scene) || this;
  13013. _this._facetNb = 0; // facet number
  13014. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  13015. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  13016. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  13017. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  13018. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  13019. _this._subDiv = {
  13020. max: 1,
  13021. X: 1,
  13022. Y: 1,
  13023. Z: 1
  13024. };
  13025. // Normal matrix
  13026. _this._nonUniformScaling = false;
  13027. // Events
  13028. /**
  13029. * An event triggered when this mesh collides with another one
  13030. * @type {BABYLON.Observable}
  13031. */
  13032. _this.onCollideObservable = new BABYLON.Observable();
  13033. /**
  13034. * An event triggered when the collision's position changes
  13035. * @type {BABYLON.Observable}
  13036. */
  13037. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  13038. /**
  13039. * An event triggered after the world matrix is updated
  13040. * @type {BABYLON.Observable}
  13041. */
  13042. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13043. /**
  13044. * An event triggered when material is changed
  13045. * @type {BABYLON.Observable}
  13046. */
  13047. _this.onMaterialChangedObservable = new BABYLON.Observable();
  13048. // Properties
  13049. _this.definedFacingForward = true; // orientation for POV movement & rotation
  13050. _this.position = BABYLON.Vector3.Zero();
  13051. /**
  13052. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  13053. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  13054. * or
  13055. * 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.
  13056. * for more info check WebGl documentations
  13057. */
  13058. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  13059. /**
  13060. * 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:
  13061. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  13062. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  13063. * 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.
  13064. */
  13065. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  13066. /**
  13067. * 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.
  13068. * The default value is -1 which means don't break the query and wait till the result.
  13069. */
  13070. _this.occlusionRetryCount = -1;
  13071. _this._occlusionInternalRetryCounter = 0;
  13072. _this._isOccluded = false;
  13073. _this._isOcclusionQueryInProgress = false;
  13074. _this._rotation = BABYLON.Vector3.Zero();
  13075. _this._scaling = BABYLON.Vector3.One();
  13076. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  13077. _this.visibility = 1.0;
  13078. _this.alphaIndex = Number.MAX_VALUE;
  13079. _this.infiniteDistance = false;
  13080. _this.isVisible = true;
  13081. _this.isPickable = true;
  13082. _this.showBoundingBox = false;
  13083. _this.showSubMeshesBoundingBox = false;
  13084. _this.isBlocker = false;
  13085. _this.enablePointerMoveEvents = false;
  13086. _this.renderingGroupId = 0;
  13087. _this._receiveShadows = false;
  13088. _this.renderOutline = false;
  13089. _this.outlineColor = BABYLON.Color3.Red();
  13090. _this.outlineWidth = 0.02;
  13091. _this.renderOverlay = false;
  13092. _this.overlayColor = BABYLON.Color3.Red();
  13093. _this.overlayAlpha = 0.5;
  13094. _this._hasVertexAlpha = false;
  13095. _this._useVertexColors = true;
  13096. _this._computeBonesUsingShaders = true;
  13097. _this._numBoneInfluencers = 4;
  13098. _this._applyFog = true;
  13099. _this.scalingDeterminant = 1;
  13100. _this.useOctreeForRenderingSelection = true;
  13101. _this.useOctreeForPicking = true;
  13102. _this.useOctreeForCollisions = true;
  13103. _this._layerMask = 0x0FFFFFFF;
  13104. /**
  13105. * True if the mesh must be rendered in any case.
  13106. */
  13107. _this.alwaysSelectAsActiveMesh = false;
  13108. // Collisions
  13109. _this._checkCollisions = false;
  13110. _this._collisionMask = -1;
  13111. _this._collisionGroup = -1;
  13112. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13113. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  13114. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13115. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13116. // Edges
  13117. _this.edgesWidth = 1;
  13118. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  13119. // Cache
  13120. _this._localWorld = BABYLON.Matrix.Zero();
  13121. _this._worldMatrix = BABYLON.Matrix.Zero();
  13122. _this._absolutePosition = BABYLON.Vector3.Zero();
  13123. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  13124. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  13125. _this._isDirty = false;
  13126. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13127. _this._postMultiplyPivotMatrix = false;
  13128. _this._isDisposed = false;
  13129. _this._renderId = 0;
  13130. _this._intersectionsInProgress = new Array();
  13131. _this._isWorldMatrixFrozen = false;
  13132. _this._unIndexed = false;
  13133. _this._lightSources = new Array();
  13134. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13135. if (collidedMesh === void 0) { collidedMesh = null; }
  13136. //TODO move this to the collision coordinator!
  13137. if (_this.getScene().workerCollisions)
  13138. newPosition.multiplyInPlace(_this._collider.radius);
  13139. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  13140. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  13141. _this.position.addInPlace(_this._diffPositionForCollisions);
  13142. }
  13143. if (collidedMesh) {
  13144. _this.onCollideObservable.notifyObservers(collidedMesh);
  13145. }
  13146. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  13147. };
  13148. _this.getScene().addMesh(_this);
  13149. _this._resyncLightSources();
  13150. return _this;
  13151. }
  13152. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  13153. get: function () {
  13154. return AbstractMesh._BILLBOARDMODE_NONE;
  13155. },
  13156. enumerable: true,
  13157. configurable: true
  13158. });
  13159. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  13160. get: function () {
  13161. return AbstractMesh._BILLBOARDMODE_X;
  13162. },
  13163. enumerable: true,
  13164. configurable: true
  13165. });
  13166. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  13167. get: function () {
  13168. return AbstractMesh._BILLBOARDMODE_Y;
  13169. },
  13170. enumerable: true,
  13171. configurable: true
  13172. });
  13173. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  13174. get: function () {
  13175. return AbstractMesh._BILLBOARDMODE_Z;
  13176. },
  13177. enumerable: true,
  13178. configurable: true
  13179. });
  13180. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  13181. get: function () {
  13182. return AbstractMesh._BILLBOARDMODE_ALL;
  13183. },
  13184. enumerable: true,
  13185. configurable: true
  13186. });
  13187. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  13188. /**
  13189. * Read-only : the number of facets in the mesh
  13190. */
  13191. get: function () {
  13192. return this._facetNb;
  13193. },
  13194. enumerable: true,
  13195. configurable: true
  13196. });
  13197. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  13198. /**
  13199. * The number (integer) of subdivisions per axis in the partioning space
  13200. */
  13201. get: function () {
  13202. return this._partitioningSubdivisions;
  13203. },
  13204. set: function (nb) {
  13205. this._partitioningSubdivisions = nb;
  13206. },
  13207. enumerable: true,
  13208. configurable: true
  13209. });
  13210. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  13211. /**
  13212. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  13213. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  13214. */
  13215. get: function () {
  13216. return this._partitioningBBoxRatio;
  13217. },
  13218. set: function (ratio) {
  13219. this._partitioningBBoxRatio = ratio;
  13220. },
  13221. enumerable: true,
  13222. configurable: true
  13223. });
  13224. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  13225. /**
  13226. * Read-only boolean : is the feature facetData enabled ?
  13227. */
  13228. get: function () {
  13229. return this._facetDataEnabled;
  13230. },
  13231. enumerable: true,
  13232. configurable: true
  13233. });
  13234. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  13235. get: function () {
  13236. return this._nonUniformScaling;
  13237. },
  13238. set: function (value) {
  13239. if (this._nonUniformScaling === value) {
  13240. return;
  13241. }
  13242. this._nonUniformScaling = true;
  13243. this._markSubMeshesAsMiscDirty();
  13244. },
  13245. enumerable: true,
  13246. configurable: true
  13247. });
  13248. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  13249. set: function (callback) {
  13250. if (this._onCollideObserver) {
  13251. this.onCollideObservable.remove(this._onCollideObserver);
  13252. }
  13253. this._onCollideObserver = this.onCollideObservable.add(callback);
  13254. },
  13255. enumerable: true,
  13256. configurable: true
  13257. });
  13258. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  13259. set: function (callback) {
  13260. if (this._onCollisionPositionChangeObserver) {
  13261. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  13262. }
  13263. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  13264. },
  13265. enumerable: true,
  13266. configurable: true
  13267. });
  13268. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  13269. /**
  13270. * 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.
  13271. */
  13272. get: function () {
  13273. return this._isOccluded;
  13274. },
  13275. set: function (value) {
  13276. this._isOccluded = value;
  13277. },
  13278. enumerable: true,
  13279. configurable: true
  13280. });
  13281. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  13282. /**
  13283. * Flag to check the progress status of the query
  13284. */
  13285. get: function () {
  13286. return this._isOcclusionQueryInProgress;
  13287. },
  13288. enumerable: true,
  13289. configurable: true
  13290. });
  13291. Object.defineProperty(AbstractMesh.prototype, "material", {
  13292. get: function () {
  13293. return this._material;
  13294. },
  13295. set: function (value) {
  13296. if (this._material === value) {
  13297. return;
  13298. }
  13299. this._material = value;
  13300. if (this.onMaterialChangedObservable.hasObservers) {
  13301. this.onMaterialChangedObservable.notifyObservers(this);
  13302. }
  13303. if (!this.subMeshes) {
  13304. return;
  13305. }
  13306. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13307. var subMesh = _a[_i];
  13308. subMesh.setEffect(null);
  13309. }
  13310. },
  13311. enumerable: true,
  13312. configurable: true
  13313. });
  13314. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  13315. get: function () {
  13316. return this._receiveShadows;
  13317. },
  13318. set: function (value) {
  13319. if (this._receiveShadows === value) {
  13320. return;
  13321. }
  13322. this._receiveShadows = value;
  13323. this._markSubMeshesAsLightDirty();
  13324. },
  13325. enumerable: true,
  13326. configurable: true
  13327. });
  13328. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  13329. get: function () {
  13330. return this._hasVertexAlpha;
  13331. },
  13332. set: function (value) {
  13333. if (this._hasVertexAlpha === value) {
  13334. return;
  13335. }
  13336. this._hasVertexAlpha = value;
  13337. this._markSubMeshesAsAttributesDirty();
  13338. },
  13339. enumerable: true,
  13340. configurable: true
  13341. });
  13342. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  13343. get: function () {
  13344. return this._useVertexColors;
  13345. },
  13346. set: function (value) {
  13347. if (this._useVertexColors === value) {
  13348. return;
  13349. }
  13350. this._useVertexColors = value;
  13351. this._markSubMeshesAsAttributesDirty();
  13352. },
  13353. enumerable: true,
  13354. configurable: true
  13355. });
  13356. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  13357. get: function () {
  13358. return this._computeBonesUsingShaders;
  13359. },
  13360. set: function (value) {
  13361. if (this._computeBonesUsingShaders === value) {
  13362. return;
  13363. }
  13364. this._computeBonesUsingShaders = value;
  13365. this._markSubMeshesAsAttributesDirty();
  13366. },
  13367. enumerable: true,
  13368. configurable: true
  13369. });
  13370. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13371. get: function () {
  13372. return this._numBoneInfluencers;
  13373. },
  13374. set: function (value) {
  13375. if (this._numBoneInfluencers === value) {
  13376. return;
  13377. }
  13378. this._numBoneInfluencers = value;
  13379. this._markSubMeshesAsAttributesDirty();
  13380. },
  13381. enumerable: true,
  13382. configurable: true
  13383. });
  13384. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13385. get: function () {
  13386. return this._applyFog;
  13387. },
  13388. set: function (value) {
  13389. if (this._applyFog === value) {
  13390. return;
  13391. }
  13392. this._applyFog = value;
  13393. this._markSubMeshesAsMiscDirty();
  13394. },
  13395. enumerable: true,
  13396. configurable: true
  13397. });
  13398. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13399. get: function () {
  13400. return this._layerMask;
  13401. },
  13402. set: function (value) {
  13403. if (value === this._layerMask) {
  13404. return;
  13405. }
  13406. this._layerMask = value;
  13407. this._resyncLightSources();
  13408. },
  13409. enumerable: true,
  13410. configurable: true
  13411. });
  13412. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13413. get: function () {
  13414. return this._collisionMask;
  13415. },
  13416. set: function (mask) {
  13417. this._collisionMask = !isNaN(mask) ? mask : -1;
  13418. },
  13419. enumerable: true,
  13420. configurable: true
  13421. });
  13422. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13423. get: function () {
  13424. return this._collisionGroup;
  13425. },
  13426. set: function (mask) {
  13427. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13428. },
  13429. enumerable: true,
  13430. configurable: true
  13431. });
  13432. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13433. get: function () {
  13434. return null;
  13435. },
  13436. enumerable: true,
  13437. configurable: true
  13438. });
  13439. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13440. get: function () {
  13441. return this._skeleton;
  13442. },
  13443. set: function (value) {
  13444. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13445. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13446. }
  13447. if (value && value.needInitialSkinMatrix) {
  13448. value._registerMeshWithPoseMatrix(this);
  13449. }
  13450. this._skeleton = value;
  13451. if (!this._skeleton) {
  13452. this._bonesTransformMatrices = null;
  13453. }
  13454. this._markSubMeshesAsAttributesDirty();
  13455. },
  13456. enumerable: true,
  13457. configurable: true
  13458. });
  13459. /**
  13460. * Boolean : true if the mesh has been disposed.
  13461. */
  13462. AbstractMesh.prototype.isDisposed = function () {
  13463. return this._isDisposed;
  13464. };
  13465. /**
  13466. * Returns the string "AbstractMesh"
  13467. */
  13468. AbstractMesh.prototype.getClassName = function () {
  13469. return "AbstractMesh";
  13470. };
  13471. /**
  13472. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13473. */
  13474. AbstractMesh.prototype.toString = function (fullDetails) {
  13475. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13476. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13477. if (this._skeleton) {
  13478. ret += ", skeleton: " + this._skeleton.name;
  13479. }
  13480. if (fullDetails) {
  13481. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13482. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13483. }
  13484. return ret;
  13485. };
  13486. AbstractMesh.prototype._rebuild = function () {
  13487. if (this._occlusionQuery) {
  13488. this._occlusionQuery = null;
  13489. }
  13490. if (this._edgesRenderer) {
  13491. this._edgesRenderer._rebuild();
  13492. }
  13493. if (!this.subMeshes) {
  13494. return;
  13495. }
  13496. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13497. var subMesh = _a[_i];
  13498. subMesh._rebuild();
  13499. }
  13500. };
  13501. AbstractMesh.prototype._resyncLightSources = function () {
  13502. this._lightSources.length = 0;
  13503. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13504. var light = _a[_i];
  13505. if (!light.isEnabled()) {
  13506. continue;
  13507. }
  13508. if (light.canAffectMesh(this)) {
  13509. this._lightSources.push(light);
  13510. }
  13511. }
  13512. this._markSubMeshesAsLightDirty();
  13513. };
  13514. AbstractMesh.prototype._resyncLighSource = function (light) {
  13515. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13516. var index = this._lightSources.indexOf(light);
  13517. if (index === -1) {
  13518. if (!isIn) {
  13519. return;
  13520. }
  13521. this._lightSources.push(light);
  13522. }
  13523. else {
  13524. if (isIn) {
  13525. return;
  13526. }
  13527. this._lightSources.splice(index, 1);
  13528. }
  13529. this._markSubMeshesAsLightDirty();
  13530. };
  13531. AbstractMesh.prototype._removeLightSource = function (light) {
  13532. var index = this._lightSources.indexOf(light);
  13533. if (index === -1) {
  13534. return;
  13535. }
  13536. this._lightSources.splice(index, 1);
  13537. };
  13538. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13539. if (!this.subMeshes) {
  13540. return;
  13541. }
  13542. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13543. var subMesh = _a[_i];
  13544. if (subMesh._materialDefines) {
  13545. func(subMesh._materialDefines);
  13546. }
  13547. }
  13548. };
  13549. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13550. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13551. };
  13552. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13553. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13554. };
  13555. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13556. if (!this.subMeshes) {
  13557. return;
  13558. }
  13559. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13560. var subMesh = _a[_i];
  13561. var material = subMesh.getMaterial();
  13562. if (material) {
  13563. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13564. }
  13565. }
  13566. };
  13567. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13568. /**
  13569. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13570. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13571. * Default : (0.0, 0.0, 0.0)
  13572. */
  13573. get: function () {
  13574. return this._rotation;
  13575. },
  13576. set: function (newRotation) {
  13577. this._rotation = newRotation;
  13578. },
  13579. enumerable: true,
  13580. configurable: true
  13581. });
  13582. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13583. /**
  13584. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13585. * Default : (1.0, 1.0, 1.0)
  13586. */
  13587. get: function () {
  13588. return this._scaling;
  13589. },
  13590. set: function (newScaling) {
  13591. this._scaling = newScaling;
  13592. if (this.physicsImpostor) {
  13593. this.physicsImpostor.forceUpdate();
  13594. }
  13595. },
  13596. enumerable: true,
  13597. configurable: true
  13598. });
  13599. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13600. /**
  13601. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13602. * It's null by default.
  13603. * 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)
  13604. */
  13605. get: function () {
  13606. return this._rotationQuaternion;
  13607. },
  13608. set: function (quaternion) {
  13609. this._rotationQuaternion = quaternion;
  13610. //reset the rotation vector.
  13611. if (quaternion && this.rotation.length()) {
  13612. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13613. }
  13614. },
  13615. enumerable: true,
  13616. configurable: true
  13617. });
  13618. // Methods
  13619. /**
  13620. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13621. * Returns the AbstractMesh.
  13622. */
  13623. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13624. this._poseMatrix.copyFrom(matrix);
  13625. return this;
  13626. };
  13627. /**
  13628. * Returns the mesh Pose matrix.
  13629. * Returned object : Matrix
  13630. */
  13631. AbstractMesh.prototype.getPoseMatrix = function () {
  13632. return this._poseMatrix;
  13633. };
  13634. /**
  13635. * Disables the mesh edger rendering mode.
  13636. * Returns the AbstractMesh.
  13637. */
  13638. AbstractMesh.prototype.disableEdgesRendering = function () {
  13639. if (this._edgesRenderer) {
  13640. this._edgesRenderer.dispose();
  13641. this._edgesRenderer = null;
  13642. }
  13643. return this;
  13644. };
  13645. /**
  13646. * Enables the edge rendering mode on the mesh.
  13647. * This mode makes the mesh edges visible.
  13648. * Returns the AbstractMesh.
  13649. */
  13650. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13651. if (epsilon === void 0) { epsilon = 0.95; }
  13652. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13653. this.disableEdgesRendering();
  13654. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13655. return this;
  13656. };
  13657. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13658. /**
  13659. * Returns true if the mesh is blocked. Used by the class Mesh.
  13660. * Returns the boolean `false` by default.
  13661. */
  13662. get: function () {
  13663. return false;
  13664. },
  13665. enumerable: true,
  13666. configurable: true
  13667. });
  13668. /**
  13669. * Returns the mesh itself by default, used by the class Mesh.
  13670. * Returned type : AbstractMesh
  13671. */
  13672. AbstractMesh.prototype.getLOD = function (camera) {
  13673. return this;
  13674. };
  13675. /**
  13676. * Returns 0 by default, used by the class Mesh.
  13677. * Returns an integer.
  13678. */
  13679. AbstractMesh.prototype.getTotalVertices = function () {
  13680. return 0;
  13681. };
  13682. /**
  13683. * Returns null by default, used by the class Mesh.
  13684. * Returned type : integer array
  13685. */
  13686. AbstractMesh.prototype.getIndices = function () {
  13687. return null;
  13688. };
  13689. /**
  13690. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13691. * Returned type : float array or Float32Array
  13692. */
  13693. AbstractMesh.prototype.getVerticesData = function (kind) {
  13694. return null;
  13695. };
  13696. /**
  13697. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13698. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13699. * The `data` are either a numeric array either a Float32Array.
  13700. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13701. * 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).
  13702. * Note that a new underlying VertexBuffer object is created each call.
  13703. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13704. *
  13705. * Possible `kind` values :
  13706. * - BABYLON.VertexBuffer.PositionKind
  13707. * - BABYLON.VertexBuffer.UVKind
  13708. * - BABYLON.VertexBuffer.UV2Kind
  13709. * - BABYLON.VertexBuffer.UV3Kind
  13710. * - BABYLON.VertexBuffer.UV4Kind
  13711. * - BABYLON.VertexBuffer.UV5Kind
  13712. * - BABYLON.VertexBuffer.UV6Kind
  13713. * - BABYLON.VertexBuffer.ColorKind
  13714. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13715. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13716. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13717. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13718. *
  13719. * Returns the Mesh.
  13720. */
  13721. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13722. return this;
  13723. };
  13724. /**
  13725. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13726. * If the mesh has no geometry, it is simply returned as it is.
  13727. * The `data` are either a numeric array either a Float32Array.
  13728. * No new underlying VertexBuffer object is created.
  13729. * 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.
  13730. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13731. *
  13732. * Possible `kind` values :
  13733. * - BABYLON.VertexBuffer.PositionKind
  13734. * - BABYLON.VertexBuffer.UVKind
  13735. * - BABYLON.VertexBuffer.UV2Kind
  13736. * - BABYLON.VertexBuffer.UV3Kind
  13737. * - BABYLON.VertexBuffer.UV4Kind
  13738. * - BABYLON.VertexBuffer.UV5Kind
  13739. * - BABYLON.VertexBuffer.UV6Kind
  13740. * - BABYLON.VertexBuffer.ColorKind
  13741. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13742. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13743. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13744. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13745. *
  13746. * Returns the Mesh.
  13747. */
  13748. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13749. return this;
  13750. };
  13751. /**
  13752. * Sets the mesh indices.
  13753. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13754. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13755. * This method creates a new index buffer each call.
  13756. * Returns the Mesh.
  13757. */
  13758. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13759. return this;
  13760. };
  13761. /** Returns false by default, used by the class Mesh.
  13762. * Returns a boolean
  13763. */
  13764. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13765. return false;
  13766. };
  13767. /**
  13768. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13769. * Returns a BoundingInfo
  13770. */
  13771. AbstractMesh.prototype.getBoundingInfo = function () {
  13772. if (this._masterMesh) {
  13773. return this._masterMesh.getBoundingInfo();
  13774. }
  13775. if (!this._boundingInfo) {
  13776. this._updateBoundingInfo();
  13777. }
  13778. return this._boundingInfo;
  13779. };
  13780. /**
  13781. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  13782. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  13783. */
  13784. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  13785. if (includeDescendants === void 0) { includeDescendants = true; }
  13786. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  13787. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  13788. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  13789. if (maxDimension === 0) {
  13790. return this;
  13791. }
  13792. var scale = 1 / maxDimension;
  13793. this.scaling.scaleInPlace(scale);
  13794. return this;
  13795. };
  13796. /**
  13797. * Sets a mesh new object BoundingInfo.
  13798. * Returns the AbstractMesh.
  13799. */
  13800. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13801. this._boundingInfo = boundingInfo;
  13802. return this;
  13803. };
  13804. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13805. get: function () {
  13806. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13807. },
  13808. enumerable: true,
  13809. configurable: true
  13810. });
  13811. AbstractMesh.prototype._preActivate = function () {
  13812. };
  13813. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13814. };
  13815. AbstractMesh.prototype._activate = function (renderId) {
  13816. this._renderId = renderId;
  13817. };
  13818. /**
  13819. * Returns the latest update of the World matrix
  13820. * Returns a Matrix.
  13821. */
  13822. AbstractMesh.prototype.getWorldMatrix = function () {
  13823. if (this._masterMesh) {
  13824. return this._masterMesh.getWorldMatrix();
  13825. }
  13826. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13827. this.computeWorldMatrix();
  13828. }
  13829. return this._worldMatrix;
  13830. };
  13831. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13832. /**
  13833. * Returns directly the latest state of the mesh World matrix.
  13834. * A Matrix is returned.
  13835. */
  13836. get: function () {
  13837. return this._worldMatrix;
  13838. },
  13839. enumerable: true,
  13840. configurable: true
  13841. });
  13842. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13843. /**
  13844. * Returns the current mesh absolute position.
  13845. * Retuns a Vector3.
  13846. */
  13847. get: function () {
  13848. return this._absolutePosition;
  13849. },
  13850. enumerable: true,
  13851. configurable: true
  13852. });
  13853. /**
  13854. * Prevents the World matrix to be computed any longer.
  13855. * Returns the AbstractMesh.
  13856. */
  13857. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13858. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13859. this.computeWorldMatrix(true);
  13860. this._isWorldMatrixFrozen = true;
  13861. return this;
  13862. };
  13863. /**
  13864. * Allows back the World matrix computation.
  13865. * Returns the AbstractMesh.
  13866. */
  13867. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13868. this._isWorldMatrixFrozen = false;
  13869. this.computeWorldMatrix(true);
  13870. return this;
  13871. };
  13872. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13873. /**
  13874. * True if the World matrix has been frozen.
  13875. * Returns a boolean.
  13876. */
  13877. get: function () {
  13878. return this._isWorldMatrixFrozen;
  13879. },
  13880. enumerable: true,
  13881. configurable: true
  13882. });
  13883. /**
  13884. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13885. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13886. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13887. * The passed axis is also normalized.
  13888. * Returns the AbstractMesh.
  13889. */
  13890. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13891. axis.normalize();
  13892. if (!this.rotationQuaternion) {
  13893. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13894. this.rotation = BABYLON.Vector3.Zero();
  13895. }
  13896. var rotationQuaternion;
  13897. if (!space || space === BABYLON.Space.LOCAL) {
  13898. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13899. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13900. }
  13901. else {
  13902. if (this.parent) {
  13903. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13904. invertParentWorldMatrix.invert();
  13905. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13906. }
  13907. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13908. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13909. }
  13910. return this;
  13911. };
  13912. /**
  13913. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13914. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13915. * The passed axis is also normalized.
  13916. * Returns the AbstractMesh.
  13917. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13918. */
  13919. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13920. axis.normalize();
  13921. if (!this.rotationQuaternion) {
  13922. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13923. this.rotation.copyFromFloats(0, 0, 0);
  13924. }
  13925. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13926. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13927. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13928. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13929. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13930. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13931. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13932. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13933. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13934. return this;
  13935. };
  13936. /**
  13937. * Translates the mesh along the axis vector for the passed distance in the given space.
  13938. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13939. * Returns the AbstractMesh.
  13940. */
  13941. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13942. var displacementVector = axis.scale(distance);
  13943. if (!space || space === BABYLON.Space.LOCAL) {
  13944. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13945. this.setPositionWithLocalVector(tempV3);
  13946. }
  13947. else {
  13948. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13949. }
  13950. return this;
  13951. };
  13952. /**
  13953. * Adds a rotation step to the mesh current rotation.
  13954. * x, y, z are Euler angles expressed in radians.
  13955. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13956. * This means this rotation is made in the mesh local space only.
  13957. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13958. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13959. * ```javascript
  13960. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13961. * ```
  13962. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13963. * 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.
  13964. * Returns the AbstractMesh.
  13965. */
  13966. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13967. var rotationQuaternion;
  13968. if (this.rotationQuaternion) {
  13969. rotationQuaternion = this.rotationQuaternion;
  13970. }
  13971. else {
  13972. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13973. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13974. }
  13975. var accumulation = BABYLON.Tmp.Quaternion[0];
  13976. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13977. rotationQuaternion.multiplyInPlace(accumulation);
  13978. if (!this.rotationQuaternion) {
  13979. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13980. }
  13981. return this;
  13982. };
  13983. /**
  13984. * Retuns the mesh absolute position in the World.
  13985. * Returns a Vector3.
  13986. */
  13987. AbstractMesh.prototype.getAbsolutePosition = function () {
  13988. this.computeWorldMatrix();
  13989. return this._absolutePosition;
  13990. };
  13991. /**
  13992. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13993. * Returns the AbstractMesh.
  13994. */
  13995. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13996. if (!absolutePosition) {
  13997. return this;
  13998. }
  13999. var absolutePositionX;
  14000. var absolutePositionY;
  14001. var absolutePositionZ;
  14002. if (absolutePosition.x === undefined) {
  14003. if (arguments.length < 3) {
  14004. return this;
  14005. }
  14006. absolutePositionX = arguments[0];
  14007. absolutePositionY = arguments[1];
  14008. absolutePositionZ = arguments[2];
  14009. }
  14010. else {
  14011. absolutePositionX = absolutePosition.x;
  14012. absolutePositionY = absolutePosition.y;
  14013. absolutePositionZ = absolutePosition.z;
  14014. }
  14015. if (this.parent) {
  14016. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14017. invertParentWorldMatrix.invert();
  14018. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14019. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14020. }
  14021. else {
  14022. this.position.x = absolutePositionX;
  14023. this.position.y = absolutePositionY;
  14024. this.position.z = absolutePositionZ;
  14025. }
  14026. return this;
  14027. };
  14028. // ================================== Point of View Movement =================================
  14029. /**
  14030. * Perform relative position change from the point of view of behind the front of the mesh.
  14031. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14032. * Supports definition of mesh facing forward or backward.
  14033. * @param {number} amountRight
  14034. * @param {number} amountUp
  14035. * @param {number} amountForward
  14036. *
  14037. * Returns the AbstractMesh.
  14038. */
  14039. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  14040. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  14041. return this;
  14042. };
  14043. /**
  14044. * Calculate relative position change from the point of view of behind the front of the mesh.
  14045. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14046. * Supports definition of mesh facing forward or backward.
  14047. * @param {number} amountRight
  14048. * @param {number} amountUp
  14049. * @param {number} amountForward
  14050. *
  14051. * Returns a new Vector3.
  14052. */
  14053. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  14054. var rotMatrix = new BABYLON.Matrix();
  14055. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14056. rotQuaternion.toRotationMatrix(rotMatrix);
  14057. var translationDelta = BABYLON.Vector3.Zero();
  14058. var defForwardMult = this.definedFacingForward ? -1 : 1;
  14059. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  14060. return translationDelta;
  14061. };
  14062. // ================================== Point of View Rotation =================================
  14063. /**
  14064. * Perform relative rotation change from the point of view of behind the front of the mesh.
  14065. * Supports definition of mesh facing forward or backward.
  14066. * @param {number} flipBack
  14067. * @param {number} twirlClockwise
  14068. * @param {number} tiltRight
  14069. *
  14070. * Returns the AbstractMesh.
  14071. */
  14072. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14073. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  14074. return this;
  14075. };
  14076. /**
  14077. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  14078. * Supports definition of mesh facing forward or backward.
  14079. * @param {number} flipBack
  14080. * @param {number} twirlClockwise
  14081. * @param {number} tiltRight
  14082. *
  14083. * Returns a new Vector3.
  14084. */
  14085. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14086. var defForwardMult = this.definedFacingForward ? 1 : -1;
  14087. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  14088. };
  14089. /**
  14090. * Sets a new pivot matrix to the mesh.
  14091. * Returns the AbstractMesh.
  14092. */
  14093. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14094. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14095. this._pivotMatrix = matrix.clone();
  14096. this._cache.pivotMatrixUpdated = true;
  14097. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14098. if (this._postMultiplyPivotMatrix) {
  14099. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14100. }
  14101. return this;
  14102. };
  14103. /**
  14104. * Returns the mesh pivot matrix.
  14105. * Default : Identity.
  14106. * A Matrix is returned.
  14107. */
  14108. AbstractMesh.prototype.getPivotMatrix = function () {
  14109. return this._pivotMatrix;
  14110. };
  14111. AbstractMesh.prototype._isSynchronized = function () {
  14112. if (this._isDirty) {
  14113. return false;
  14114. }
  14115. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  14116. return false;
  14117. if (this._cache.pivotMatrixUpdated) {
  14118. return false;
  14119. }
  14120. if (this.infiniteDistance) {
  14121. return false;
  14122. }
  14123. if (!this._cache.position.equals(this.position))
  14124. return false;
  14125. if (this.rotationQuaternion) {
  14126. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14127. return false;
  14128. }
  14129. if (!this._cache.rotation.equals(this.rotation))
  14130. return false;
  14131. if (!this._cache.scaling.equals(this.scaling))
  14132. return false;
  14133. return true;
  14134. };
  14135. AbstractMesh.prototype._initCache = function () {
  14136. _super.prototype._initCache.call(this);
  14137. this._cache.localMatrixUpdated = false;
  14138. this._cache.position = BABYLON.Vector3.Zero();
  14139. this._cache.scaling = BABYLON.Vector3.Zero();
  14140. this._cache.rotation = BABYLON.Vector3.Zero();
  14141. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14142. this._cache.billboardMode = -1;
  14143. };
  14144. AbstractMesh.prototype.markAsDirty = function (property) {
  14145. if (property === "rotation") {
  14146. this.rotationQuaternion = null;
  14147. }
  14148. this._currentRenderId = Number.MAX_VALUE;
  14149. this._isDirty = true;
  14150. return this;
  14151. };
  14152. /**
  14153. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14154. * @param includeDescendants Include bounding info from descendants as well (true by default).
  14155. */
  14156. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  14157. if (includeDescendants === void 0) { includeDescendants = true; }
  14158. this.computeWorldMatrix(true);
  14159. var min;
  14160. var max;
  14161. var boundingInfo = this.getBoundingInfo();
  14162. if (!this.subMeshes || !boundingInfo) {
  14163. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14164. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14165. }
  14166. else {
  14167. min = boundingInfo.boundingBox.minimumWorld;
  14168. max = boundingInfo.boundingBox.maximumWorld;
  14169. }
  14170. if (includeDescendants) {
  14171. var descendants = this.getDescendants(false);
  14172. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14173. var descendant = descendants_1[_i];
  14174. var childMesh = descendant;
  14175. childMesh.computeWorldMatrix(true);
  14176. var childBoundingInfo = childMesh.getBoundingInfo();
  14177. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  14178. continue;
  14179. }
  14180. var boundingBox = childBoundingInfo.boundingBox;
  14181. var minBox = boundingBox.minimumWorld;
  14182. var maxBox = boundingBox.maximumWorld;
  14183. BABYLON.Tools.CheckExtends(minBox, min, max);
  14184. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14185. }
  14186. }
  14187. return {
  14188. min: min,
  14189. max: max
  14190. };
  14191. };
  14192. /**
  14193. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14194. * Returns the AbstractMesh.
  14195. */
  14196. AbstractMesh.prototype._updateBoundingInfo = function () {
  14197. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14198. this._boundingInfo.update(this.worldMatrixFromCache);
  14199. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14200. return this;
  14201. };
  14202. /**
  14203. * Update a mesh's children BoundingInfo objects only.
  14204. * Returns the AbstractMesh.
  14205. */
  14206. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14207. if (!this.subMeshes) {
  14208. return this;
  14209. }
  14210. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14211. var subMesh = this.subMeshes[subIndex];
  14212. if (!subMesh.IsGlobal) {
  14213. subMesh.updateBoundingInfo(matrix);
  14214. }
  14215. }
  14216. return this;
  14217. };
  14218. /**
  14219. * Computes the mesh World matrix and returns it.
  14220. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14221. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14222. * If the parameter `force`is set to `true`, the actual computation is done.
  14223. * Returns the mesh World Matrix.
  14224. */
  14225. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  14226. if (this._isWorldMatrixFrozen) {
  14227. return this._worldMatrix;
  14228. }
  14229. if (!force && this.isSynchronized(true)) {
  14230. return this._worldMatrix;
  14231. }
  14232. this._cache.position.copyFrom(this.position);
  14233. this._cache.scaling.copyFrom(this.scaling);
  14234. this._cache.pivotMatrixUpdated = false;
  14235. this._cache.billboardMode = this.billboardMode;
  14236. this._currentRenderId = this.getScene().getRenderId();
  14237. this._isDirty = false;
  14238. // Scaling
  14239. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14240. // Rotation
  14241. //rotate, if quaternion is set and rotation was used
  14242. if (this.rotationQuaternion) {
  14243. var len = this.rotation.length();
  14244. if (len) {
  14245. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14246. this.rotation.copyFromFloats(0, 0, 0);
  14247. }
  14248. }
  14249. if (this.rotationQuaternion) {
  14250. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14251. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14252. }
  14253. else {
  14254. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14255. this._cache.rotation.copyFrom(this.rotation);
  14256. }
  14257. // Translation
  14258. var camera = this.getScene().activeCamera;
  14259. if (this.infiniteDistance && !this.parent && camera) {
  14260. var cameraWorldMatrix = camera.getWorldMatrix();
  14261. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14262. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14263. }
  14264. else {
  14265. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14266. }
  14267. // Composing transformations
  14268. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14269. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14270. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14271. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14272. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  14273. // Need to decompose each rotation here
  14274. var currentPosition = BABYLON.Tmp.Vector3[3];
  14275. if (this.parent && this.parent.getWorldMatrix) {
  14276. if (this._meshToBoneReferal) {
  14277. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14278. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14279. }
  14280. else {
  14281. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14282. }
  14283. }
  14284. else {
  14285. currentPosition.copyFrom(this.position);
  14286. }
  14287. currentPosition.subtractInPlace(camera.globalPosition);
  14288. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14289. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  14290. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14291. }
  14292. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  14293. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14294. }
  14295. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  14296. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14297. }
  14298. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14299. }
  14300. else {
  14301. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14302. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14303. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14304. }
  14305. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14306. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14307. }
  14308. // Local world
  14309. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14310. // Parent
  14311. if (this.parent && this.parent.getWorldMatrix) {
  14312. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  14313. if (this._meshToBoneReferal) {
  14314. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14315. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14316. }
  14317. else {
  14318. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14319. }
  14320. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14321. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14322. this._worldMatrix.copyFrom(this._localWorld);
  14323. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14324. }
  14325. else {
  14326. if (this._meshToBoneReferal) {
  14327. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14328. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14329. }
  14330. else {
  14331. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14332. }
  14333. }
  14334. this._markSyncedWithParent();
  14335. }
  14336. else {
  14337. this._worldMatrix.copyFrom(this._localWorld);
  14338. }
  14339. // Post multiply inverse of pivotMatrix
  14340. if (this._postMultiplyPivotMatrix) {
  14341. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14342. }
  14343. // Normal matrix
  14344. if (this.scaling.isNonUniform) {
  14345. this.nonUniformScaling = true;
  14346. }
  14347. else if (this.parent && this.parent._nonUniformScaling) {
  14348. this.nonUniformScaling = this.parent._nonUniformScaling;
  14349. }
  14350. else {
  14351. this.nonUniformScaling = false;
  14352. }
  14353. // Bounding info
  14354. this._updateBoundingInfo();
  14355. // Absolute position
  14356. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14357. // Callbacks
  14358. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14359. if (!this._poseMatrix) {
  14360. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14361. }
  14362. return this._worldMatrix;
  14363. };
  14364. /**
  14365. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14366. * @param func: callback function to add
  14367. *
  14368. * Returns the AbstractMesh.
  14369. */
  14370. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14371. this.onAfterWorldMatrixUpdateObservable.add(func);
  14372. return this;
  14373. };
  14374. /**
  14375. * Removes a registered callback function.
  14376. * Returns the AbstractMesh.
  14377. */
  14378. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14379. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14380. return this;
  14381. };
  14382. /**
  14383. * Sets the mesh position in its local space.
  14384. * Returns the AbstractMesh.
  14385. */
  14386. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14387. this.computeWorldMatrix();
  14388. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14389. return this;
  14390. };
  14391. /**
  14392. * Returns the mesh position in the local space from the current World matrix values.
  14393. * Returns a new Vector3.
  14394. */
  14395. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14396. this.computeWorldMatrix();
  14397. var invLocalWorldMatrix = this._localWorld.clone();
  14398. invLocalWorldMatrix.invert();
  14399. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14400. };
  14401. /**
  14402. * Translates the mesh along the passed Vector3 in its local space.
  14403. * Returns the AbstractMesh.
  14404. */
  14405. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14406. this.computeWorldMatrix(true);
  14407. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14408. return this;
  14409. };
  14410. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14411. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14412. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14413. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14414. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14415. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14416. /// <returns>Mesh oriented towards targetMesh</returns>
  14417. if (yawCor === void 0) { yawCor = 0; }
  14418. if (pitchCor === void 0) { pitchCor = 0; }
  14419. if (rollCor === void 0) { rollCor = 0; }
  14420. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14421. var dv = AbstractMesh._lookAtVectorCache;
  14422. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14423. targetPoint.subtractToRef(pos, dv);
  14424. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14425. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14426. var pitch = Math.atan2(dv.y, len);
  14427. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14428. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14429. return this;
  14430. };
  14431. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14432. this._meshToBoneReferal = affectedMesh;
  14433. this.parent = bone;
  14434. if (bone.getWorldMatrix().determinant() < 0) {
  14435. this.scalingDeterminant *= -1;
  14436. }
  14437. return this;
  14438. };
  14439. AbstractMesh.prototype.detachFromBone = function () {
  14440. if (!this.parent) {
  14441. return this;
  14442. }
  14443. if (this.parent.getWorldMatrix().determinant() < 0) {
  14444. this.scalingDeterminant *= -1;
  14445. }
  14446. this._meshToBoneReferal = null;
  14447. this.parent = null;
  14448. return this;
  14449. };
  14450. /**
  14451. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14452. * A mesh is in the frustum if its bounding box intersects the frustum.
  14453. * Boolean returned.
  14454. */
  14455. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14456. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14457. };
  14458. /**
  14459. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14460. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14461. * Boolean returned.
  14462. */
  14463. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14464. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14465. ;
  14466. };
  14467. /**
  14468. * True if the mesh intersects another mesh or a SolidParticle object.
  14469. * 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)
  14470. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14471. * Returns a boolean.
  14472. */
  14473. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14474. if (precise === void 0) { precise = false; }
  14475. if (!this._boundingInfo || !mesh._boundingInfo) {
  14476. return false;
  14477. }
  14478. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14479. return true;
  14480. }
  14481. if (includeDescendants) {
  14482. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14483. var child = _a[_i];
  14484. if (child.intersectsMesh(mesh, precise, true)) {
  14485. return true;
  14486. }
  14487. }
  14488. }
  14489. return false;
  14490. };
  14491. /**
  14492. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14493. * Returns a boolean.
  14494. */
  14495. AbstractMesh.prototype.intersectsPoint = function (point) {
  14496. if (!this._boundingInfo) {
  14497. return false;
  14498. }
  14499. return this._boundingInfo.intersectsPoint(point);
  14500. };
  14501. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14502. return this.physicsImpostor;
  14503. };
  14504. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14505. if (camera === void 0) { camera = null; }
  14506. if (!camera) {
  14507. camera = this.getScene().activeCamera;
  14508. }
  14509. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14510. };
  14511. /**
  14512. * Returns the distance from the mesh to the active camera.
  14513. * Returns a float.
  14514. */
  14515. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14516. if (camera === void 0) { camera = null; }
  14517. if (!camera) {
  14518. camera = this.getScene().activeCamera;
  14519. }
  14520. return this.absolutePosition.subtract(camera.position).length();
  14521. };
  14522. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14523. if (!this.physicsImpostor) {
  14524. return this;
  14525. }
  14526. this.physicsImpostor.applyImpulse(force, contactPoint);
  14527. return this;
  14528. };
  14529. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14530. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14531. return this;
  14532. }
  14533. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14534. mainPivot: pivot1,
  14535. connectedPivot: pivot2,
  14536. nativeParams: options
  14537. });
  14538. return this;
  14539. };
  14540. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14541. // Collisions
  14542. /**
  14543. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14544. * Default `false`.
  14545. */
  14546. get: function () {
  14547. return this._checkCollisions;
  14548. },
  14549. set: function (collisionEnabled) {
  14550. this._checkCollisions = collisionEnabled;
  14551. if (this.getScene().workerCollisions) {
  14552. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14553. }
  14554. },
  14555. enumerable: true,
  14556. configurable: true
  14557. });
  14558. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14559. var globalPosition = this.getAbsolutePosition();
  14560. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14561. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14562. if (!this._collider) {
  14563. this._collider = new BABYLON.Collider();
  14564. }
  14565. this._collider.radius = this.ellipsoid;
  14566. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14567. return this;
  14568. };
  14569. // Submeshes octree
  14570. /**
  14571. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14572. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14573. * Returns an Octree of submeshes.
  14574. */
  14575. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14576. if (maxCapacity === void 0) { maxCapacity = 64; }
  14577. if (maxDepth === void 0) { maxDepth = 2; }
  14578. if (!this._submeshesOctree) {
  14579. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14580. }
  14581. this.computeWorldMatrix(true);
  14582. var boundingInfo = this.getBoundingInfo();
  14583. // Update octree
  14584. if (boundingInfo) {
  14585. var bbox = boundingInfo.boundingBox;
  14586. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14587. }
  14588. return this._submeshesOctree;
  14589. };
  14590. // Collisions
  14591. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14592. this._generatePointsArray();
  14593. if (!this._positions) {
  14594. return this;
  14595. }
  14596. // Transformation
  14597. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14598. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14599. subMesh._lastColliderWorldVertices = [];
  14600. subMesh._trianglePlanes = [];
  14601. var start = subMesh.verticesStart;
  14602. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14603. for (var i = start; i < end; i++) {
  14604. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14605. }
  14606. }
  14607. // Collide
  14608. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14609. if (collider.collisionFound) {
  14610. collider.collidedMesh = this;
  14611. }
  14612. return this;
  14613. };
  14614. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14615. var subMeshes;
  14616. var len;
  14617. // Octrees
  14618. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14619. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14620. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14621. len = intersections.length;
  14622. subMeshes = intersections.data;
  14623. }
  14624. else {
  14625. subMeshes = this.subMeshes;
  14626. len = subMeshes.length;
  14627. }
  14628. for (var index = 0; index < len; index++) {
  14629. var subMesh = subMeshes[index];
  14630. // Bounding test
  14631. if (len > 1 && !subMesh._checkCollision(collider))
  14632. continue;
  14633. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14634. }
  14635. return this;
  14636. };
  14637. AbstractMesh.prototype._checkCollision = function (collider) {
  14638. // Bounding box test
  14639. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14640. return this;
  14641. // Transformation matrix
  14642. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14643. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14644. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14645. return this;
  14646. };
  14647. // Picking
  14648. AbstractMesh.prototype._generatePointsArray = function () {
  14649. return false;
  14650. };
  14651. /**
  14652. * Checks if the passed Ray intersects with the mesh.
  14653. * Returns an object PickingInfo.
  14654. */
  14655. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14656. var pickingInfo = new BABYLON.PickingInfo();
  14657. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14658. return pickingInfo;
  14659. }
  14660. if (!this._generatePointsArray()) {
  14661. return pickingInfo;
  14662. }
  14663. var intersectInfo = null;
  14664. // Octrees
  14665. var subMeshes;
  14666. var len;
  14667. if (this._submeshesOctree && this.useOctreeForPicking) {
  14668. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14669. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14670. len = intersections.length;
  14671. subMeshes = intersections.data;
  14672. }
  14673. else {
  14674. subMeshes = this.subMeshes;
  14675. len = subMeshes.length;
  14676. }
  14677. for (var index = 0; index < len; index++) {
  14678. var subMesh = subMeshes[index];
  14679. // Bounding test
  14680. if (len > 1 && !subMesh.canIntersects(ray))
  14681. continue;
  14682. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14683. if (currentIntersectInfo) {
  14684. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14685. intersectInfo = currentIntersectInfo;
  14686. intersectInfo.subMeshId = index;
  14687. if (fastCheck) {
  14688. break;
  14689. }
  14690. }
  14691. }
  14692. }
  14693. if (intersectInfo) {
  14694. // Get picked point
  14695. var world = this.getWorldMatrix();
  14696. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14697. var direction = ray.direction.clone();
  14698. direction = direction.scale(intersectInfo.distance);
  14699. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14700. var pickedPoint = worldOrigin.add(worldDirection);
  14701. // Return result
  14702. pickingInfo.hit = true;
  14703. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14704. pickingInfo.pickedPoint = pickedPoint;
  14705. pickingInfo.pickedMesh = this;
  14706. pickingInfo.bu = intersectInfo.bu || 0;
  14707. pickingInfo.bv = intersectInfo.bv || 0;
  14708. pickingInfo.faceId = intersectInfo.faceId;
  14709. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14710. return pickingInfo;
  14711. }
  14712. return pickingInfo;
  14713. };
  14714. /**
  14715. * Clones the mesh, used by the class Mesh.
  14716. * Just returns `null` for an AbstractMesh.
  14717. */
  14718. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14719. return null;
  14720. };
  14721. /**
  14722. * Disposes all the mesh submeshes.
  14723. * Returns the AbstractMesh.
  14724. */
  14725. AbstractMesh.prototype.releaseSubMeshes = function () {
  14726. if (this.subMeshes) {
  14727. while (this.subMeshes.length) {
  14728. this.subMeshes[0].dispose();
  14729. }
  14730. }
  14731. else {
  14732. this.subMeshes = new Array();
  14733. }
  14734. return this;
  14735. };
  14736. /**
  14737. * Disposes the AbstractMesh.
  14738. * Some internal references are kept for further use.
  14739. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14740. * Returns nothing.
  14741. */
  14742. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14743. var _this = this;
  14744. var index;
  14745. // Action manager
  14746. if (this.actionManager) {
  14747. this.actionManager.dispose();
  14748. this.actionManager = null;
  14749. }
  14750. // Skeleton
  14751. this.skeleton = null;
  14752. // Animations
  14753. this.getScene().stopAnimation(this);
  14754. // Physics
  14755. if (this.physicsImpostor) {
  14756. this.physicsImpostor.dispose();
  14757. }
  14758. // Intersections in progress
  14759. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14760. var other = this._intersectionsInProgress[index];
  14761. var pos = other._intersectionsInProgress.indexOf(this);
  14762. other._intersectionsInProgress.splice(pos, 1);
  14763. }
  14764. this._intersectionsInProgress = [];
  14765. // Lights
  14766. var lights = this.getScene().lights;
  14767. lights.forEach(function (light) {
  14768. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14769. if (meshIndex !== -1) {
  14770. light.includedOnlyMeshes.splice(meshIndex, 1);
  14771. }
  14772. meshIndex = light.excludedMeshes.indexOf(_this);
  14773. if (meshIndex !== -1) {
  14774. light.excludedMeshes.splice(meshIndex, 1);
  14775. }
  14776. // Shadow generators
  14777. var generator = light.getShadowGenerator();
  14778. if (generator) {
  14779. var shadowMap = generator.getShadowMap();
  14780. if (shadowMap && shadowMap.renderList) {
  14781. meshIndex = shadowMap.renderList.indexOf(_this);
  14782. if (meshIndex !== -1) {
  14783. shadowMap.renderList.splice(meshIndex, 1);
  14784. }
  14785. }
  14786. }
  14787. });
  14788. // Edges
  14789. if (this._edgesRenderer) {
  14790. this._edgesRenderer.dispose();
  14791. this._edgesRenderer = null;
  14792. }
  14793. // SubMeshes
  14794. if (this.getClassName() !== "InstancedMesh") {
  14795. this.releaseSubMeshes();
  14796. }
  14797. // Octree
  14798. var sceneOctree = this.getScene().selectionOctree;
  14799. if (sceneOctree) {
  14800. var index = sceneOctree.dynamicContent.indexOf(this);
  14801. if (index !== -1) {
  14802. sceneOctree.dynamicContent.splice(index, 1);
  14803. }
  14804. }
  14805. // Query
  14806. var engine = this.getScene().getEngine();
  14807. if (this._occlusionQuery) {
  14808. this._isOcclusionQueryInProgress = false;
  14809. engine.deleteQuery(this._occlusionQuery);
  14810. this._occlusionQuery = null;
  14811. }
  14812. // Engine
  14813. engine.wipeCaches();
  14814. // Remove from scene
  14815. this.getScene().removeMesh(this);
  14816. if (!doNotRecurse) {
  14817. // Particles
  14818. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14819. if (this.getScene().particleSystems[index].emitter === this) {
  14820. this.getScene().particleSystems[index].dispose();
  14821. index--;
  14822. }
  14823. }
  14824. // Children
  14825. var objects = this.getDescendants(true);
  14826. for (index = 0; index < objects.length; index++) {
  14827. objects[index].dispose();
  14828. }
  14829. }
  14830. else {
  14831. var childMeshes = this.getChildMeshes(true);
  14832. for (index = 0; index < childMeshes.length; index++) {
  14833. var child = childMeshes[index];
  14834. child.parent = null;
  14835. child.computeWorldMatrix(true);
  14836. }
  14837. }
  14838. // facet data
  14839. if (this._facetDataEnabled) {
  14840. this.disableFacetData();
  14841. }
  14842. this.onAfterWorldMatrixUpdateObservable.clear();
  14843. this.onCollideObservable.clear();
  14844. this.onCollisionPositionChangeObservable.clear();
  14845. this._isDisposed = true;
  14846. _super.prototype.dispose.call(this);
  14847. };
  14848. /**
  14849. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14850. * This Vector3 is expressed in the World space.
  14851. */
  14852. AbstractMesh.prototype.getDirection = function (localAxis) {
  14853. var result = BABYLON.Vector3.Zero();
  14854. this.getDirectionToRef(localAxis, result);
  14855. return result;
  14856. };
  14857. /**
  14858. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14859. * localAxis is expressed in the mesh local space.
  14860. * result is computed in the Wordl space from the mesh World matrix.
  14861. * Returns the AbstractMesh.
  14862. */
  14863. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14864. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14865. return this;
  14866. };
  14867. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14868. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14869. if (this.getScene().getRenderId() == 0) {
  14870. this.computeWorldMatrix(true);
  14871. }
  14872. var wm = this.getWorldMatrix();
  14873. if (space == BABYLON.Space.WORLD) {
  14874. var tmat = BABYLON.Tmp.Matrix[0];
  14875. wm.invertToRef(tmat);
  14876. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14877. }
  14878. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14879. this._pivotMatrix.m[12] = -point.x;
  14880. this._pivotMatrix.m[13] = -point.y;
  14881. this._pivotMatrix.m[14] = -point.z;
  14882. this._cache.pivotMatrixUpdated = true;
  14883. return this;
  14884. };
  14885. /**
  14886. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14887. */
  14888. AbstractMesh.prototype.getPivotPoint = function () {
  14889. var point = BABYLON.Vector3.Zero();
  14890. this.getPivotPointToRef(point);
  14891. return point;
  14892. };
  14893. /**
  14894. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14895. * Returns the AbstractMesh.
  14896. */
  14897. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14898. result.x = -this._pivotMatrix.m[12];
  14899. result.y = -this._pivotMatrix.m[13];
  14900. result.z = -this._pivotMatrix.m[14];
  14901. return this;
  14902. };
  14903. /**
  14904. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14905. */
  14906. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14907. var point = BABYLON.Vector3.Zero();
  14908. this.getAbsolutePivotPointToRef(point);
  14909. return point;
  14910. };
  14911. /**
  14912. * Defines the passed mesh as the parent of the current mesh.
  14913. * Returns the AbstractMesh.
  14914. */
  14915. AbstractMesh.prototype.setParent = function (mesh) {
  14916. var parent = mesh;
  14917. if (mesh == null) {
  14918. var rotation = BABYLON.Tmp.Quaternion[0];
  14919. var position = BABYLON.Tmp.Vector3[0];
  14920. var scale = BABYLON.Tmp.Vector3[1];
  14921. this.getWorldMatrix().decompose(scale, rotation, position);
  14922. if (this.rotationQuaternion) {
  14923. this.rotationQuaternion.copyFrom(rotation);
  14924. }
  14925. else {
  14926. rotation.toEulerAnglesToRef(this.rotation);
  14927. }
  14928. this.position.x = position.x;
  14929. this.position.y = position.y;
  14930. this.position.z = position.z;
  14931. }
  14932. else {
  14933. var position = BABYLON.Tmp.Vector3[0];
  14934. var m1 = BABYLON.Tmp.Matrix[0];
  14935. parent.getWorldMatrix().invertToRef(m1);
  14936. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14937. this.position.copyFrom(position);
  14938. }
  14939. this.parent = parent;
  14940. return this;
  14941. };
  14942. /**
  14943. * Adds the passed mesh as a child to the current mesh.
  14944. * Returns the AbstractMesh.
  14945. */
  14946. AbstractMesh.prototype.addChild = function (mesh) {
  14947. mesh.setParent(this);
  14948. return this;
  14949. };
  14950. /**
  14951. * Removes the passed mesh from the current mesh children list.
  14952. * Returns the AbstractMesh.
  14953. */
  14954. AbstractMesh.prototype.removeChild = function (mesh) {
  14955. mesh.setParent(null);
  14956. return this;
  14957. };
  14958. /**
  14959. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14960. * Returns the AbstractMesh.
  14961. */
  14962. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14963. result.x = this._pivotMatrix.m[12];
  14964. result.y = this._pivotMatrix.m[13];
  14965. result.z = this._pivotMatrix.m[14];
  14966. this.getPivotPointToRef(result);
  14967. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14968. return this;
  14969. };
  14970. // Facet data
  14971. /**
  14972. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14973. * Returns the AbstractMesh.
  14974. */
  14975. AbstractMesh.prototype._initFacetData = function () {
  14976. if (!this._facetNormals) {
  14977. this._facetNormals = new Array();
  14978. }
  14979. if (!this._facetPositions) {
  14980. this._facetPositions = new Array();
  14981. }
  14982. if (!this._facetPartitioning) {
  14983. this._facetPartitioning = new Array();
  14984. }
  14985. this._facetNb = this.getIndices().length / 3;
  14986. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14987. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14988. for (var f = 0; f < this._facetNb; f++) {
  14989. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14990. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14991. }
  14992. this._facetDataEnabled = true;
  14993. return this;
  14994. };
  14995. /**
  14996. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14997. * This method can be called within the render loop.
  14998. * 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.
  14999. * Returns the AbstractMesh.
  15000. */
  15001. AbstractMesh.prototype.updateFacetData = function () {
  15002. if (!this._facetDataEnabled) {
  15003. this._initFacetData();
  15004. }
  15005. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15006. var indices = this.getIndices();
  15007. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15008. var bInfo = this.getBoundingInfo();
  15009. if (!bInfo) {
  15010. return this;
  15011. }
  15012. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15013. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15014. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15015. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15016. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15017. this._subDiv.max = this._partitioningSubdivisions;
  15018. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15019. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15020. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15021. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15022. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15023. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15024. // set the parameters for ComputeNormals()
  15025. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15026. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15027. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15028. this._facetParameters.bInfo = bInfo;
  15029. this._facetParameters.bbSize = this._bbSize;
  15030. this._facetParameters.subDiv = this._subDiv;
  15031. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15032. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15033. return this;
  15034. };
  15035. /**
  15036. * Returns the facetLocalNormals array.
  15037. * The normals are expressed in the mesh local space.
  15038. */
  15039. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15040. if (!this._facetNormals) {
  15041. this.updateFacetData();
  15042. }
  15043. return this._facetNormals;
  15044. };
  15045. /**
  15046. * Returns the facetLocalPositions array.
  15047. * The facet positions are expressed in the mesh local space.
  15048. */
  15049. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15050. if (!this._facetPositions) {
  15051. this.updateFacetData();
  15052. }
  15053. return this._facetPositions;
  15054. };
  15055. /**
  15056. * Returns the facetLocalPartioning array.
  15057. */
  15058. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15059. if (!this._facetPartitioning) {
  15060. this.updateFacetData();
  15061. }
  15062. return this._facetPartitioning;
  15063. };
  15064. /**
  15065. * Returns the i-th facet position in the world system.
  15066. * This method allocates a new Vector3 per call.
  15067. */
  15068. AbstractMesh.prototype.getFacetPosition = function (i) {
  15069. var pos = BABYLON.Vector3.Zero();
  15070. this.getFacetPositionToRef(i, pos);
  15071. return pos;
  15072. };
  15073. /**
  15074. * Sets the reference Vector3 with the i-th facet position in the world system.
  15075. * Returns the AbstractMesh.
  15076. */
  15077. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15078. var localPos = (this.getFacetLocalPositions())[i];
  15079. var world = this.getWorldMatrix();
  15080. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15081. return this;
  15082. };
  15083. /**
  15084. * Returns the i-th facet normal in the world system.
  15085. * This method allocates a new Vector3 per call.
  15086. */
  15087. AbstractMesh.prototype.getFacetNormal = function (i) {
  15088. var norm = BABYLON.Vector3.Zero();
  15089. this.getFacetNormalToRef(i, norm);
  15090. return norm;
  15091. };
  15092. /**
  15093. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15094. * Returns the AbstractMesh.
  15095. */
  15096. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15097. var localNorm = (this.getFacetLocalNormals())[i];
  15098. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15099. return this;
  15100. };
  15101. /**
  15102. * 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).
  15103. */
  15104. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15105. var bInfo = this.getBoundingInfo();
  15106. if (!bInfo) {
  15107. return null;
  15108. }
  15109. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15110. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15111. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15112. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15113. return null;
  15114. }
  15115. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15116. };
  15117. /**
  15118. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15119. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15120. * 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.
  15121. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15122. * 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.
  15123. */
  15124. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15125. if (checkFace === void 0) { checkFace = false; }
  15126. if (facing === void 0) { facing = true; }
  15127. var world = this.getWorldMatrix();
  15128. var invMat = BABYLON.Tmp.Matrix[5];
  15129. world.invertToRef(invMat);
  15130. var invVect = BABYLON.Tmp.Vector3[8];
  15131. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15132. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15133. if (projected) {
  15134. // tranform the local computed projected vector to world coordinates
  15135. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15136. }
  15137. return closest;
  15138. };
  15139. /**
  15140. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15141. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15142. * 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.
  15143. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15144. * 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.
  15145. */
  15146. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15147. if (checkFace === void 0) { checkFace = false; }
  15148. if (facing === void 0) { facing = true; }
  15149. var closest = null;
  15150. var tmpx = 0.0;
  15151. var tmpy = 0.0;
  15152. var tmpz = 0.0;
  15153. var d = 0.0; // tmp dot facet normal * facet position
  15154. var t0 = 0.0;
  15155. var projx = 0.0;
  15156. var projy = 0.0;
  15157. var projz = 0.0;
  15158. // Get all the facets in the same partitioning block than (x, y, z)
  15159. var facetPositions = this.getFacetLocalPositions();
  15160. var facetNormals = this.getFacetLocalNormals();
  15161. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15162. if (!facetsInBlock) {
  15163. return null;
  15164. }
  15165. // Get the closest facet to (x, y, z)
  15166. var shortest = Number.MAX_VALUE; // init distance vars
  15167. var tmpDistance = shortest;
  15168. var fib; // current facet in the block
  15169. var norm; // current facet normal
  15170. var p0; // current facet barycenter position
  15171. // loop on all the facets in the current partitioning block
  15172. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15173. fib = facetsInBlock[idx];
  15174. norm = facetNormals[fib];
  15175. p0 = facetPositions[fib];
  15176. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15177. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15178. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15179. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15180. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15181. projx = x + norm.x * t0;
  15182. projy = y + norm.y * t0;
  15183. projz = z + norm.z * t0;
  15184. tmpx = projx - x;
  15185. tmpy = projy - y;
  15186. tmpz = projz - z;
  15187. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15188. if (tmpDistance < shortest) {
  15189. shortest = tmpDistance;
  15190. closest = fib;
  15191. if (projected) {
  15192. projected.x = projx;
  15193. projected.y = projy;
  15194. projected.z = projz;
  15195. }
  15196. }
  15197. }
  15198. }
  15199. return closest;
  15200. };
  15201. /**
  15202. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15203. */
  15204. AbstractMesh.prototype.getFacetDataParameters = function () {
  15205. return this._facetParameters;
  15206. };
  15207. /**
  15208. * Disables the feature FacetData and frees the related memory.
  15209. * Returns the AbstractMesh.
  15210. */
  15211. AbstractMesh.prototype.disableFacetData = function () {
  15212. if (this._facetDataEnabled) {
  15213. this._facetDataEnabled = false;
  15214. this._facetPositions = new Array();
  15215. ;
  15216. this._facetNormals = new Array();
  15217. ;
  15218. this._facetPartitioning = new Array();
  15219. ;
  15220. this._facetParameters = null;
  15221. }
  15222. return this;
  15223. };
  15224. /**
  15225. * Creates new normals data for the mesh.
  15226. * @param updatable.
  15227. */
  15228. AbstractMesh.prototype.createNormals = function (updatable) {
  15229. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15230. var indices = this.getIndices();
  15231. var normals;
  15232. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15233. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15234. }
  15235. else {
  15236. normals = [];
  15237. }
  15238. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15239. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15240. };
  15241. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15242. var engine = this.getEngine();
  15243. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15244. this._isOccluded = false;
  15245. return;
  15246. }
  15247. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15248. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15249. if (isOcclusionQueryAvailable) {
  15250. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15251. this._isOcclusionQueryInProgress = false;
  15252. this._occlusionInternalRetryCounter = 0;
  15253. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15254. }
  15255. else {
  15256. this._occlusionInternalRetryCounter++;
  15257. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15258. this._isOcclusionQueryInProgress = false;
  15259. this._occlusionInternalRetryCounter = 0;
  15260. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15261. // if strict continue the last state of the object.
  15262. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15263. }
  15264. else {
  15265. return;
  15266. }
  15267. }
  15268. }
  15269. var scene = this.getScene();
  15270. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15271. if (!this._occlusionQuery) {
  15272. this._occlusionQuery = engine.createQuery();
  15273. }
  15274. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15275. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15276. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15277. this._isOcclusionQueryInProgress = true;
  15278. };
  15279. // Statics
  15280. AbstractMesh._BILLBOARDMODE_NONE = 0;
  15281. AbstractMesh._BILLBOARDMODE_X = 1;
  15282. AbstractMesh._BILLBOARDMODE_Y = 2;
  15283. AbstractMesh._BILLBOARDMODE_Z = 4;
  15284. AbstractMesh._BILLBOARDMODE_ALL = 7;
  15285. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15286. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15287. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15288. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15289. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15290. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  15291. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15292. return AbstractMesh;
  15293. }(BABYLON.Node));
  15294. BABYLON.AbstractMesh = AbstractMesh;
  15295. })(BABYLON || (BABYLON = {}));
  15296. //# sourceMappingURL=babylon.abstractMesh.js.map
  15297. var BABYLON;
  15298. (function (BABYLON) {
  15299. var Light = /** @class */ (function (_super) {
  15300. __extends(Light, _super);
  15301. /**
  15302. * Creates a Light object in the scene.
  15303. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15304. */
  15305. function Light(name, scene) {
  15306. var _this = _super.call(this, name, scene) || this;
  15307. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15308. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15309. _this.intensity = 1.0;
  15310. _this.range = Number.MAX_VALUE;
  15311. /**
  15312. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15313. * of light.
  15314. */
  15315. _this._photometricScale = 1.0;
  15316. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15317. _this._radius = 0.00001;
  15318. _this.renderPriority = 0;
  15319. /**
  15320. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15321. * the current shadow generator.
  15322. */
  15323. _this.shadowEnabled = true;
  15324. _this._excludeWithLayerMask = 0;
  15325. _this._includeOnlyWithLayerMask = 0;
  15326. _this._lightmapMode = 0;
  15327. _this._excludedMeshesIds = new Array();
  15328. _this._includedOnlyMeshesIds = new Array();
  15329. _this.getScene().addLight(_this);
  15330. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15331. _this._buildUniformLayout();
  15332. _this.includedOnlyMeshes = new Array();
  15333. _this.excludedMeshes = new Array();
  15334. _this._resyncMeshes();
  15335. return _this;
  15336. }
  15337. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15338. /**
  15339. * If every light affecting the material is in this lightmapMode,
  15340. * material.lightmapTexture adds or multiplies
  15341. * (depends on material.useLightmapAsShadowmap)
  15342. * after every other light calculations.
  15343. */
  15344. get: function () {
  15345. return Light._LIGHTMAP_DEFAULT;
  15346. },
  15347. enumerable: true,
  15348. configurable: true
  15349. });
  15350. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15351. /**
  15352. * material.lightmapTexture as only diffuse lighting from this light
  15353. * adds pnly specular lighting from this light
  15354. * adds dynamic shadows
  15355. */
  15356. get: function () {
  15357. return Light._LIGHTMAP_SPECULAR;
  15358. },
  15359. enumerable: true,
  15360. configurable: true
  15361. });
  15362. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15363. /**
  15364. * material.lightmapTexture as only lighting
  15365. * no light calculation from this light
  15366. * only adds dynamic shadows from this light
  15367. */
  15368. get: function () {
  15369. return Light._LIGHTMAP_SHADOWSONLY;
  15370. },
  15371. enumerable: true,
  15372. configurable: true
  15373. });
  15374. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15375. /**
  15376. * Each light type uses the default quantity according to its type:
  15377. * point/spot lights use luminous intensity
  15378. * directional lights use illuminance
  15379. */
  15380. get: function () {
  15381. return Light._INTENSITYMODE_AUTOMATIC;
  15382. },
  15383. enumerable: true,
  15384. configurable: true
  15385. });
  15386. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15387. /**
  15388. * lumen (lm)
  15389. */
  15390. get: function () {
  15391. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15392. },
  15393. enumerable: true,
  15394. configurable: true
  15395. });
  15396. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15397. /**
  15398. * candela (lm/sr)
  15399. */
  15400. get: function () {
  15401. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15402. },
  15403. enumerable: true,
  15404. configurable: true
  15405. });
  15406. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15407. /**
  15408. * lux (lm/m^2)
  15409. */
  15410. get: function () {
  15411. return Light._INTENSITYMODE_ILLUMINANCE;
  15412. },
  15413. enumerable: true,
  15414. configurable: true
  15415. });
  15416. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15417. /**
  15418. * nit (cd/m^2)
  15419. */
  15420. get: function () {
  15421. return Light._INTENSITYMODE_LUMINANCE;
  15422. },
  15423. enumerable: true,
  15424. configurable: true
  15425. });
  15426. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15427. /**
  15428. * Light type const id of the point light.
  15429. */
  15430. get: function () {
  15431. return Light._LIGHTTYPEID_POINTLIGHT;
  15432. },
  15433. enumerable: true,
  15434. configurable: true
  15435. });
  15436. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15437. /**
  15438. * Light type const id of the directional light.
  15439. */
  15440. get: function () {
  15441. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15442. },
  15443. enumerable: true,
  15444. configurable: true
  15445. });
  15446. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15447. /**
  15448. * Light type const id of the spot light.
  15449. */
  15450. get: function () {
  15451. return Light._LIGHTTYPEID_SPOTLIGHT;
  15452. },
  15453. enumerable: true,
  15454. configurable: true
  15455. });
  15456. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15457. /**
  15458. * Light type const id of the hemispheric light.
  15459. */
  15460. get: function () {
  15461. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15462. },
  15463. enumerable: true,
  15464. configurable: true
  15465. });
  15466. Object.defineProperty(Light.prototype, "intensityMode", {
  15467. /**
  15468. * Gets the photometric scale used to interpret the intensity.
  15469. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15470. */
  15471. get: function () {
  15472. return this._intensityMode;
  15473. },
  15474. /**
  15475. * Sets the photometric scale used to interpret the intensity.
  15476. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15477. */
  15478. set: function (value) {
  15479. this._intensityMode = value;
  15480. this._computePhotometricScale();
  15481. },
  15482. enumerable: true,
  15483. configurable: true
  15484. });
  15485. ;
  15486. ;
  15487. Object.defineProperty(Light.prototype, "radius", {
  15488. /**
  15489. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15490. */
  15491. get: function () {
  15492. return this._radius;
  15493. },
  15494. /**
  15495. * sets the light radius used by PBR Materials to simulate soft area lights.
  15496. */
  15497. set: function (value) {
  15498. this._radius = value;
  15499. this._computePhotometricScale();
  15500. },
  15501. enumerable: true,
  15502. configurable: true
  15503. });
  15504. ;
  15505. ;
  15506. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15507. get: function () {
  15508. return this._includedOnlyMeshes;
  15509. },
  15510. set: function (value) {
  15511. this._includedOnlyMeshes = value;
  15512. this._hookArrayForIncludedOnly(value);
  15513. },
  15514. enumerable: true,
  15515. configurable: true
  15516. });
  15517. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15518. get: function () {
  15519. return this._excludedMeshes;
  15520. },
  15521. set: function (value) {
  15522. this._excludedMeshes = value;
  15523. this._hookArrayForExcluded(value);
  15524. },
  15525. enumerable: true,
  15526. configurable: true
  15527. });
  15528. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15529. get: function () {
  15530. return this._excludeWithLayerMask;
  15531. },
  15532. set: function (value) {
  15533. this._excludeWithLayerMask = value;
  15534. this._resyncMeshes();
  15535. },
  15536. enumerable: true,
  15537. configurable: true
  15538. });
  15539. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15540. get: function () {
  15541. return this._includeOnlyWithLayerMask;
  15542. },
  15543. set: function (value) {
  15544. this._includeOnlyWithLayerMask = value;
  15545. this._resyncMeshes();
  15546. },
  15547. enumerable: true,
  15548. configurable: true
  15549. });
  15550. Object.defineProperty(Light.prototype, "lightmapMode", {
  15551. get: function () {
  15552. return this._lightmapMode;
  15553. },
  15554. set: function (value) {
  15555. if (this._lightmapMode === value) {
  15556. return;
  15557. }
  15558. this._lightmapMode = value;
  15559. this._markMeshesAsLightDirty();
  15560. },
  15561. enumerable: true,
  15562. configurable: true
  15563. });
  15564. Light.prototype._buildUniformLayout = function () {
  15565. // Overridden
  15566. };
  15567. /**
  15568. * Returns the string "Light".
  15569. */
  15570. Light.prototype.getClassName = function () {
  15571. return "Light";
  15572. };
  15573. /**
  15574. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15575. */
  15576. Light.prototype.toString = function (fullDetails) {
  15577. var ret = "Name: " + this.name;
  15578. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15579. if (this.animations) {
  15580. for (var i = 0; i < this.animations.length; i++) {
  15581. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15582. }
  15583. }
  15584. if (fullDetails) {
  15585. }
  15586. return ret;
  15587. };
  15588. /**
  15589. * Set the enabled state of this node.
  15590. * @param {boolean} value - the new enabled state
  15591. * @see isEnabled
  15592. */
  15593. Light.prototype.setEnabled = function (value) {
  15594. _super.prototype.setEnabled.call(this, value);
  15595. this._resyncMeshes();
  15596. };
  15597. /**
  15598. * Returns the Light associated shadow generator.
  15599. */
  15600. Light.prototype.getShadowGenerator = function () {
  15601. return this._shadowGenerator;
  15602. };
  15603. /**
  15604. * Returns a Vector3, the absolute light position in the World.
  15605. */
  15606. Light.prototype.getAbsolutePosition = function () {
  15607. return BABYLON.Vector3.Zero();
  15608. };
  15609. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15610. };
  15611. Light.prototype._getWorldMatrix = function () {
  15612. return BABYLON.Matrix.Identity();
  15613. };
  15614. /**
  15615. * Boolean : True if the light will affect the passed mesh.
  15616. */
  15617. Light.prototype.canAffectMesh = function (mesh) {
  15618. if (!mesh) {
  15619. return true;
  15620. }
  15621. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15622. return false;
  15623. }
  15624. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15625. return false;
  15626. }
  15627. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15628. return false;
  15629. }
  15630. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15631. return false;
  15632. }
  15633. return true;
  15634. };
  15635. /**
  15636. * Returns the light World matrix.
  15637. */
  15638. Light.prototype.getWorldMatrix = function () {
  15639. this._currentRenderId = this.getScene().getRenderId();
  15640. var worldMatrix = this._getWorldMatrix();
  15641. if (this.parent && this.parent.getWorldMatrix) {
  15642. if (!this._parentedWorldMatrix) {
  15643. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15644. }
  15645. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15646. this._markSyncedWithParent();
  15647. return this._parentedWorldMatrix;
  15648. }
  15649. return worldMatrix;
  15650. };
  15651. /**
  15652. * Sort function to order lights for rendering.
  15653. * @param a First Light object to compare to second.
  15654. * @param b Second Light object to compare first.
  15655. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15656. */
  15657. Light.compareLightsPriority = function (a, b) {
  15658. //shadow-casting lights have priority over non-shadow-casting lights
  15659. //the renderPrioirty is a secondary sort criterion
  15660. if (a.shadowEnabled !== b.shadowEnabled) {
  15661. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15662. }
  15663. return b.renderPriority - a.renderPriority;
  15664. };
  15665. /**
  15666. * Disposes the light.
  15667. */
  15668. Light.prototype.dispose = function () {
  15669. if (this._shadowGenerator) {
  15670. this._shadowGenerator.dispose();
  15671. this._shadowGenerator = null;
  15672. }
  15673. // Animations
  15674. this.getScene().stopAnimation(this);
  15675. // Remove from meshes
  15676. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15677. var mesh = _a[_i];
  15678. mesh._removeLightSource(this);
  15679. }
  15680. this._uniformBuffer.dispose();
  15681. // Remove from scene
  15682. this.getScene().removeLight(this);
  15683. _super.prototype.dispose.call(this);
  15684. };
  15685. /**
  15686. * Returns the light type ID (integer).
  15687. */
  15688. Light.prototype.getTypeID = function () {
  15689. return 0;
  15690. };
  15691. /**
  15692. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15693. */
  15694. Light.prototype.getScaledIntensity = function () {
  15695. return this._photometricScale * this.intensity;
  15696. };
  15697. /**
  15698. * Returns a new Light object, named "name", from the current one.
  15699. */
  15700. Light.prototype.clone = function (name) {
  15701. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15702. if (!constructor) {
  15703. return null;
  15704. }
  15705. return BABYLON.SerializationHelper.Clone(constructor, this);
  15706. };
  15707. /**
  15708. * Serializes the current light into a Serialization object.
  15709. * Returns the serialized object.
  15710. */
  15711. Light.prototype.serialize = function () {
  15712. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15713. // Type
  15714. serializationObject.type = this.getTypeID();
  15715. // Parent
  15716. if (this.parent) {
  15717. serializationObject.parentId = this.parent.id;
  15718. }
  15719. // Inclusion / exclusions
  15720. if (this.excludedMeshes.length > 0) {
  15721. serializationObject.excludedMeshesIds = [];
  15722. this.excludedMeshes.forEach(function (mesh) {
  15723. serializationObject.excludedMeshesIds.push(mesh.id);
  15724. });
  15725. }
  15726. if (this.includedOnlyMeshes.length > 0) {
  15727. serializationObject.includedOnlyMeshesIds = [];
  15728. this.includedOnlyMeshes.forEach(function (mesh) {
  15729. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15730. });
  15731. }
  15732. // Animations
  15733. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15734. serializationObject.ranges = this.serializeAnimationRanges();
  15735. return serializationObject;
  15736. };
  15737. /**
  15738. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15739. * This new light is named "name" and added to the passed scene.
  15740. */
  15741. Light.GetConstructorFromName = function (type, name, scene) {
  15742. switch (type) {
  15743. case 0:
  15744. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15745. case 1:
  15746. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15747. case 2:
  15748. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15749. case 3:
  15750. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15751. }
  15752. return null;
  15753. };
  15754. /**
  15755. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15756. */
  15757. Light.Parse = function (parsedLight, scene) {
  15758. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15759. if (!constructor) {
  15760. return null;
  15761. }
  15762. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15763. // Inclusion / exclusions
  15764. if (parsedLight.excludedMeshesIds) {
  15765. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15766. }
  15767. if (parsedLight.includedOnlyMeshesIds) {
  15768. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15769. }
  15770. // Parent
  15771. if (parsedLight.parentId) {
  15772. light._waitingParentId = parsedLight.parentId;
  15773. }
  15774. // Animations
  15775. if (parsedLight.animations) {
  15776. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15777. var parsedAnimation = parsedLight.animations[animationIndex];
  15778. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15779. }
  15780. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15781. }
  15782. if (parsedLight.autoAnimate) {
  15783. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15784. }
  15785. return light;
  15786. };
  15787. Light.prototype._hookArrayForExcluded = function (array) {
  15788. var _this = this;
  15789. var oldPush = array.push;
  15790. array.push = function () {
  15791. var items = [];
  15792. for (var _i = 0; _i < arguments.length; _i++) {
  15793. items[_i] = arguments[_i];
  15794. }
  15795. var result = oldPush.apply(array, items);
  15796. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15797. var item = items_1[_a];
  15798. item._resyncLighSource(_this);
  15799. }
  15800. return result;
  15801. };
  15802. var oldSplice = array.splice;
  15803. array.splice = function (index, deleteCount) {
  15804. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15805. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15806. var item = deleted_1[_i];
  15807. item._resyncLighSource(_this);
  15808. }
  15809. return deleted;
  15810. };
  15811. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15812. var item = array_1[_i];
  15813. item._resyncLighSource(this);
  15814. }
  15815. };
  15816. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15817. var _this = this;
  15818. var oldPush = array.push;
  15819. array.push = function () {
  15820. var items = [];
  15821. for (var _i = 0; _i < arguments.length; _i++) {
  15822. items[_i] = arguments[_i];
  15823. }
  15824. var result = oldPush.apply(array, items);
  15825. _this._resyncMeshes();
  15826. return result;
  15827. };
  15828. var oldSplice = array.splice;
  15829. array.splice = function (index, deleteCount) {
  15830. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15831. _this._resyncMeshes();
  15832. return deleted;
  15833. };
  15834. this._resyncMeshes();
  15835. };
  15836. Light.prototype._resyncMeshes = function () {
  15837. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15838. var mesh = _a[_i];
  15839. mesh._resyncLighSource(this);
  15840. }
  15841. };
  15842. Light.prototype._markMeshesAsLightDirty = function () {
  15843. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15844. var mesh = _a[_i];
  15845. if (mesh._lightSources.indexOf(this) !== -1) {
  15846. mesh._markSubMeshesAsLightDirty();
  15847. }
  15848. }
  15849. };
  15850. /**
  15851. * Recomputes the cached photometric scale if needed.
  15852. */
  15853. Light.prototype._computePhotometricScale = function () {
  15854. this._photometricScale = this._getPhotometricScale();
  15855. this.getScene().resetCachedMaterial();
  15856. };
  15857. /**
  15858. * Returns the Photometric Scale according to the light type and intensity mode.
  15859. */
  15860. Light.prototype._getPhotometricScale = function () {
  15861. var photometricScale = 0.0;
  15862. var lightTypeID = this.getTypeID();
  15863. //get photometric mode
  15864. var photometricMode = this.intensityMode;
  15865. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15866. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15867. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15868. }
  15869. else {
  15870. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15871. }
  15872. }
  15873. //compute photometric scale
  15874. switch (lightTypeID) {
  15875. case Light.LIGHTTYPEID_POINTLIGHT:
  15876. case Light.LIGHTTYPEID_SPOTLIGHT:
  15877. switch (photometricMode) {
  15878. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15879. photometricScale = 1.0 / (4.0 * Math.PI);
  15880. break;
  15881. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15882. photometricScale = 1.0;
  15883. break;
  15884. case Light.INTENSITYMODE_LUMINANCE:
  15885. photometricScale = this.radius * this.radius;
  15886. break;
  15887. }
  15888. break;
  15889. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15890. switch (photometricMode) {
  15891. case Light.INTENSITYMODE_ILLUMINANCE:
  15892. photometricScale = 1.0;
  15893. break;
  15894. case Light.INTENSITYMODE_LUMINANCE:
  15895. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15896. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15897. var apexAngleRadians = this.radius;
  15898. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15899. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15900. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15901. photometricScale = solidAngle;
  15902. break;
  15903. }
  15904. break;
  15905. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15906. // No fall off in hemisperic light.
  15907. photometricScale = 1.0;
  15908. break;
  15909. }
  15910. return photometricScale;
  15911. };
  15912. Light.prototype._reorderLightsInScene = function () {
  15913. var scene = this.getScene();
  15914. if (this._renderPriority != 0) {
  15915. scene.requireLightSorting = true;
  15916. }
  15917. this.getScene().sortLightsByPriority();
  15918. };
  15919. //lightmapMode Consts
  15920. Light._LIGHTMAP_DEFAULT = 0;
  15921. Light._LIGHTMAP_SPECULAR = 1;
  15922. Light._LIGHTMAP_SHADOWSONLY = 2;
  15923. // Intensity Mode Consts
  15924. Light._INTENSITYMODE_AUTOMATIC = 0;
  15925. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15926. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15927. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15928. Light._INTENSITYMODE_LUMINANCE = 4;
  15929. // Light types ids const.
  15930. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15931. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15932. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15933. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15934. __decorate([
  15935. BABYLON.serializeAsColor3()
  15936. ], Light.prototype, "diffuse", void 0);
  15937. __decorate([
  15938. BABYLON.serializeAsColor3()
  15939. ], Light.prototype, "specular", void 0);
  15940. __decorate([
  15941. BABYLON.serialize()
  15942. ], Light.prototype, "intensity", void 0);
  15943. __decorate([
  15944. BABYLON.serialize()
  15945. ], Light.prototype, "range", void 0);
  15946. __decorate([
  15947. BABYLON.serialize()
  15948. ], Light.prototype, "intensityMode", null);
  15949. __decorate([
  15950. BABYLON.serialize()
  15951. ], Light.prototype, "radius", null);
  15952. __decorate([
  15953. BABYLON.serialize()
  15954. ], Light.prototype, "_renderPriority", void 0);
  15955. __decorate([
  15956. BABYLON.expandToProperty("_reorderLightsInScene")
  15957. ], Light.prototype, "renderPriority", void 0);
  15958. __decorate([
  15959. BABYLON.serialize()
  15960. ], Light.prototype, "shadowEnabled", void 0);
  15961. __decorate([
  15962. BABYLON.serialize("excludeWithLayerMask")
  15963. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15964. __decorate([
  15965. BABYLON.serialize("includeOnlyWithLayerMask")
  15966. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15967. __decorate([
  15968. BABYLON.serialize("lightmapMode")
  15969. ], Light.prototype, "_lightmapMode", void 0);
  15970. return Light;
  15971. }(BABYLON.Node));
  15972. BABYLON.Light = Light;
  15973. })(BABYLON || (BABYLON = {}));
  15974. //# sourceMappingURL=babylon.light.js.map
  15975. var BABYLON;
  15976. (function (BABYLON) {
  15977. var Camera = /** @class */ (function (_super) {
  15978. __extends(Camera, _super);
  15979. function Camera(name, position, scene) {
  15980. var _this = _super.call(this, name, scene) || this;
  15981. _this.upVector = BABYLON.Vector3.Up();
  15982. _this.orthoLeft = null;
  15983. _this.orthoRight = null;
  15984. _this.orthoBottom = null;
  15985. _this.orthoTop = null;
  15986. _this.fov = 0.8;
  15987. _this.minZ = 1;
  15988. _this.maxZ = 10000.0;
  15989. _this.inertia = 0.9;
  15990. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15991. _this.isIntermediate = false;
  15992. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15993. _this.layerMask = 0x0FFFFFFF;
  15994. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15995. // Camera rig members
  15996. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15997. _this._rigCameras = new Array();
  15998. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15999. _this._skipRendering = false;
  16000. _this.customRenderTargets = new Array();
  16001. // Observables
  16002. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16003. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16004. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16005. _this.onRestoreStateObservable = new BABYLON.Observable();
  16006. // Cache
  16007. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16008. _this._projectionMatrix = new BABYLON.Matrix();
  16009. _this._doNotComputeProjectionMatrix = false;
  16010. _this._postProcesses = new Array();
  16011. _this._transformMatrix = BABYLON.Matrix.Zero();
  16012. _this._activeMeshes = new BABYLON.SmartArray(256);
  16013. _this._globalPosition = BABYLON.Vector3.Zero();
  16014. _this._refreshFrustumPlanes = true;
  16015. _this.getScene().addCamera(_this);
  16016. if (!_this.getScene().activeCamera) {
  16017. _this.getScene().activeCamera = _this;
  16018. }
  16019. _this.position = position;
  16020. return _this;
  16021. }
  16022. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16023. get: function () {
  16024. return Camera._PERSPECTIVE_CAMERA;
  16025. },
  16026. enumerable: true,
  16027. configurable: true
  16028. });
  16029. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16030. get: function () {
  16031. return Camera._ORTHOGRAPHIC_CAMERA;
  16032. },
  16033. enumerable: true,
  16034. configurable: true
  16035. });
  16036. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16037. get: function () {
  16038. return Camera._FOVMODE_VERTICAL_FIXED;
  16039. },
  16040. enumerable: true,
  16041. configurable: true
  16042. });
  16043. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16044. get: function () {
  16045. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16046. },
  16047. enumerable: true,
  16048. configurable: true
  16049. });
  16050. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16051. get: function () {
  16052. return Camera._RIG_MODE_NONE;
  16053. },
  16054. enumerable: true,
  16055. configurable: true
  16056. });
  16057. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16058. get: function () {
  16059. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16060. },
  16061. enumerable: true,
  16062. configurable: true
  16063. });
  16064. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16065. get: function () {
  16066. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16067. },
  16068. enumerable: true,
  16069. configurable: true
  16070. });
  16071. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16072. get: function () {
  16073. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16074. },
  16075. enumerable: true,
  16076. configurable: true
  16077. });
  16078. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16079. get: function () {
  16080. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16081. },
  16082. enumerable: true,
  16083. configurable: true
  16084. });
  16085. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16086. get: function () {
  16087. return Camera._RIG_MODE_VR;
  16088. },
  16089. enumerable: true,
  16090. configurable: true
  16091. });
  16092. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16093. get: function () {
  16094. return Camera._RIG_MODE_WEBVR;
  16095. },
  16096. enumerable: true,
  16097. configurable: true
  16098. });
  16099. /**
  16100. * Store current camera state (fov, position, etc..)
  16101. */
  16102. Camera.prototype.storeState = function () {
  16103. this._stateStored = true;
  16104. this._storedFov = this.fov;
  16105. return this;
  16106. };
  16107. /**
  16108. * Restores the camera state values if it has been stored. You must call storeState() first
  16109. */
  16110. Camera.prototype._restoreStateValues = function () {
  16111. if (!this._stateStored) {
  16112. return false;
  16113. }
  16114. this.fov = this._storedFov;
  16115. return true;
  16116. };
  16117. /**
  16118. * Restored camera state. You must call storeState() first
  16119. */
  16120. Camera.prototype.restoreState = function () {
  16121. if (this._restoreStateValues()) {
  16122. this.onRestoreStateObservable.notifyObservers(this);
  16123. return true;
  16124. }
  16125. return false;
  16126. };
  16127. Camera.prototype.getClassName = function () {
  16128. return "Camera";
  16129. };
  16130. /**
  16131. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16132. */
  16133. Camera.prototype.toString = function (fullDetails) {
  16134. var ret = "Name: " + this.name;
  16135. ret += ", type: " + this.getClassName();
  16136. if (this.animations) {
  16137. for (var i = 0; i < this.animations.length; i++) {
  16138. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16139. }
  16140. }
  16141. if (fullDetails) {
  16142. }
  16143. return ret;
  16144. };
  16145. Object.defineProperty(Camera.prototype, "globalPosition", {
  16146. get: function () {
  16147. return this._globalPosition;
  16148. },
  16149. enumerable: true,
  16150. configurable: true
  16151. });
  16152. Camera.prototype.getActiveMeshes = function () {
  16153. return this._activeMeshes;
  16154. };
  16155. Camera.prototype.isActiveMesh = function (mesh) {
  16156. return (this._activeMeshes.indexOf(mesh) !== -1);
  16157. };
  16158. //Cache
  16159. Camera.prototype._initCache = function () {
  16160. _super.prototype._initCache.call(this);
  16161. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16162. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16163. this._cache.mode = undefined;
  16164. this._cache.minZ = undefined;
  16165. this._cache.maxZ = undefined;
  16166. this._cache.fov = undefined;
  16167. this._cache.fovMode = undefined;
  16168. this._cache.aspectRatio = undefined;
  16169. this._cache.orthoLeft = undefined;
  16170. this._cache.orthoRight = undefined;
  16171. this._cache.orthoBottom = undefined;
  16172. this._cache.orthoTop = undefined;
  16173. this._cache.renderWidth = undefined;
  16174. this._cache.renderHeight = undefined;
  16175. };
  16176. Camera.prototype._updateCache = function (ignoreParentClass) {
  16177. if (!ignoreParentClass) {
  16178. _super.prototype._updateCache.call(this);
  16179. }
  16180. this._cache.position.copyFrom(this.position);
  16181. this._cache.upVector.copyFrom(this.upVector);
  16182. };
  16183. // Synchronized
  16184. Camera.prototype._isSynchronized = function () {
  16185. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16186. };
  16187. Camera.prototype._isSynchronizedViewMatrix = function () {
  16188. if (!_super.prototype._isSynchronized.call(this))
  16189. return false;
  16190. return this._cache.position.equals(this.position)
  16191. && this._cache.upVector.equals(this.upVector)
  16192. && this.isSynchronizedWithParent();
  16193. };
  16194. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16195. var check = this._cache.mode === this.mode
  16196. && this._cache.minZ === this.minZ
  16197. && this._cache.maxZ === this.maxZ;
  16198. if (!check) {
  16199. return false;
  16200. }
  16201. var engine = this.getEngine();
  16202. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16203. check = this._cache.fov === this.fov
  16204. && this._cache.fovMode === this.fovMode
  16205. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16206. }
  16207. else {
  16208. check = this._cache.orthoLeft === this.orthoLeft
  16209. && this._cache.orthoRight === this.orthoRight
  16210. && this._cache.orthoBottom === this.orthoBottom
  16211. && this._cache.orthoTop === this.orthoTop
  16212. && this._cache.renderWidth === engine.getRenderWidth()
  16213. && this._cache.renderHeight === engine.getRenderHeight();
  16214. }
  16215. return check;
  16216. };
  16217. // Controls
  16218. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16219. };
  16220. Camera.prototype.detachControl = function (element) {
  16221. };
  16222. Camera.prototype.update = function () {
  16223. this._checkInputs();
  16224. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16225. this._updateRigCameras();
  16226. }
  16227. };
  16228. Camera.prototype._checkInputs = function () {
  16229. this.onAfterCheckInputsObservable.notifyObservers(this);
  16230. };
  16231. Object.defineProperty(Camera.prototype, "rigCameras", {
  16232. get: function () {
  16233. return this._rigCameras;
  16234. },
  16235. enumerable: true,
  16236. configurable: true
  16237. });
  16238. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16239. get: function () {
  16240. return this._rigPostProcess;
  16241. },
  16242. enumerable: true,
  16243. configurable: true
  16244. });
  16245. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16246. // invalidate framebuffer
  16247. if (this._postProcesses.length > 0) {
  16248. this._postProcesses[0].markTextureDirty();
  16249. }
  16250. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16251. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16252. var cam = this._rigCameras[i];
  16253. var rigPostProcess = cam._rigPostProcess;
  16254. // for VR rig, there does not have to be a post process
  16255. if (rigPostProcess) {
  16256. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16257. if (isPass) {
  16258. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16259. cam.isIntermediate = this._postProcesses.length === 0;
  16260. }
  16261. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16262. rigPostProcess.markTextureDirty();
  16263. }
  16264. else {
  16265. cam._postProcesses = this._postProcesses.slice(0);
  16266. }
  16267. }
  16268. };
  16269. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16270. if (insertAt === void 0) { insertAt = null; }
  16271. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16272. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16273. return 0;
  16274. }
  16275. if (insertAt == null || insertAt < 0) {
  16276. this._postProcesses.push(postProcess);
  16277. }
  16278. else {
  16279. this._postProcesses.splice(insertAt, 0, postProcess);
  16280. }
  16281. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16282. return this._postProcesses.indexOf(postProcess);
  16283. };
  16284. Camera.prototype.detachPostProcess = function (postProcess) {
  16285. var idx = this._postProcesses.indexOf(postProcess);
  16286. if (idx !== -1) {
  16287. this._postProcesses.splice(idx, 1);
  16288. }
  16289. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16290. };
  16291. Camera.prototype.getWorldMatrix = function () {
  16292. if (!this._worldMatrix) {
  16293. this._worldMatrix = BABYLON.Matrix.Identity();
  16294. }
  16295. var viewMatrix = this.getViewMatrix();
  16296. viewMatrix.invertToRef(this._worldMatrix);
  16297. return this._worldMatrix;
  16298. };
  16299. Camera.prototype._getViewMatrix = function () {
  16300. return BABYLON.Matrix.Identity();
  16301. };
  16302. Camera.prototype.getViewMatrix = function (force) {
  16303. if (!force && this._isSynchronizedViewMatrix()) {
  16304. return this._computedViewMatrix;
  16305. }
  16306. this.updateCache();
  16307. this._computedViewMatrix = this._getViewMatrix();
  16308. this._currentRenderId = this.getScene().getRenderId();
  16309. this._refreshFrustumPlanes = true;
  16310. if (!this.parent || !this.parent.getWorldMatrix) {
  16311. this._globalPosition.copyFrom(this.position);
  16312. }
  16313. else {
  16314. if (!this._worldMatrix) {
  16315. this._worldMatrix = BABYLON.Matrix.Identity();
  16316. }
  16317. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16318. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16319. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16320. this._computedViewMatrix.invert();
  16321. this._markSyncedWithParent();
  16322. }
  16323. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16324. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16325. }
  16326. this.onViewMatrixChangedObservable.notifyObservers(this);
  16327. return this._computedViewMatrix;
  16328. };
  16329. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16330. this._doNotComputeProjectionMatrix = true;
  16331. if (projection !== undefined) {
  16332. this._projectionMatrix = projection;
  16333. }
  16334. };
  16335. ;
  16336. Camera.prototype.unfreezeProjectionMatrix = function () {
  16337. this._doNotComputeProjectionMatrix = false;
  16338. };
  16339. ;
  16340. Camera.prototype.getProjectionMatrix = function (force) {
  16341. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16342. return this._projectionMatrix;
  16343. }
  16344. // Cache
  16345. this._cache.mode = this.mode;
  16346. this._cache.minZ = this.minZ;
  16347. this._cache.maxZ = this.maxZ;
  16348. // Matrix
  16349. this._refreshFrustumPlanes = true;
  16350. var engine = this.getEngine();
  16351. var scene = this.getScene();
  16352. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16353. this._cache.fov = this.fov;
  16354. this._cache.fovMode = this.fovMode;
  16355. this._cache.aspectRatio = engine.getAspectRatio(this);
  16356. if (this.minZ <= 0) {
  16357. this.minZ = 0.1;
  16358. }
  16359. if (scene.useRightHandedSystem) {
  16360. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16361. }
  16362. else {
  16363. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16364. }
  16365. }
  16366. else {
  16367. var halfWidth = engine.getRenderWidth() / 2.0;
  16368. var halfHeight = engine.getRenderHeight() / 2.0;
  16369. if (scene.useRightHandedSystem) {
  16370. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16371. }
  16372. else {
  16373. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16374. }
  16375. this._cache.orthoLeft = this.orthoLeft;
  16376. this._cache.orthoRight = this.orthoRight;
  16377. this._cache.orthoBottom = this.orthoBottom;
  16378. this._cache.orthoTop = this.orthoTop;
  16379. this._cache.renderWidth = engine.getRenderWidth();
  16380. this._cache.renderHeight = engine.getRenderHeight();
  16381. }
  16382. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16383. return this._projectionMatrix;
  16384. };
  16385. Camera.prototype.getTranformationMatrix = function () {
  16386. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16387. return this._transformMatrix;
  16388. };
  16389. Camera.prototype.updateFrustumPlanes = function () {
  16390. if (!this._refreshFrustumPlanes) {
  16391. return;
  16392. }
  16393. this.getTranformationMatrix();
  16394. if (!this._frustumPlanes) {
  16395. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16396. }
  16397. else {
  16398. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16399. }
  16400. this._refreshFrustumPlanes = false;
  16401. };
  16402. Camera.prototype.isInFrustum = function (target) {
  16403. this.updateFrustumPlanes();
  16404. return target.isInFrustum(this._frustumPlanes);
  16405. };
  16406. Camera.prototype.isCompletelyInFrustum = function (target) {
  16407. this.updateFrustumPlanes();
  16408. return target.isCompletelyInFrustum(this._frustumPlanes);
  16409. };
  16410. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16411. if (length === void 0) { length = 100; }
  16412. if (!transform) {
  16413. transform = this.getWorldMatrix();
  16414. }
  16415. if (!origin) {
  16416. origin = this.position;
  16417. }
  16418. var forward = new BABYLON.Vector3(0, 0, 1);
  16419. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16420. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16421. return new BABYLON.Ray(origin, direction, length);
  16422. };
  16423. Camera.prototype.dispose = function () {
  16424. // Observables
  16425. this.onViewMatrixChangedObservable.clear();
  16426. this.onProjectionMatrixChangedObservable.clear();
  16427. this.onAfterCheckInputsObservable.clear();
  16428. this.onRestoreStateObservable.clear();
  16429. // Inputs
  16430. if (this.inputs) {
  16431. this.inputs.clear();
  16432. }
  16433. // Animations
  16434. this.getScene().stopAnimation(this);
  16435. // Remove from scene
  16436. this.getScene().removeCamera(this);
  16437. while (this._rigCameras.length > 0) {
  16438. var camera = this._rigCameras.pop();
  16439. if (camera) {
  16440. camera.dispose();
  16441. }
  16442. }
  16443. // Postprocesses
  16444. if (this._rigPostProcess) {
  16445. this._rigPostProcess.dispose(this);
  16446. this._rigPostProcess = null;
  16447. this._postProcesses = [];
  16448. }
  16449. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16450. this._rigPostProcess = null;
  16451. this._postProcesses = [];
  16452. }
  16453. else {
  16454. var i = this._postProcesses.length;
  16455. while (--i >= 0) {
  16456. this._postProcesses[i].dispose(this);
  16457. }
  16458. }
  16459. // Render targets
  16460. var i = this.customRenderTargets.length;
  16461. while (--i >= 0) {
  16462. this.customRenderTargets[i].dispose();
  16463. }
  16464. this.customRenderTargets = [];
  16465. // Active Meshes
  16466. this._activeMeshes.dispose();
  16467. _super.prototype.dispose.call(this);
  16468. };
  16469. Object.defineProperty(Camera.prototype, "leftCamera", {
  16470. // ---- Camera rigs section ----
  16471. get: function () {
  16472. if (this._rigCameras.length < 1) {
  16473. return null;
  16474. }
  16475. return this._rigCameras[0];
  16476. },
  16477. enumerable: true,
  16478. configurable: true
  16479. });
  16480. Object.defineProperty(Camera.prototype, "rightCamera", {
  16481. get: function () {
  16482. if (this._rigCameras.length < 2) {
  16483. return null;
  16484. }
  16485. return this._rigCameras[1];
  16486. },
  16487. enumerable: true,
  16488. configurable: true
  16489. });
  16490. Camera.prototype.getLeftTarget = function () {
  16491. if (this._rigCameras.length < 1) {
  16492. return null;
  16493. }
  16494. return this._rigCameras[0].getTarget();
  16495. };
  16496. Camera.prototype.getRightTarget = function () {
  16497. if (this._rigCameras.length < 2) {
  16498. return null;
  16499. }
  16500. return this._rigCameras[1].getTarget();
  16501. };
  16502. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16503. if (this.cameraRigMode === mode) {
  16504. return;
  16505. }
  16506. while (this._rigCameras.length > 0) {
  16507. var camera = this._rigCameras.pop();
  16508. if (camera) {
  16509. camera.dispose();
  16510. }
  16511. }
  16512. this.cameraRigMode = mode;
  16513. this._cameraRigParams = {};
  16514. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16515. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16516. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16517. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16518. // create the rig cameras, unless none
  16519. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16520. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16521. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16522. if (leftCamera && rightCamera) {
  16523. this._rigCameras.push(leftCamera);
  16524. this._rigCameras.push(rightCamera);
  16525. }
  16526. }
  16527. switch (this.cameraRigMode) {
  16528. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16529. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16530. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16531. break;
  16532. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16533. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16534. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16535. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16536. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16537. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16538. break;
  16539. case Camera.RIG_MODE_VR:
  16540. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16541. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16542. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16543. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16544. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16545. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16546. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16547. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16548. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16549. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16550. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16551. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16552. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16553. if (metrics.compensateDistortion) {
  16554. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16555. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16556. }
  16557. break;
  16558. case Camera.RIG_MODE_WEBVR:
  16559. if (rigParams.vrDisplay) {
  16560. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16561. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16562. //Left eye
  16563. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16564. this._rigCameras[0].setCameraRigParameter("left", true);
  16565. //leaving this for future reference
  16566. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16567. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16568. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16569. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16570. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16571. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16572. this._rigCameras[0].parent = this;
  16573. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16574. //Right eye
  16575. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16576. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16577. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16578. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16579. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16580. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16581. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16582. this._rigCameras[1].parent = this;
  16583. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16584. if (Camera.UseAlternateWebVRRendering) {
  16585. this._rigCameras[1]._skipRendering = true;
  16586. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16587. }
  16588. }
  16589. break;
  16590. }
  16591. this._cascadePostProcessesToRigCams();
  16592. this.update();
  16593. };
  16594. Camera.prototype._getVRProjectionMatrix = function () {
  16595. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16596. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16597. return this._projectionMatrix;
  16598. };
  16599. Camera.prototype._updateCameraRotationMatrix = function () {
  16600. //Here for WebVR
  16601. };
  16602. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16603. //Here for WebVR
  16604. };
  16605. /**
  16606. * This function MUST be overwritten by the different WebVR cameras available.
  16607. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16608. */
  16609. Camera.prototype._getWebVRProjectionMatrix = function () {
  16610. return BABYLON.Matrix.Identity();
  16611. };
  16612. /**
  16613. * This function MUST be overwritten by the different WebVR cameras available.
  16614. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16615. */
  16616. Camera.prototype._getWebVRViewMatrix = function () {
  16617. return BABYLON.Matrix.Identity();
  16618. };
  16619. Camera.prototype.setCameraRigParameter = function (name, value) {
  16620. if (!this._cameraRigParams) {
  16621. this._cameraRigParams = {};
  16622. }
  16623. this._cameraRigParams[name] = value;
  16624. //provisionnally:
  16625. if (name === "interaxialDistance") {
  16626. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16627. }
  16628. };
  16629. /**
  16630. * needs to be overridden by children so sub has required properties to be copied
  16631. */
  16632. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16633. return null;
  16634. };
  16635. /**
  16636. * May need to be overridden by children
  16637. */
  16638. Camera.prototype._updateRigCameras = function () {
  16639. for (var i = 0; i < this._rigCameras.length; i++) {
  16640. this._rigCameras[i].minZ = this.minZ;
  16641. this._rigCameras[i].maxZ = this.maxZ;
  16642. this._rigCameras[i].fov = this.fov;
  16643. }
  16644. // only update viewport when ANAGLYPH
  16645. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16646. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16647. }
  16648. };
  16649. Camera.prototype._setupInputs = function () {
  16650. };
  16651. Camera.prototype.serialize = function () {
  16652. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16653. // Type
  16654. serializationObject.type = this.getClassName();
  16655. // Parent
  16656. if (this.parent) {
  16657. serializationObject.parentId = this.parent.id;
  16658. }
  16659. if (this.inputs) {
  16660. this.inputs.serialize(serializationObject);
  16661. }
  16662. // Animations
  16663. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16664. serializationObject.ranges = this.serializeAnimationRanges();
  16665. return serializationObject;
  16666. };
  16667. Camera.prototype.clone = function (name) {
  16668. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16669. };
  16670. Camera.prototype.getDirection = function (localAxis) {
  16671. var result = BABYLON.Vector3.Zero();
  16672. this.getDirectionToRef(localAxis, result);
  16673. return result;
  16674. };
  16675. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16676. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16677. };
  16678. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16679. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16680. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16681. switch (type) {
  16682. case "ArcRotateCamera":
  16683. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16684. case "DeviceOrientationCamera":
  16685. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16686. case "FollowCamera":
  16687. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16688. case "ArcFollowCamera":
  16689. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16690. case "GamepadCamera":
  16691. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16692. case "TouchCamera":
  16693. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16694. case "VirtualJoysticksCamera":
  16695. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16696. case "WebVRFreeCamera":
  16697. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16698. case "WebVRGamepadCamera":
  16699. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16700. case "VRDeviceOrientationFreeCamera":
  16701. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16702. case "VRDeviceOrientationGamepadCamera":
  16703. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16704. case "AnaglyphArcRotateCamera":
  16705. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16706. case "AnaglyphFreeCamera":
  16707. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16708. case "AnaglyphGamepadCamera":
  16709. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16710. case "AnaglyphUniversalCamera":
  16711. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16712. case "StereoscopicArcRotateCamera":
  16713. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16714. case "StereoscopicFreeCamera":
  16715. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16716. case "StereoscopicGamepadCamera":
  16717. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16718. case "StereoscopicUniversalCamera":
  16719. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16720. case "FreeCamera":// Forcing Universal here
  16721. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16722. default:// Universal Camera is the default value
  16723. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16724. }
  16725. };
  16726. Camera.Parse = function (parsedCamera, scene) {
  16727. var type = parsedCamera.type;
  16728. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16729. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16730. // Parent
  16731. if (parsedCamera.parentId) {
  16732. camera._waitingParentId = parsedCamera.parentId;
  16733. }
  16734. //If camera has an input manager, let it parse inputs settings
  16735. if (camera.inputs) {
  16736. camera.inputs.parse(parsedCamera);
  16737. camera._setupInputs();
  16738. }
  16739. if (camera.setPosition) {
  16740. camera.position.copyFromFloats(0, 0, 0);
  16741. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16742. }
  16743. // Target
  16744. if (parsedCamera.target) {
  16745. if (camera.setTarget) {
  16746. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16747. }
  16748. }
  16749. // Apply 3d rig, when found
  16750. if (parsedCamera.cameraRigMode) {
  16751. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16752. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16753. }
  16754. // Animations
  16755. if (parsedCamera.animations) {
  16756. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16757. var parsedAnimation = parsedCamera.animations[animationIndex];
  16758. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16759. }
  16760. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16761. }
  16762. if (parsedCamera.autoAnimate) {
  16763. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16764. }
  16765. return camera;
  16766. };
  16767. // Statics
  16768. Camera._PERSPECTIVE_CAMERA = 0;
  16769. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16770. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16771. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16772. Camera._RIG_MODE_NONE = 0;
  16773. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16774. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16775. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16776. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16777. Camera._RIG_MODE_VR = 20;
  16778. Camera._RIG_MODE_WEBVR = 21;
  16779. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16780. Camera.UseAlternateWebVRRendering = false;
  16781. __decorate([
  16782. BABYLON.serializeAsVector3()
  16783. ], Camera.prototype, "position", void 0);
  16784. __decorate([
  16785. BABYLON.serializeAsVector3()
  16786. ], Camera.prototype, "upVector", void 0);
  16787. __decorate([
  16788. BABYLON.serialize()
  16789. ], Camera.prototype, "orthoLeft", void 0);
  16790. __decorate([
  16791. BABYLON.serialize()
  16792. ], Camera.prototype, "orthoRight", void 0);
  16793. __decorate([
  16794. BABYLON.serialize()
  16795. ], Camera.prototype, "orthoBottom", void 0);
  16796. __decorate([
  16797. BABYLON.serialize()
  16798. ], Camera.prototype, "orthoTop", void 0);
  16799. __decorate([
  16800. BABYLON.serialize()
  16801. ], Camera.prototype, "fov", void 0);
  16802. __decorate([
  16803. BABYLON.serialize()
  16804. ], Camera.prototype, "minZ", void 0);
  16805. __decorate([
  16806. BABYLON.serialize()
  16807. ], Camera.prototype, "maxZ", void 0);
  16808. __decorate([
  16809. BABYLON.serialize()
  16810. ], Camera.prototype, "inertia", void 0);
  16811. __decorate([
  16812. BABYLON.serialize()
  16813. ], Camera.prototype, "mode", void 0);
  16814. __decorate([
  16815. BABYLON.serialize()
  16816. ], Camera.prototype, "layerMask", void 0);
  16817. __decorate([
  16818. BABYLON.serialize()
  16819. ], Camera.prototype, "fovMode", void 0);
  16820. __decorate([
  16821. BABYLON.serialize()
  16822. ], Camera.prototype, "cameraRigMode", void 0);
  16823. __decorate([
  16824. BABYLON.serialize()
  16825. ], Camera.prototype, "interaxialDistance", void 0);
  16826. __decorate([
  16827. BABYLON.serialize()
  16828. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16829. return Camera;
  16830. }(BABYLON.Node));
  16831. BABYLON.Camera = Camera;
  16832. })(BABYLON || (BABYLON = {}));
  16833. //# sourceMappingURL=babylon.camera.js.map
  16834. var BABYLON;
  16835. (function (BABYLON) {
  16836. var RenderingManager = /** @class */ (function () {
  16837. function RenderingManager(scene) {
  16838. this._renderingGroups = new Array();
  16839. this._autoClearDepthStencil = {};
  16840. this._customOpaqueSortCompareFn = {};
  16841. this._customAlphaTestSortCompareFn = {};
  16842. this._customTransparentSortCompareFn = {};
  16843. this._renderinGroupInfo = null;
  16844. this._scene = scene;
  16845. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16846. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16847. }
  16848. }
  16849. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16850. if (depth === void 0) { depth = true; }
  16851. if (stencil === void 0) { stencil = true; }
  16852. if (this._depthStencilBufferAlreadyCleaned) {
  16853. return;
  16854. }
  16855. this._scene.getEngine().clear(null, false, depth, stencil);
  16856. this._depthStencilBufferAlreadyCleaned = true;
  16857. };
  16858. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16859. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16860. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16861. var info = null;
  16862. if (observable) {
  16863. if (!this._renderinGroupInfo) {
  16864. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16865. }
  16866. info = this._renderinGroupInfo;
  16867. info.scene = this._scene;
  16868. info.camera = this._scene.activeCamera;
  16869. }
  16870. // Dispatch sprites
  16871. if (renderSprites) {
  16872. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16873. var manager = this._scene.spriteManagers[index];
  16874. this.dispatchSprites(manager);
  16875. }
  16876. }
  16877. // Render
  16878. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16879. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16880. var renderingGroup = this._renderingGroups[index];
  16881. if (!renderingGroup && !observable)
  16882. continue;
  16883. this._currentIndex = index;
  16884. var renderingGroupMask = 0;
  16885. // Fire PRECLEAR stage
  16886. if (observable && info) {
  16887. renderingGroupMask = Math.pow(2, index);
  16888. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16889. info.renderingGroupId = index;
  16890. observable.notifyObservers(info, renderingGroupMask);
  16891. }
  16892. // Clear depth/stencil if needed
  16893. if (RenderingManager.AUTOCLEAR) {
  16894. var autoClear = this._autoClearDepthStencil[index];
  16895. if (autoClear && autoClear.autoClear) {
  16896. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16897. }
  16898. }
  16899. if (observable && info) {
  16900. // Fire PREOPAQUE stage
  16901. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16902. observable.notifyObservers(info, renderingGroupMask);
  16903. // Fire PRETRANSPARENT stage
  16904. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16905. observable.notifyObservers(info, renderingGroupMask);
  16906. }
  16907. if (renderingGroup)
  16908. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16909. // Fire POSTTRANSPARENT stage
  16910. if (observable && info) {
  16911. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16912. observable.notifyObservers(info, renderingGroupMask);
  16913. }
  16914. }
  16915. };
  16916. RenderingManager.prototype.reset = function () {
  16917. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16918. var renderingGroup = this._renderingGroups[index];
  16919. if (renderingGroup) {
  16920. renderingGroup.prepare();
  16921. }
  16922. }
  16923. };
  16924. RenderingManager.prototype.dispose = function () {
  16925. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16926. var renderingGroup = this._renderingGroups[index];
  16927. if (renderingGroup) {
  16928. renderingGroup.dispose();
  16929. }
  16930. }
  16931. this._renderingGroups.length = 0;
  16932. };
  16933. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16934. if (!this._renderingGroups[renderingGroupId]) {
  16935. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16936. }
  16937. };
  16938. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16939. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16940. this._prepareRenderingGroup(renderingGroupId);
  16941. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16942. };
  16943. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16944. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16945. this._prepareRenderingGroup(renderingGroupId);
  16946. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16947. };
  16948. RenderingManager.prototype.dispatch = function (subMesh) {
  16949. var mesh = subMesh.getMesh();
  16950. var renderingGroupId = mesh.renderingGroupId || 0;
  16951. this._prepareRenderingGroup(renderingGroupId);
  16952. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16953. };
  16954. /**
  16955. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16956. * This allowed control for front to back rendering or reversly depending of the special needs.
  16957. *
  16958. * @param renderingGroupId The rendering group id corresponding to its index
  16959. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16960. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16961. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16962. */
  16963. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16964. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16965. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16966. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16967. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16968. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16969. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16970. if (this._renderingGroups[renderingGroupId]) {
  16971. var group = this._renderingGroups[renderingGroupId];
  16972. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16973. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16974. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16975. }
  16976. };
  16977. /**
  16978. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16979. *
  16980. * @param renderingGroupId The rendering group id corresponding to its index
  16981. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16982. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16983. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16984. */
  16985. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16986. if (depth === void 0) { depth = true; }
  16987. if (stencil === void 0) { stencil = true; }
  16988. this._autoClearDepthStencil[renderingGroupId] = {
  16989. autoClear: autoClearDepthStencil,
  16990. depth: depth,
  16991. stencil: stencil
  16992. };
  16993. };
  16994. /**
  16995. * The max id used for rendering groups (not included)
  16996. */
  16997. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16998. /**
  16999. * The min id used for rendering groups (included)
  17000. */
  17001. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17002. /**
  17003. * Used to globally prevent autoclearing scenes.
  17004. */
  17005. RenderingManager.AUTOCLEAR = true;
  17006. return RenderingManager;
  17007. }());
  17008. BABYLON.RenderingManager = RenderingManager;
  17009. })(BABYLON || (BABYLON = {}));
  17010. //# sourceMappingURL=babylon.renderingManager.js.map
  17011. var BABYLON;
  17012. (function (BABYLON) {
  17013. var RenderingGroup = /** @class */ (function () {
  17014. /**
  17015. * Creates a new rendering group.
  17016. * @param index The rendering group index
  17017. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17018. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17019. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17020. */
  17021. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17022. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17023. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17024. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17025. this.index = index;
  17026. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17027. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17028. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17029. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17030. this._particleSystems = new BABYLON.SmartArray(256);
  17031. this._spriteManagers = new BABYLON.SmartArray(256);
  17032. this._edgesRenderers = new BABYLON.SmartArray(16);
  17033. this._scene = scene;
  17034. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17035. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17036. this.transparentSortCompareFn = transparentSortCompareFn;
  17037. }
  17038. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17039. /**
  17040. * Set the opaque sort comparison function.
  17041. * If null the sub meshes will be render in the order they were created
  17042. */
  17043. set: function (value) {
  17044. this._opaqueSortCompareFn = value;
  17045. if (value) {
  17046. this._renderOpaque = this.renderOpaqueSorted;
  17047. }
  17048. else {
  17049. this._renderOpaque = RenderingGroup.renderUnsorted;
  17050. }
  17051. },
  17052. enumerable: true,
  17053. configurable: true
  17054. });
  17055. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17056. /**
  17057. * Set the alpha test sort comparison function.
  17058. * If null the sub meshes will be render in the order they were created
  17059. */
  17060. set: function (value) {
  17061. this._alphaTestSortCompareFn = value;
  17062. if (value) {
  17063. this._renderAlphaTest = this.renderAlphaTestSorted;
  17064. }
  17065. else {
  17066. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17067. }
  17068. },
  17069. enumerable: true,
  17070. configurable: true
  17071. });
  17072. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17073. /**
  17074. * Set the transparent sort comparison function.
  17075. * If null the sub meshes will be render in the order they were created
  17076. */
  17077. set: function (value) {
  17078. if (value) {
  17079. this._transparentSortCompareFn = value;
  17080. }
  17081. else {
  17082. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17083. }
  17084. this._renderTransparent = this.renderTransparentSorted;
  17085. },
  17086. enumerable: true,
  17087. configurable: true
  17088. });
  17089. /**
  17090. * Render all the sub meshes contained in the group.
  17091. * @param customRenderFunction Used to override the default render behaviour of the group.
  17092. * @returns true if rendered some submeshes.
  17093. */
  17094. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17095. if (customRenderFunction) {
  17096. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17097. return;
  17098. }
  17099. var engine = this._scene.getEngine();
  17100. // Depth only
  17101. if (this._depthOnlySubMeshes.length !== 0) {
  17102. engine.setAlphaTesting(true);
  17103. engine.setColorWrite(false);
  17104. this._renderAlphaTest(this._depthOnlySubMeshes);
  17105. engine.setAlphaTesting(false);
  17106. engine.setColorWrite(true);
  17107. }
  17108. // Opaque
  17109. if (this._opaqueSubMeshes.length !== 0) {
  17110. this._renderOpaque(this._opaqueSubMeshes);
  17111. }
  17112. // Alpha test
  17113. if (this._alphaTestSubMeshes.length !== 0) {
  17114. engine.setAlphaTesting(true);
  17115. this._renderAlphaTest(this._alphaTestSubMeshes);
  17116. engine.setAlphaTesting(false);
  17117. }
  17118. var stencilState = engine.getStencilBuffer();
  17119. engine.setStencilBuffer(false);
  17120. // Sprites
  17121. if (renderSprites) {
  17122. this._renderSprites();
  17123. }
  17124. // Particles
  17125. if (renderParticles) {
  17126. this._renderParticles(activeMeshes);
  17127. }
  17128. if (this.onBeforeTransparentRendering) {
  17129. this.onBeforeTransparentRendering();
  17130. }
  17131. // Transparent
  17132. if (this._transparentSubMeshes.length !== 0) {
  17133. this._renderTransparent(this._transparentSubMeshes);
  17134. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17135. }
  17136. // Set back stencil to false in case it changes before the edge renderer.
  17137. engine.setStencilBuffer(false);
  17138. // Edges
  17139. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17140. this._edgesRenderers.data[edgesRendererIndex].render();
  17141. }
  17142. // Restore Stencil state.
  17143. engine.setStencilBuffer(stencilState);
  17144. };
  17145. /**
  17146. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17147. * @param subMeshes The submeshes to render
  17148. */
  17149. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17150. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17151. };
  17152. /**
  17153. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17154. * @param subMeshes The submeshes to render
  17155. */
  17156. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17157. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17158. };
  17159. /**
  17160. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17161. * @param subMeshes The submeshes to render
  17162. */
  17163. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17164. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17165. };
  17166. /**
  17167. * Renders the submeshes in a specified order.
  17168. * @param subMeshes The submeshes to sort before render
  17169. * @param sortCompareFn The comparison function use to sort
  17170. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17171. * @param transparent Specifies to activate blending if true
  17172. */
  17173. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17174. var subIndex = 0;
  17175. var subMesh;
  17176. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17177. for (; subIndex < subMeshes.length; subIndex++) {
  17178. subMesh = subMeshes.data[subIndex];
  17179. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17180. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17181. }
  17182. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17183. if (sortCompareFn) {
  17184. sortedArray.sort(sortCompareFn);
  17185. }
  17186. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17187. subMesh = sortedArray[subIndex];
  17188. if (transparent) {
  17189. var material = subMesh.getMaterial();
  17190. if (material && material.needDepthPrePass) {
  17191. var engine = material.getScene().getEngine();
  17192. engine.setColorWrite(false);
  17193. engine.setAlphaTesting(true);
  17194. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17195. subMesh.render(false);
  17196. engine.setAlphaTesting(false);
  17197. engine.setColorWrite(true);
  17198. }
  17199. }
  17200. subMesh.render(transparent);
  17201. }
  17202. };
  17203. /**
  17204. * Renders the submeshes in the order they were dispatched (no sort applied).
  17205. * @param subMeshes The submeshes to render
  17206. */
  17207. RenderingGroup.renderUnsorted = function (subMeshes) {
  17208. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17209. var submesh = subMeshes.data[subIndex];
  17210. submesh.render(false);
  17211. }
  17212. };
  17213. /**
  17214. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17215. * are rendered back to front if in the same alpha index.
  17216. *
  17217. * @param a The first submesh
  17218. * @param b The second submesh
  17219. * @returns The result of the comparison
  17220. */
  17221. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17222. // Alpha index first
  17223. if (a._alphaIndex > b._alphaIndex) {
  17224. return 1;
  17225. }
  17226. if (a._alphaIndex < b._alphaIndex) {
  17227. return -1;
  17228. }
  17229. // Then distance to camera
  17230. return RenderingGroup.backToFrontSortCompare(a, b);
  17231. };
  17232. /**
  17233. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17234. * are rendered back to front.
  17235. *
  17236. * @param a The first submesh
  17237. * @param b The second submesh
  17238. * @returns The result of the comparison
  17239. */
  17240. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17241. // Then distance to camera
  17242. if (a._distanceToCamera < b._distanceToCamera) {
  17243. return 1;
  17244. }
  17245. if (a._distanceToCamera > b._distanceToCamera) {
  17246. return -1;
  17247. }
  17248. return 0;
  17249. };
  17250. /**
  17251. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17252. * are rendered front to back (prevent overdraw).
  17253. *
  17254. * @param a The first submesh
  17255. * @param b The second submesh
  17256. * @returns The result of the comparison
  17257. */
  17258. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17259. // Then distance to camera
  17260. if (a._distanceToCamera < b._distanceToCamera) {
  17261. return -1;
  17262. }
  17263. if (a._distanceToCamera > b._distanceToCamera) {
  17264. return 1;
  17265. }
  17266. return 0;
  17267. };
  17268. /**
  17269. * Resets the different lists of submeshes to prepare a new frame.
  17270. */
  17271. RenderingGroup.prototype.prepare = function () {
  17272. this._opaqueSubMeshes.reset();
  17273. this._transparentSubMeshes.reset();
  17274. this._alphaTestSubMeshes.reset();
  17275. this._depthOnlySubMeshes.reset();
  17276. this._particleSystems.reset();
  17277. this._spriteManagers.reset();
  17278. this._edgesRenderers.reset();
  17279. };
  17280. RenderingGroup.prototype.dispose = function () {
  17281. this._opaqueSubMeshes.dispose();
  17282. this._transparentSubMeshes.dispose();
  17283. this._alphaTestSubMeshes.dispose();
  17284. this._depthOnlySubMeshes.dispose();
  17285. this._particleSystems.dispose();
  17286. this._spriteManagers.dispose();
  17287. this._edgesRenderers.dispose();
  17288. };
  17289. /**
  17290. * Inserts the submesh in its correct queue depending on its material.
  17291. * @param subMesh The submesh to dispatch
  17292. */
  17293. RenderingGroup.prototype.dispatch = function (subMesh) {
  17294. var material = subMesh.getMaterial();
  17295. var mesh = subMesh.getMesh();
  17296. if (!material) {
  17297. return;
  17298. }
  17299. if (material.needAlphaBlending() || material.needAlphaBlendingForMesh(mesh)) {
  17300. this._transparentSubMeshes.push(subMesh);
  17301. }
  17302. else if (material.needAlphaTesting()) {
  17303. if (material.needDepthPrePass) {
  17304. this._depthOnlySubMeshes.push(subMesh);
  17305. }
  17306. this._alphaTestSubMeshes.push(subMesh);
  17307. }
  17308. else {
  17309. if (material.needDepthPrePass) {
  17310. this._depthOnlySubMeshes.push(subMesh);
  17311. }
  17312. this._opaqueSubMeshes.push(subMesh); // Opaque
  17313. }
  17314. if (mesh._edgesRenderer) {
  17315. this._edgesRenderers.push(mesh._edgesRenderer);
  17316. }
  17317. };
  17318. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17319. this._spriteManagers.push(spriteManager);
  17320. };
  17321. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17322. this._particleSystems.push(particleSystem);
  17323. };
  17324. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17325. if (this._particleSystems.length === 0) {
  17326. return;
  17327. }
  17328. // Particles
  17329. var activeCamera = this._scene.activeCamera;
  17330. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17331. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17332. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17333. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17334. continue;
  17335. }
  17336. var emitter = particleSystem.emitter;
  17337. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17338. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17339. }
  17340. }
  17341. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17342. };
  17343. RenderingGroup.prototype._renderSprites = function () {
  17344. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17345. return;
  17346. }
  17347. // Sprites
  17348. var activeCamera = this._scene.activeCamera;
  17349. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17350. for (var id = 0; id < this._spriteManagers.length; id++) {
  17351. var spriteManager = this._spriteManagers.data[id];
  17352. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17353. spriteManager.render();
  17354. }
  17355. }
  17356. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17357. };
  17358. return RenderingGroup;
  17359. }());
  17360. BABYLON.RenderingGroup = RenderingGroup;
  17361. })(BABYLON || (BABYLON = {}));
  17362. //# sourceMappingURL=babylon.renderingGroup.js.map
  17363. var BABYLON;
  17364. (function (BABYLON) {
  17365. var ClickInfo = /** @class */ (function () {
  17366. function ClickInfo() {
  17367. this._singleClick = false;
  17368. this._doubleClick = false;
  17369. this._hasSwiped = false;
  17370. this._ignore = false;
  17371. }
  17372. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17373. get: function () {
  17374. return this._singleClick;
  17375. },
  17376. set: function (b) {
  17377. this._singleClick = b;
  17378. },
  17379. enumerable: true,
  17380. configurable: true
  17381. });
  17382. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17383. get: function () {
  17384. return this._doubleClick;
  17385. },
  17386. set: function (b) {
  17387. this._doubleClick = b;
  17388. },
  17389. enumerable: true,
  17390. configurable: true
  17391. });
  17392. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17393. get: function () {
  17394. return this._hasSwiped;
  17395. },
  17396. set: function (b) {
  17397. this._hasSwiped = b;
  17398. },
  17399. enumerable: true,
  17400. configurable: true
  17401. });
  17402. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17403. get: function () {
  17404. return this._ignore;
  17405. },
  17406. set: function (b) {
  17407. this._ignore = b;
  17408. },
  17409. enumerable: true,
  17410. configurable: true
  17411. });
  17412. return ClickInfo;
  17413. }());
  17414. /**
  17415. * This class is used by the onRenderingGroupObservable
  17416. */
  17417. var RenderingGroupInfo = /** @class */ (function () {
  17418. function RenderingGroupInfo() {
  17419. }
  17420. /**
  17421. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17422. * This stage will be fired no matter what
  17423. */
  17424. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17425. /**
  17426. * Called before opaque object are rendered.
  17427. * This stage will be fired only if there's 3D Opaque content to render
  17428. */
  17429. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17430. /**
  17431. * Called after the opaque objects are rendered and before the transparent ones
  17432. * This stage will be fired only if there's 3D transparent content to render
  17433. */
  17434. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17435. /**
  17436. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17437. * This stage will be fired no matter what
  17438. */
  17439. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17440. return RenderingGroupInfo;
  17441. }());
  17442. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17443. /**
  17444. * Represents a scene to be rendered by the engine.
  17445. * @see http://doc.babylonjs.com/page.php?p=21911
  17446. */
  17447. var Scene = /** @class */ (function () {
  17448. /**
  17449. * @constructor
  17450. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17451. */
  17452. function Scene(engine) {
  17453. // Members
  17454. this.autoClear = true;
  17455. this.autoClearDepthAndStencil = true;
  17456. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17457. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17458. this.forceWireframe = false;
  17459. this._forcePointsCloud = false;
  17460. this.forceShowBoundingBoxes = false;
  17461. this.animationsEnabled = true;
  17462. this.constantlyUpdateMeshUnderPointer = false;
  17463. this.hoverCursor = "pointer";
  17464. this.defaultCursor = "";
  17465. /**
  17466. * This is used to call preventDefault() on pointer down
  17467. * in order to block unwanted artifacts like system double clicks
  17468. */
  17469. this.preventDefaultOnPointerDown = true;
  17470. // Metadata
  17471. this.metadata = null;
  17472. /**
  17473. * An event triggered when the scene is disposed.
  17474. * @type {BABYLON.Observable}
  17475. */
  17476. this.onDisposeObservable = new BABYLON.Observable();
  17477. /**
  17478. * An event triggered before rendering the scene (right after animations and physics)
  17479. * @type {BABYLON.Observable}
  17480. */
  17481. this.onBeforeRenderObservable = new BABYLON.Observable();
  17482. /**
  17483. * An event triggered after rendering the scene
  17484. * @type {BABYLON.Observable}
  17485. */
  17486. this.onAfterRenderObservable = new BABYLON.Observable();
  17487. /**
  17488. * An event triggered before animating the scene
  17489. * @type {BABYLON.Observable}
  17490. */
  17491. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17492. /**
  17493. * An event triggered after animations processing
  17494. * @type {BABYLON.Observable}
  17495. */
  17496. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17497. /**
  17498. * An event triggered before draw calls are ready to be sent
  17499. * @type {BABYLON.Observable}
  17500. */
  17501. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17502. /**
  17503. * An event triggered after draw calls have been sent
  17504. * @type {BABYLON.Observable}
  17505. */
  17506. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17507. /**
  17508. * An event triggered when physic simulation is about to be run
  17509. * @type {BABYLON.Observable}
  17510. */
  17511. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17512. /**
  17513. * An event triggered when physic simulation has been done
  17514. * @type {BABYLON.Observable}
  17515. */
  17516. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17517. /**
  17518. * An event triggered when the scene is ready
  17519. * @type {BABYLON.Observable}
  17520. */
  17521. this.onReadyObservable = new BABYLON.Observable();
  17522. /**
  17523. * An event triggered before rendering a camera
  17524. * @type {BABYLON.Observable}
  17525. */
  17526. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17527. /**
  17528. * An event triggered after rendering a camera
  17529. * @type {BABYLON.Observable}
  17530. */
  17531. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17532. /**
  17533. * An event triggered when active meshes evaluation is about to start
  17534. * @type {BABYLON.Observable}
  17535. */
  17536. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17537. /**
  17538. * An event triggered when active meshes evaluation is done
  17539. * @type {BABYLON.Observable}
  17540. */
  17541. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17542. /**
  17543. * An event triggered when particles rendering is about to start
  17544. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17545. * @type {BABYLON.Observable}
  17546. */
  17547. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17548. /**
  17549. * An event triggered when particles rendering is done
  17550. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17551. * @type {BABYLON.Observable}
  17552. */
  17553. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17554. /**
  17555. * An event triggered when sprites rendering is about to start
  17556. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17557. * @type {BABYLON.Observable}
  17558. */
  17559. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17560. /**
  17561. * An event triggered when sprites rendering is done
  17562. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17563. * @type {BABYLON.Observable}
  17564. */
  17565. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17566. /**
  17567. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  17568. * @type {BABYLON.Observable}
  17569. */
  17570. this.onDataLoadedObservable = new BABYLON.Observable();
  17571. /**
  17572. * An event triggered when a camera is created
  17573. * @type {BABYLON.Observable}
  17574. */
  17575. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17576. /**
  17577. * An event triggered when a camera is removed
  17578. * @type {BABYLON.Observable}
  17579. */
  17580. this.onCameraRemovedObservable = new BABYLON.Observable();
  17581. /**
  17582. * An event triggered when a light is created
  17583. * @type {BABYLON.Observable}
  17584. */
  17585. this.onNewLightAddedObservable = new BABYLON.Observable();
  17586. /**
  17587. * An event triggered when a light is removed
  17588. * @type {BABYLON.Observable}
  17589. */
  17590. this.onLightRemovedObservable = new BABYLON.Observable();
  17591. /**
  17592. * An event triggered when a geometry is created
  17593. * @type {BABYLON.Observable}
  17594. */
  17595. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17596. /**
  17597. * An event triggered when a geometry is removed
  17598. * @type {BABYLON.Observable}
  17599. */
  17600. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17601. /**
  17602. * An event triggered when a mesh is created
  17603. * @type {BABYLON.Observable}
  17604. */
  17605. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17606. /**
  17607. * An event triggered when a mesh is removed
  17608. * @type {BABYLON.Observable}
  17609. */
  17610. this.onMeshRemovedObservable = new BABYLON.Observable();
  17611. /**
  17612. * An event triggered when render targets are about to be rendered
  17613. * Can happen multiple times per frame.
  17614. * @type {BABYLON.Observable}
  17615. */
  17616. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17617. /**
  17618. * An event triggered when render targets were rendered.
  17619. * Can happen multiple times per frame.
  17620. * @type {BABYLON.Observable}
  17621. */
  17622. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17623. /**
  17624. * An event triggered before calculating deterministic simulation step
  17625. * @type {BABYLON.Observable}
  17626. */
  17627. this.onBeforeStepObservable = new BABYLON.Observable();
  17628. /**
  17629. * An event triggered after calculating deterministic simulation step
  17630. * @type {BABYLON.Observable}
  17631. */
  17632. this.onAfterStepObservable = new BABYLON.Observable();
  17633. /**
  17634. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17635. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17636. * 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)
  17637. */
  17638. this.onRenderingGroupObservable = new BABYLON.Observable();
  17639. // Animations
  17640. this.animations = [];
  17641. /**
  17642. * 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).
  17643. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17644. */
  17645. this.onPrePointerObservable = new BABYLON.Observable();
  17646. /**
  17647. * Observable event triggered each time an input event is received from the rendering canvas
  17648. */
  17649. this.onPointerObservable = new BABYLON.Observable();
  17650. this._meshPickProceed = false;
  17651. this._previousHasSwiped = false;
  17652. this._currentPickResult = null;
  17653. this._previousPickResult = null;
  17654. this._totalPointersPressed = 0;
  17655. this._doubleClickOccured = false;
  17656. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17657. this.cameraToUseForPointers = null;
  17658. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17659. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17660. this._startingPointerTime = 0;
  17661. this._previousStartingPointerTime = 0;
  17662. // Deterministic lockstep
  17663. this._timeAccumulator = 0;
  17664. this._currentStepId = 0;
  17665. this._currentInternalStep = 0;
  17666. // Keyboard
  17667. /**
  17668. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17669. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17670. */
  17671. this.onPreKeyboardObservable = new BABYLON.Observable();
  17672. /**
  17673. * Observable event triggered each time an keyboard event is received from the hosting window
  17674. */
  17675. this.onKeyboardObservable = new BABYLON.Observable();
  17676. // Coordinate system
  17677. /**
  17678. * use right-handed coordinate system on this scene.
  17679. * @type {boolean}
  17680. */
  17681. this._useRightHandedSystem = false;
  17682. // Fog
  17683. this._fogEnabled = true;
  17684. this._fogMode = Scene.FOGMODE_NONE;
  17685. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17686. this.fogDensity = 0.1;
  17687. this.fogStart = 0;
  17688. this.fogEnd = 1000.0;
  17689. // Lights
  17690. /**
  17691. * is shadow enabled on this scene.
  17692. * @type {boolean}
  17693. */
  17694. this._shadowsEnabled = true;
  17695. /**
  17696. * is light enabled on this scene.
  17697. * @type {boolean}
  17698. */
  17699. this._lightsEnabled = true;
  17700. /**
  17701. * All of the lights added to this scene.
  17702. * @see BABYLON.Light
  17703. * @type {BABYLON.Light[]}
  17704. */
  17705. this.lights = new Array();
  17706. // Cameras
  17707. /** All of the cameras added to this scene. */
  17708. this.cameras = new Array();
  17709. /** All of the active cameras added to this scene. */
  17710. this.activeCameras = new Array();
  17711. // Meshes
  17712. /**
  17713. * All of the (abstract) meshes added to this scene.
  17714. * @see BABYLON.AbstractMesh
  17715. * @type {BABYLON.AbstractMesh[]}
  17716. */
  17717. this.meshes = new Array();
  17718. // Geometries
  17719. this._geometries = new Array();
  17720. this.materials = new Array();
  17721. this.multiMaterials = new Array();
  17722. // Textures
  17723. this._texturesEnabled = true;
  17724. this.textures = new Array();
  17725. // Particles
  17726. this.particlesEnabled = true;
  17727. this.particleSystems = new Array();
  17728. // Sprites
  17729. this.spritesEnabled = true;
  17730. this.spriteManagers = new Array();
  17731. // Layers
  17732. this.layers = new Array();
  17733. this.highlightLayers = new Array();
  17734. // Skeletons
  17735. this._skeletonsEnabled = true;
  17736. this.skeletons = new Array();
  17737. // Morph targets
  17738. this.morphTargetManagers = new Array();
  17739. // Lens flares
  17740. this.lensFlaresEnabled = true;
  17741. this.lensFlareSystems = new Array();
  17742. // Collisions
  17743. this.collisionsEnabled = true;
  17744. /** Defines the gravity applied to this scene */
  17745. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17746. // Postprocesses
  17747. this.postProcesses = new Array();
  17748. this.postProcessesEnabled = true;
  17749. // Customs render targets
  17750. this.renderTargetsEnabled = true;
  17751. this.dumpNextRenderTargets = false;
  17752. this.customRenderTargets = new Array();
  17753. // Imported meshes
  17754. this.importedMeshesFiles = new Array();
  17755. // Probes
  17756. this.probesEnabled = true;
  17757. this.reflectionProbes = new Array();
  17758. this._actionManagers = new Array();
  17759. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  17760. // Procedural textures
  17761. this.proceduralTexturesEnabled = true;
  17762. this._proceduralTextures = new Array();
  17763. this.soundTracks = new Array();
  17764. this._audioEnabled = true;
  17765. this._headphone = false;
  17766. // Performance counters
  17767. this._totalVertices = new BABYLON.PerfCounter();
  17768. this._activeIndices = new BABYLON.PerfCounter();
  17769. this._activeParticles = new BABYLON.PerfCounter();
  17770. this._activeBones = new BABYLON.PerfCounter();
  17771. this._animationTime = 0;
  17772. this.animationTimeScale = 1;
  17773. this._renderId = 0;
  17774. this._executeWhenReadyTimeoutId = -1;
  17775. this._intermediateRendering = false;
  17776. this._viewUpdateFlag = -1;
  17777. this._projectionUpdateFlag = -1;
  17778. this._alternateViewUpdateFlag = -1;
  17779. this._alternateProjectionUpdateFlag = -1;
  17780. this._toBeDisposed = new BABYLON.SmartArray(256);
  17781. this._pendingData = new Array();
  17782. this._isDisposed = false;
  17783. this._activeMeshes = new BABYLON.SmartArray(256);
  17784. this._processedMaterials = new BABYLON.SmartArray(256);
  17785. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  17786. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17787. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  17788. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  17789. this._activeAnimatables = new Array();
  17790. this._transformMatrix = BABYLON.Matrix.Zero();
  17791. this._useAlternateCameraConfiguration = false;
  17792. this._alternateRendering = false;
  17793. this.requireLightSorting = false;
  17794. this._activeMeshesFrozen = false;
  17795. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17796. this._engine.scenes.push(this);
  17797. this._uid = null;
  17798. this._renderingManager = new BABYLON.RenderingManager(this);
  17799. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17800. if (BABYLON.OutlineRenderer) {
  17801. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17802. }
  17803. if (BABYLON.Tools.IsWindowObjectExist()) {
  17804. this.attachControl();
  17805. }
  17806. //simplification queue
  17807. if (BABYLON.SimplificationQueue) {
  17808. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17809. }
  17810. //collision coordinator initialization. For now legacy per default.
  17811. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17812. // Uniform Buffer
  17813. this._createUbo();
  17814. // Default Image processing definition.
  17815. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17816. }
  17817. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17818. /** The fog is deactivated */
  17819. get: function () {
  17820. return Scene._FOGMODE_NONE;
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17826. /** The fog density is following an exponential function */
  17827. get: function () {
  17828. return Scene._FOGMODE_EXP;
  17829. },
  17830. enumerable: true,
  17831. configurable: true
  17832. });
  17833. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17834. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17835. get: function () {
  17836. return Scene._FOGMODE_EXP2;
  17837. },
  17838. enumerable: true,
  17839. configurable: true
  17840. });
  17841. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17842. /** The fog density is following a linear function. */
  17843. get: function () {
  17844. return Scene._FOGMODE_LINEAR;
  17845. },
  17846. enumerable: true,
  17847. configurable: true
  17848. });
  17849. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17850. /**
  17851. * Texture used in all pbr material as the reflection texture.
  17852. * As in the majority of the scene they are the same (exception for multi room and so on),
  17853. * this is easier to reference from here than from all the materials.
  17854. */
  17855. get: function () {
  17856. return this._environmentTexture;
  17857. },
  17858. /**
  17859. * Texture used in all pbr material as the reflection texture.
  17860. * As in the majority of the scene they are the same (exception for multi room and so on),
  17861. * this is easier to set here than in all the materials.
  17862. */
  17863. set: function (value) {
  17864. if (this._environmentTexture === value) {
  17865. return;
  17866. }
  17867. this._environmentTexture = value;
  17868. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17869. },
  17870. enumerable: true,
  17871. configurable: true
  17872. });
  17873. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17874. /**
  17875. * Default image processing configuration used either in the rendering
  17876. * Forward main pass or through the imageProcessingPostProcess if present.
  17877. * As in the majority of the scene they are the same (exception for multi camera),
  17878. * this is easier to reference from here than from all the materials and post process.
  17879. *
  17880. * No setter as we it is a shared configuration, you can set the values instead.
  17881. */
  17882. get: function () {
  17883. return this._imageProcessingConfiguration;
  17884. },
  17885. enumerable: true,
  17886. configurable: true
  17887. });
  17888. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17889. get: function () {
  17890. return this._forcePointsCloud;
  17891. },
  17892. set: function (value) {
  17893. if (this._forcePointsCloud === value) {
  17894. return;
  17895. }
  17896. this._forcePointsCloud = value;
  17897. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17898. },
  17899. enumerable: true,
  17900. configurable: true
  17901. });
  17902. Object.defineProperty(Scene.prototype, "onDispose", {
  17903. /** A function to be executed when this scene is disposed. */
  17904. set: function (callback) {
  17905. if (this._onDisposeObserver) {
  17906. this.onDisposeObservable.remove(this._onDisposeObserver);
  17907. }
  17908. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17909. },
  17910. enumerable: true,
  17911. configurable: true
  17912. });
  17913. Object.defineProperty(Scene.prototype, "beforeRender", {
  17914. /** A function to be executed before rendering this scene */
  17915. set: function (callback) {
  17916. if (this._onBeforeRenderObserver) {
  17917. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17918. }
  17919. if (callback) {
  17920. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17921. }
  17922. },
  17923. enumerable: true,
  17924. configurable: true
  17925. });
  17926. Object.defineProperty(Scene.prototype, "afterRender", {
  17927. /** A function to be executed after rendering this scene */
  17928. set: function (callback) {
  17929. if (this._onAfterRenderObserver) {
  17930. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17931. }
  17932. if (callback) {
  17933. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17934. }
  17935. },
  17936. enumerable: true,
  17937. configurable: true
  17938. });
  17939. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17940. set: function (callback) {
  17941. if (this._onBeforeCameraRenderObserver) {
  17942. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17943. }
  17944. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17945. },
  17946. enumerable: true,
  17947. configurable: true
  17948. });
  17949. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17950. set: function (callback) {
  17951. if (this._onAfterCameraRenderObserver) {
  17952. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17953. }
  17954. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17955. },
  17956. enumerable: true,
  17957. configurable: true
  17958. });
  17959. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17960. get: function () {
  17961. if (!this._gamepadManager) {
  17962. this._gamepadManager = new BABYLON.GamepadManager();
  17963. }
  17964. return this._gamepadManager;
  17965. },
  17966. enumerable: true,
  17967. configurable: true
  17968. });
  17969. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17970. get: function () {
  17971. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17972. },
  17973. enumerable: true,
  17974. configurable: true
  17975. });
  17976. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17977. get: function () {
  17978. return this._useRightHandedSystem;
  17979. },
  17980. set: function (value) {
  17981. if (this._useRightHandedSystem === value) {
  17982. return;
  17983. }
  17984. this._useRightHandedSystem = value;
  17985. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17986. },
  17987. enumerable: true,
  17988. configurable: true
  17989. });
  17990. Scene.prototype.setStepId = function (newStepId) {
  17991. this._currentStepId = newStepId;
  17992. };
  17993. ;
  17994. Scene.prototype.getStepId = function () {
  17995. return this._currentStepId;
  17996. };
  17997. ;
  17998. Scene.prototype.getInternalStep = function () {
  17999. return this._currentInternalStep;
  18000. };
  18001. ;
  18002. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18003. get: function () {
  18004. return this._fogEnabled;
  18005. },
  18006. /**
  18007. * is fog enabled on this scene.
  18008. */
  18009. set: function (value) {
  18010. if (this._fogEnabled === value) {
  18011. return;
  18012. }
  18013. this._fogEnabled = value;
  18014. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18015. },
  18016. enumerable: true,
  18017. configurable: true
  18018. });
  18019. Object.defineProperty(Scene.prototype, "fogMode", {
  18020. get: function () {
  18021. return this._fogMode;
  18022. },
  18023. set: function (value) {
  18024. if (this._fogMode === value) {
  18025. return;
  18026. }
  18027. this._fogMode = value;
  18028. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18029. },
  18030. enumerable: true,
  18031. configurable: true
  18032. });
  18033. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18034. get: function () {
  18035. return this._shadowsEnabled;
  18036. },
  18037. set: function (value) {
  18038. if (this._shadowsEnabled === value) {
  18039. return;
  18040. }
  18041. this._shadowsEnabled = value;
  18042. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18043. },
  18044. enumerable: true,
  18045. configurable: true
  18046. });
  18047. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18048. get: function () {
  18049. return this._lightsEnabled;
  18050. },
  18051. set: function (value) {
  18052. if (this._lightsEnabled === value) {
  18053. return;
  18054. }
  18055. this._lightsEnabled = value;
  18056. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18057. },
  18058. enumerable: true,
  18059. configurable: true
  18060. });
  18061. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18062. /** The default material used on meshes when no material is affected */
  18063. get: function () {
  18064. if (!this._defaultMaterial) {
  18065. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18066. }
  18067. return this._defaultMaterial;
  18068. },
  18069. /** The default material used on meshes when no material is affected */
  18070. set: function (value) {
  18071. this._defaultMaterial = value;
  18072. },
  18073. enumerable: true,
  18074. configurable: true
  18075. });
  18076. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18077. get: function () {
  18078. return this._texturesEnabled;
  18079. },
  18080. set: function (value) {
  18081. if (this._texturesEnabled === value) {
  18082. return;
  18083. }
  18084. this._texturesEnabled = value;
  18085. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18086. },
  18087. enumerable: true,
  18088. configurable: true
  18089. });
  18090. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18091. get: function () {
  18092. return this._skeletonsEnabled;
  18093. },
  18094. set: function (value) {
  18095. if (this._skeletonsEnabled === value) {
  18096. return;
  18097. }
  18098. this._skeletonsEnabled = value;
  18099. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18100. },
  18101. enumerable: true,
  18102. configurable: true
  18103. });
  18104. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18105. get: function () {
  18106. if (!this._postProcessRenderPipelineManager) {
  18107. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18108. }
  18109. return this._postProcessRenderPipelineManager;
  18110. },
  18111. enumerable: true,
  18112. configurable: true
  18113. });
  18114. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18115. get: function () {
  18116. if (!this._mainSoundTrack) {
  18117. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18118. }
  18119. return this._mainSoundTrack;
  18120. },
  18121. enumerable: true,
  18122. configurable: true
  18123. });
  18124. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18125. get: function () {
  18126. return this._alternateRendering;
  18127. },
  18128. enumerable: true,
  18129. configurable: true
  18130. });
  18131. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18132. get: function () {
  18133. return this._frustumPlanes;
  18134. },
  18135. enumerable: true,
  18136. configurable: true
  18137. });
  18138. Object.defineProperty(Scene.prototype, "debugLayer", {
  18139. // Properties
  18140. get: function () {
  18141. if (!this._debugLayer) {
  18142. this._debugLayer = new BABYLON.DebugLayer(this);
  18143. }
  18144. return this._debugLayer;
  18145. },
  18146. enumerable: true,
  18147. configurable: true
  18148. });
  18149. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18150. get: function () {
  18151. return this._workerCollisions;
  18152. },
  18153. set: function (enabled) {
  18154. if (!BABYLON.CollisionCoordinatorLegacy) {
  18155. return;
  18156. }
  18157. enabled = (enabled && !!Worker);
  18158. this._workerCollisions = enabled;
  18159. if (this.collisionCoordinator) {
  18160. this.collisionCoordinator.destroy();
  18161. }
  18162. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18163. this.collisionCoordinator.init(this);
  18164. },
  18165. enumerable: true,
  18166. configurable: true
  18167. });
  18168. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18169. get: function () {
  18170. return this._selectionOctree;
  18171. },
  18172. enumerable: true,
  18173. configurable: true
  18174. });
  18175. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18176. /**
  18177. * The mesh that is currently under the pointer.
  18178. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18179. */
  18180. get: function () {
  18181. return this._pointerOverMesh;
  18182. },
  18183. enumerable: true,
  18184. configurable: true
  18185. });
  18186. Object.defineProperty(Scene.prototype, "pointerX", {
  18187. /**
  18188. * Current on-screen X position of the pointer
  18189. * @return {number} X position of the pointer
  18190. */
  18191. get: function () {
  18192. return this._pointerX;
  18193. },
  18194. enumerable: true,
  18195. configurable: true
  18196. });
  18197. Object.defineProperty(Scene.prototype, "pointerY", {
  18198. /**
  18199. * Current on-screen Y position of the pointer
  18200. * @return {number} Y position of the pointer
  18201. */
  18202. get: function () {
  18203. return this._pointerY;
  18204. },
  18205. enumerable: true,
  18206. configurable: true
  18207. });
  18208. Scene.prototype.getCachedMaterial = function () {
  18209. return this._cachedMaterial;
  18210. };
  18211. Scene.prototype.getCachedEffect = function () {
  18212. return this._cachedEffect;
  18213. };
  18214. Scene.prototype.getCachedVisibility = function () {
  18215. return this._cachedVisibility;
  18216. };
  18217. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18218. if (visibility === void 0) { visibility = 1; }
  18219. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18220. };
  18221. Scene.prototype.getBoundingBoxRenderer = function () {
  18222. if (!this._boundingBoxRenderer) {
  18223. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18224. }
  18225. return this._boundingBoxRenderer;
  18226. };
  18227. Scene.prototype.getOutlineRenderer = function () {
  18228. return this._outlineRenderer;
  18229. };
  18230. Scene.prototype.getEngine = function () {
  18231. return this._engine;
  18232. };
  18233. Scene.prototype.getTotalVertices = function () {
  18234. return this._totalVertices.current;
  18235. };
  18236. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18237. get: function () {
  18238. return this._totalVertices;
  18239. },
  18240. enumerable: true,
  18241. configurable: true
  18242. });
  18243. Scene.prototype.getActiveIndices = function () {
  18244. return this._activeIndices.current;
  18245. };
  18246. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18247. get: function () {
  18248. return this._activeIndices;
  18249. },
  18250. enumerable: true,
  18251. configurable: true
  18252. });
  18253. Scene.prototype.getActiveParticles = function () {
  18254. return this._activeParticles.current;
  18255. };
  18256. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18257. get: function () {
  18258. return this._activeParticles;
  18259. },
  18260. enumerable: true,
  18261. configurable: true
  18262. });
  18263. Scene.prototype.getActiveBones = function () {
  18264. return this._activeBones.current;
  18265. };
  18266. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18267. get: function () {
  18268. return this._activeBones;
  18269. },
  18270. enumerable: true,
  18271. configurable: true
  18272. });
  18273. // Stats
  18274. Scene.prototype.getInterFramePerfCounter = function () {
  18275. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18276. return 0;
  18277. };
  18278. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18279. get: function () {
  18280. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18281. return null;
  18282. },
  18283. enumerable: true,
  18284. configurable: true
  18285. });
  18286. Scene.prototype.getLastFrameDuration = function () {
  18287. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18288. return 0;
  18289. };
  18290. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18291. get: function () {
  18292. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18293. return null;
  18294. },
  18295. enumerable: true,
  18296. configurable: true
  18297. });
  18298. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18299. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18300. return 0;
  18301. };
  18302. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18303. get: function () {
  18304. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18305. return null;
  18306. },
  18307. enumerable: true,
  18308. configurable: true
  18309. });
  18310. Scene.prototype.getActiveMeshes = function () {
  18311. return this._activeMeshes;
  18312. };
  18313. Scene.prototype.getRenderTargetsDuration = function () {
  18314. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18315. return 0;
  18316. };
  18317. Scene.prototype.getRenderDuration = function () {
  18318. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18319. return 0;
  18320. };
  18321. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18322. get: function () {
  18323. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18324. return null;
  18325. },
  18326. enumerable: true,
  18327. configurable: true
  18328. });
  18329. Scene.prototype.getParticlesDuration = function () {
  18330. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18331. return 0;
  18332. };
  18333. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18334. get: function () {
  18335. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18336. return null;
  18337. },
  18338. enumerable: true,
  18339. configurable: true
  18340. });
  18341. Scene.prototype.getSpritesDuration = function () {
  18342. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18343. return 0;
  18344. };
  18345. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18346. get: function () {
  18347. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18348. return null;
  18349. },
  18350. enumerable: true,
  18351. configurable: true
  18352. });
  18353. Scene.prototype.getAnimationRatio = function () {
  18354. return this._animationRatio;
  18355. };
  18356. Scene.prototype.getRenderId = function () {
  18357. return this._renderId;
  18358. };
  18359. Scene.prototype.incrementRenderId = function () {
  18360. this._renderId++;
  18361. };
  18362. Scene.prototype._updatePointerPosition = function (evt) {
  18363. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18364. if (!canvasRect) {
  18365. return;
  18366. }
  18367. this._pointerX = evt.clientX - canvasRect.left;
  18368. this._pointerY = evt.clientY - canvasRect.top;
  18369. this._unTranslatedPointerX = this._pointerX;
  18370. this._unTranslatedPointerY = this._pointerY;
  18371. };
  18372. Scene.prototype._createUbo = function () {
  18373. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18374. this._sceneUbo.addUniform("viewProjection", 16);
  18375. this._sceneUbo.addUniform("view", 16);
  18376. };
  18377. Scene.prototype._createAlternateUbo = function () {
  18378. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18379. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18380. this._alternateSceneUbo.addUniform("view", 16);
  18381. };
  18382. // Pointers handling
  18383. /**
  18384. * Use this method to simulate a pointer move on a mesh
  18385. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18386. */
  18387. Scene.prototype.simulatePointerMove = function (pickResult) {
  18388. var evt = new PointerEvent("pointermove");
  18389. return this._processPointerMove(pickResult, evt);
  18390. };
  18391. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18392. var canvas = this._engine.getRenderingCanvas();
  18393. if (!canvas) {
  18394. return this;
  18395. }
  18396. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18397. this.setPointerOverSprite(null);
  18398. this.setPointerOverMesh(pickResult.pickedMesh);
  18399. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18400. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18401. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18402. }
  18403. else {
  18404. canvas.style.cursor = this.hoverCursor;
  18405. }
  18406. }
  18407. else {
  18408. canvas.style.cursor = this.defaultCursor;
  18409. }
  18410. }
  18411. else {
  18412. this.setPointerOverMesh(null);
  18413. // Sprites
  18414. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18415. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18416. this.setPointerOverSprite(pickResult.pickedSprite);
  18417. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18418. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18419. }
  18420. else {
  18421. canvas.style.cursor = this.hoverCursor;
  18422. }
  18423. }
  18424. else {
  18425. this.setPointerOverSprite(null);
  18426. // Restore pointer
  18427. canvas.style.cursor = this.defaultCursor;
  18428. }
  18429. }
  18430. if (pickResult) {
  18431. if (this.onPointerMove) {
  18432. this.onPointerMove(evt, pickResult);
  18433. }
  18434. if (this.onPointerObservable.hasObservers()) {
  18435. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18436. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18437. this.onPointerObservable.notifyObservers(pi, type);
  18438. }
  18439. }
  18440. return this;
  18441. };
  18442. /**
  18443. * Use this method to simulate a pointer down on a mesh
  18444. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18445. */
  18446. Scene.prototype.simulatePointerDown = function (pickResult) {
  18447. var evt = new PointerEvent("pointerdown");
  18448. return this._processPointerDown(pickResult, evt);
  18449. };
  18450. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18451. var _this = this;
  18452. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18453. this._pickedDownMesh = pickResult.pickedMesh;
  18454. var actionManager = pickResult.pickedMesh.actionManager;
  18455. if (actionManager) {
  18456. if (actionManager.hasPickTriggers) {
  18457. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18458. switch (evt.button) {
  18459. case 0:
  18460. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18461. break;
  18462. case 1:
  18463. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18464. break;
  18465. case 2:
  18466. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18467. break;
  18468. }
  18469. }
  18470. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18471. window.setTimeout(function () {
  18472. 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);
  18473. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18474. if (_this._totalPointersPressed !== 0 &&
  18475. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18476. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18477. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18478. _this._startingPointerTime = 0;
  18479. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18480. }
  18481. }
  18482. }, Scene.LongPressDelay);
  18483. }
  18484. }
  18485. }
  18486. if (pickResult) {
  18487. if (this.onPointerDown) {
  18488. this.onPointerDown(evt, pickResult);
  18489. }
  18490. if (this.onPointerObservable.hasObservers()) {
  18491. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18492. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18493. this.onPointerObservable.notifyObservers(pi, type);
  18494. }
  18495. }
  18496. return this;
  18497. };
  18498. /**
  18499. * Use this method to simulate a pointer up on a mesh
  18500. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18501. */
  18502. Scene.prototype.simulatePointerUp = function (pickResult) {
  18503. var evt = new PointerEvent("pointerup");
  18504. var clickInfo = new ClickInfo();
  18505. clickInfo.singleClick = true;
  18506. return this._processPointerUp(pickResult, evt, clickInfo);
  18507. };
  18508. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18509. if (pickResult && pickResult && pickResult.pickedMesh) {
  18510. this._pickedUpMesh = pickResult.pickedMesh;
  18511. if (this._pickedDownMesh === this._pickedUpMesh) {
  18512. if (this.onPointerPick) {
  18513. this.onPointerPick(evt, pickResult);
  18514. }
  18515. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18516. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18517. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18518. this.onPointerObservable.notifyObservers(pi, type);
  18519. }
  18520. }
  18521. if (pickResult.pickedMesh.actionManager) {
  18522. if (clickInfo.ignore) {
  18523. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18524. }
  18525. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18526. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18527. }
  18528. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18529. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18530. }
  18531. }
  18532. }
  18533. if (this._pickedDownMesh &&
  18534. this._pickedDownMesh.actionManager &&
  18535. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18536. this._pickedDownMesh !== this._pickedUpMesh) {
  18537. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18538. }
  18539. if (this.onPointerUp) {
  18540. this.onPointerUp(evt, pickResult);
  18541. }
  18542. if (this.onPointerObservable.hasObservers()) {
  18543. if (!clickInfo.ignore) {
  18544. if (!clickInfo.hasSwiped) {
  18545. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18546. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18547. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18548. this.onPointerObservable.notifyObservers(pi, type);
  18549. }
  18550. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18551. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18552. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18553. this.onPointerObservable.notifyObservers(pi, type);
  18554. }
  18555. }
  18556. }
  18557. else {
  18558. var type = BABYLON.PointerEventTypes.POINTERUP;
  18559. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18560. this.onPointerObservable.notifyObservers(pi, type);
  18561. }
  18562. }
  18563. return this;
  18564. };
  18565. /**
  18566. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18567. * @param attachUp defines if you want to attach events to pointerup
  18568. * @param attachDown defines if you want to attach events to pointerdown
  18569. * @param attachMove defines if you want to attach events to pointermove
  18570. */
  18571. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18572. var _this = this;
  18573. if (attachUp === void 0) { attachUp = true; }
  18574. if (attachDown === void 0) { attachDown = true; }
  18575. if (attachMove === void 0) { attachMove = true; }
  18576. this._initActionManager = function (act, clickInfo) {
  18577. if (!_this._meshPickProceed) {
  18578. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18579. _this._currentPickResult = pickResult;
  18580. if (pickResult) {
  18581. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18582. }
  18583. _this._meshPickProceed = true;
  18584. }
  18585. return act;
  18586. };
  18587. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18588. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18589. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18590. btn !== _this._previousButtonPressed) {
  18591. _this._doubleClickOccured = false;
  18592. clickInfo.singleClick = true;
  18593. clickInfo.ignore = false;
  18594. cb(clickInfo, _this._currentPickResult);
  18595. }
  18596. };
  18597. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18598. var clickInfo = new ClickInfo();
  18599. _this._currentPickResult = null;
  18600. var act = null;
  18601. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18602. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18603. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18604. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18605. act = _this._initActionManager(act, clickInfo);
  18606. if (act)
  18607. checkPicking = act.hasPickTriggers;
  18608. }
  18609. if (checkPicking) {
  18610. var btn = evt.button;
  18611. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18612. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18613. if (!clickInfo.hasSwiped) {
  18614. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18615. if (!checkSingleClickImmediately) {
  18616. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18617. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18618. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18619. act = _this._initActionManager(act, clickInfo);
  18620. if (act)
  18621. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18622. }
  18623. }
  18624. if (checkSingleClickImmediately) {
  18625. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18626. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18627. btn !== _this._previousButtonPressed) {
  18628. clickInfo.singleClick = true;
  18629. cb(clickInfo, _this._currentPickResult);
  18630. }
  18631. }
  18632. else {
  18633. // wait that no double click has been raised during the double click delay
  18634. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18635. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18636. }
  18637. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18638. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18639. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18640. act = _this._initActionManager(act, clickInfo);
  18641. if (act)
  18642. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18643. }
  18644. if (checkDoubleClick) {
  18645. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18646. if (btn === _this._previousButtonPressed &&
  18647. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18648. !_this._doubleClickOccured) {
  18649. // pointer has not moved for 2 clicks, it's a double click
  18650. if (!clickInfo.hasSwiped &&
  18651. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18652. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18653. _this._previousStartingPointerTime = 0;
  18654. _this._doubleClickOccured = true;
  18655. clickInfo.doubleClick = true;
  18656. clickInfo.ignore = false;
  18657. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18658. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18659. }
  18660. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18661. cb(clickInfo, _this._currentPickResult);
  18662. }
  18663. else {
  18664. _this._doubleClickOccured = false;
  18665. _this._previousStartingPointerTime = _this._startingPointerTime;
  18666. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18667. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18668. _this._previousButtonPressed = btn;
  18669. _this._previousHasSwiped = clickInfo.hasSwiped;
  18670. if (Scene.ExclusiveDoubleClickMode) {
  18671. if (_this._previousDelayedSimpleClickTimeout) {
  18672. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18673. }
  18674. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18675. cb(clickInfo, _this._previousPickResult);
  18676. }
  18677. else {
  18678. cb(clickInfo, _this._currentPickResult);
  18679. }
  18680. }
  18681. }
  18682. else {
  18683. _this._doubleClickOccured = false;
  18684. _this._previousStartingPointerTime = _this._startingPointerTime;
  18685. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18686. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18687. _this._previousButtonPressed = btn;
  18688. _this._previousHasSwiped = clickInfo.hasSwiped;
  18689. }
  18690. }
  18691. }
  18692. }
  18693. clickInfo.ignore = true;
  18694. cb(clickInfo, _this._currentPickResult);
  18695. };
  18696. this._spritePredicate = function (sprite) {
  18697. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18698. };
  18699. this._onPointerMove = function (evt) {
  18700. _this._updatePointerPosition(evt);
  18701. // PreObservable support
  18702. if (_this.onPrePointerObservable.hasObservers()) {
  18703. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18704. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18705. _this.onPrePointerObservable.notifyObservers(pi, type);
  18706. if (pi.skipOnPointerObservable) {
  18707. return;
  18708. }
  18709. }
  18710. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18711. return;
  18712. }
  18713. if (!_this.pointerMovePredicate) {
  18714. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18715. }
  18716. // Meshes
  18717. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18718. _this._processPointerMove(pickResult, evt);
  18719. };
  18720. this._onPointerDown = function (evt) {
  18721. _this._totalPointersPressed++;
  18722. _this._pickedDownMesh = null;
  18723. _this._meshPickProceed = false;
  18724. _this._updatePointerPosition(evt);
  18725. if (_this.preventDefaultOnPointerDown && canvas) {
  18726. evt.preventDefault();
  18727. canvas.focus();
  18728. }
  18729. // PreObservable support
  18730. if (_this.onPrePointerObservable.hasObservers()) {
  18731. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18732. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18733. _this.onPrePointerObservable.notifyObservers(pi, type);
  18734. if (pi.skipOnPointerObservable) {
  18735. return;
  18736. }
  18737. }
  18738. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18739. return;
  18740. }
  18741. _this._startingPointerPosition.x = _this._pointerX;
  18742. _this._startingPointerPosition.y = _this._pointerY;
  18743. _this._startingPointerTime = new Date().getTime();
  18744. if (!_this.pointerDownPredicate) {
  18745. _this.pointerDownPredicate = function (mesh) {
  18746. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18747. };
  18748. }
  18749. // Meshes
  18750. _this._pickedDownMesh = null;
  18751. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18752. _this._processPointerDown(pickResult, evt);
  18753. // Sprites
  18754. _this._pickedDownSprite = null;
  18755. if (_this.spriteManagers.length > 0) {
  18756. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18757. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18758. if (pickResult.pickedSprite.actionManager) {
  18759. _this._pickedDownSprite = pickResult.pickedSprite;
  18760. switch (evt.button) {
  18761. case 0:
  18762. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18763. break;
  18764. case 1:
  18765. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18766. break;
  18767. case 2:
  18768. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18769. break;
  18770. }
  18771. if (pickResult.pickedSprite.actionManager) {
  18772. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18773. }
  18774. }
  18775. }
  18776. }
  18777. };
  18778. this._onPointerUp = function (evt) {
  18779. if (_this._totalPointersPressed === 0) {
  18780. return; // So we need to test it the pointer down was pressed before.
  18781. }
  18782. _this._totalPointersPressed--;
  18783. _this._pickedUpMesh = null;
  18784. _this._meshPickProceed = false;
  18785. _this._updatePointerPosition(evt);
  18786. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18787. // PreObservable support
  18788. if (_this.onPrePointerObservable.hasObservers()) {
  18789. if (!clickInfo.ignore) {
  18790. if (!clickInfo.hasSwiped) {
  18791. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18792. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18793. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18794. _this.onPrePointerObservable.notifyObservers(pi, type);
  18795. if (pi.skipOnPointerObservable) {
  18796. return;
  18797. }
  18798. }
  18799. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18800. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18801. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18802. _this.onPrePointerObservable.notifyObservers(pi, type);
  18803. if (pi.skipOnPointerObservable) {
  18804. return;
  18805. }
  18806. }
  18807. }
  18808. }
  18809. else {
  18810. var type = BABYLON.PointerEventTypes.POINTERUP;
  18811. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18812. _this.onPrePointerObservable.notifyObservers(pi, type);
  18813. if (pi.skipOnPointerObservable) {
  18814. return;
  18815. }
  18816. }
  18817. }
  18818. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18819. return;
  18820. }
  18821. if (!_this.pointerUpPredicate) {
  18822. _this.pointerUpPredicate = function (mesh) {
  18823. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18824. };
  18825. }
  18826. // Meshes
  18827. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18828. _this._initActionManager(null, clickInfo);
  18829. }
  18830. if (!pickResult) {
  18831. pickResult = _this._currentPickResult;
  18832. }
  18833. _this._processPointerUp(pickResult, evt, clickInfo);
  18834. // Sprites
  18835. if (_this.spriteManagers.length > 0) {
  18836. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18837. if (spritePickResult) {
  18838. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18839. if (spritePickResult.pickedSprite.actionManager) {
  18840. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18841. if (spritePickResult.pickedSprite.actionManager) {
  18842. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18843. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18844. }
  18845. }
  18846. }
  18847. }
  18848. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18849. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18850. }
  18851. }
  18852. }
  18853. _this._previousPickResult = _this._currentPickResult;
  18854. });
  18855. };
  18856. this._onKeyDown = function (evt) {
  18857. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18858. if (_this.onPreKeyboardObservable.hasObservers()) {
  18859. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18860. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18861. if (pi.skipOnPointerObservable) {
  18862. return;
  18863. }
  18864. }
  18865. if (_this.onKeyboardObservable.hasObservers()) {
  18866. var pi = new BABYLON.KeyboardInfo(type, evt);
  18867. _this.onKeyboardObservable.notifyObservers(pi, type);
  18868. }
  18869. if (_this.actionManager) {
  18870. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18871. }
  18872. };
  18873. this._onKeyUp = function (evt) {
  18874. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18875. if (_this.onPreKeyboardObservable.hasObservers()) {
  18876. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18877. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18878. if (pi.skipOnPointerObservable) {
  18879. return;
  18880. }
  18881. }
  18882. if (_this.onKeyboardObservable.hasObservers()) {
  18883. var pi = new BABYLON.KeyboardInfo(type, evt);
  18884. _this.onKeyboardObservable.notifyObservers(pi, type);
  18885. }
  18886. if (_this.actionManager) {
  18887. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18888. }
  18889. };
  18890. var engine = this.getEngine();
  18891. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18892. if (!canvas) {
  18893. return;
  18894. }
  18895. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18896. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18897. });
  18898. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18899. if (!canvas) {
  18900. return;
  18901. }
  18902. canvas.removeEventListener("keydown", _this._onKeyDown);
  18903. canvas.removeEventListener("keyup", _this._onKeyUp);
  18904. });
  18905. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18906. var canvas = this._engine.getRenderingCanvas();
  18907. if (!canvas) {
  18908. return;
  18909. }
  18910. if (attachMove) {
  18911. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18912. // Wheel
  18913. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18914. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18915. }
  18916. if (attachDown) {
  18917. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18918. }
  18919. if (attachUp) {
  18920. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18921. }
  18922. canvas.tabIndex = 1;
  18923. };
  18924. Scene.prototype.detachControl = function () {
  18925. var engine = this.getEngine();
  18926. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18927. var canvas = engine.getRenderingCanvas();
  18928. if (!canvas) {
  18929. return;
  18930. }
  18931. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18932. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18933. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18934. if (this._onCanvasBlurObserver) {
  18935. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18936. }
  18937. if (this._onCanvasFocusObserver) {
  18938. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18939. }
  18940. // Wheel
  18941. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18942. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18943. // Keyboard
  18944. canvas.removeEventListener("keydown", this._onKeyDown);
  18945. canvas.removeEventListener("keyup", this._onKeyUp);
  18946. // Observables
  18947. this.onKeyboardObservable.clear();
  18948. this.onPreKeyboardObservable.clear();
  18949. this.onPointerObservable.clear();
  18950. this.onPrePointerObservable.clear();
  18951. };
  18952. // Ready
  18953. Scene.prototype.isReady = function () {
  18954. if (this._isDisposed) {
  18955. return false;
  18956. }
  18957. if (this._pendingData.length > 0) {
  18958. return false;
  18959. }
  18960. var index;
  18961. // Geometries
  18962. for (index = 0; index < this._geometries.length; index++) {
  18963. var geometry = this._geometries[index];
  18964. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18965. return false;
  18966. }
  18967. }
  18968. // Meshes
  18969. for (index = 0; index < this.meshes.length; index++) {
  18970. var mesh = this.meshes[index];
  18971. if (!mesh.isEnabled()) {
  18972. continue;
  18973. }
  18974. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18975. continue;
  18976. }
  18977. if (!mesh.isReady()) {
  18978. return false;
  18979. }
  18980. var mat = mesh.material;
  18981. if (mat) {
  18982. if (!mat.isReady(mesh)) {
  18983. return false;
  18984. }
  18985. }
  18986. }
  18987. return true;
  18988. };
  18989. Scene.prototype.resetCachedMaterial = function () {
  18990. this._cachedMaterial = null;
  18991. this._cachedEffect = null;
  18992. this._cachedVisibility = null;
  18993. };
  18994. Scene.prototype.registerBeforeRender = function (func) {
  18995. this.onBeforeRenderObservable.add(func);
  18996. };
  18997. Scene.prototype.unregisterBeforeRender = function (func) {
  18998. this.onBeforeRenderObservable.removeCallback(func);
  18999. };
  19000. Scene.prototype.registerAfterRender = function (func) {
  19001. this.onAfterRenderObservable.add(func);
  19002. };
  19003. Scene.prototype.unregisterAfterRender = function (func) {
  19004. this.onAfterRenderObservable.removeCallback(func);
  19005. };
  19006. Scene.prototype._addPendingData = function (data) {
  19007. this._pendingData.push(data);
  19008. };
  19009. Scene.prototype._removePendingData = function (data) {
  19010. var wasLoading = this.isLoading;
  19011. var index = this._pendingData.indexOf(data);
  19012. if (index !== -1) {
  19013. this._pendingData.splice(index, 1);
  19014. }
  19015. if (wasLoading && !this.isLoading) {
  19016. this.onDataLoadedObservable.notifyObservers(this);
  19017. }
  19018. };
  19019. Scene.prototype.getWaitingItemsCount = function () {
  19020. return this._pendingData.length;
  19021. };
  19022. Object.defineProperty(Scene.prototype, "isLoading", {
  19023. get: function () {
  19024. return this._pendingData.length > 0;
  19025. },
  19026. enumerable: true,
  19027. configurable: true
  19028. });
  19029. /**
  19030. * Registers a function to be executed when the scene is ready.
  19031. * @param {Function} func - the function to be executed.
  19032. */
  19033. Scene.prototype.executeWhenReady = function (func) {
  19034. var _this = this;
  19035. this.onReadyObservable.add(func);
  19036. if (this._executeWhenReadyTimeoutId !== -1) {
  19037. return;
  19038. }
  19039. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19040. _this._checkIsReady();
  19041. }, 150);
  19042. };
  19043. Scene.prototype._checkIsReady = function () {
  19044. var _this = this;
  19045. if (this.isReady()) {
  19046. this.onReadyObservable.notifyObservers(this);
  19047. this.onReadyObservable.clear();
  19048. this._executeWhenReadyTimeoutId = -1;
  19049. return;
  19050. }
  19051. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19052. _this._checkIsReady();
  19053. }, 150);
  19054. };
  19055. // Animations
  19056. /**
  19057. * Will start the animation sequence of a given target
  19058. * @param target - the target
  19059. * @param {number} from - from which frame should animation start
  19060. * @param {number} to - till which frame should animation run.
  19061. * @param {boolean} [loop] - should the animation loop
  19062. * @param {number} [speedRatio] - the speed in which to run the animation
  19063. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19064. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19065. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19066. * See BABYLON.Animatable
  19067. */
  19068. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19069. if (speedRatio === void 0) { speedRatio = 1.0; }
  19070. if (from > to && speedRatio > 0) {
  19071. speedRatio *= -1;
  19072. }
  19073. this.stopAnimation(target);
  19074. if (!animatable) {
  19075. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19076. }
  19077. // Local animations
  19078. if (target.animations) {
  19079. animatable.appendAnimations(target, target.animations);
  19080. }
  19081. // Children animations
  19082. if (target.getAnimatables) {
  19083. var animatables = target.getAnimatables();
  19084. for (var index = 0; index < animatables.length; index++) {
  19085. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19086. }
  19087. }
  19088. animatable.reset();
  19089. return animatable;
  19090. };
  19091. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19092. if (speedRatio === undefined) {
  19093. speedRatio = 1.0;
  19094. }
  19095. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19096. return animatable;
  19097. };
  19098. Scene.prototype.getAnimatableByTarget = function (target) {
  19099. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19100. if (this._activeAnimatables[index].target === target) {
  19101. return this._activeAnimatables[index];
  19102. }
  19103. }
  19104. return null;
  19105. };
  19106. Object.defineProperty(Scene.prototype, "Animatables", {
  19107. get: function () {
  19108. return this._activeAnimatables;
  19109. },
  19110. enumerable: true,
  19111. configurable: true
  19112. });
  19113. /**
  19114. * Will stop the animation of the given target
  19115. * @param target - the target
  19116. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19117. * @see beginAnimation
  19118. */
  19119. Scene.prototype.stopAnimation = function (target, animationName) {
  19120. var animatable = this.getAnimatableByTarget(target);
  19121. if (animatable) {
  19122. animatable.stop(animationName);
  19123. }
  19124. };
  19125. Scene.prototype._animate = function () {
  19126. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19127. return;
  19128. }
  19129. // Getting time
  19130. var now = BABYLON.Tools.Now;
  19131. if (!this._animationTimeLast) {
  19132. if (this._pendingData.length > 0) {
  19133. return;
  19134. }
  19135. this._animationTimeLast = now;
  19136. }
  19137. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  19138. this._animationTime += deltaTime;
  19139. this._animationTimeLast = now;
  19140. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19141. this._activeAnimatables[index]._animate(this._animationTime);
  19142. }
  19143. };
  19144. // Matrix
  19145. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19146. this._useAlternateCameraConfiguration = active;
  19147. };
  19148. Scene.prototype.getViewMatrix = function () {
  19149. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19150. };
  19151. Scene.prototype.getProjectionMatrix = function () {
  19152. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19153. };
  19154. Scene.prototype.getTransformMatrix = function () {
  19155. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19156. };
  19157. Scene.prototype.setTransformMatrix = function (view, projection) {
  19158. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19159. return;
  19160. }
  19161. this._viewUpdateFlag = view.updateFlag;
  19162. this._projectionUpdateFlag = projection.updateFlag;
  19163. this._viewMatrix = view;
  19164. this._projectionMatrix = projection;
  19165. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19166. // Update frustum
  19167. if (!this._frustumPlanes) {
  19168. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19169. }
  19170. else {
  19171. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19172. }
  19173. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19174. var otherCamera = this.activeCamera._alternateCamera;
  19175. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19176. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19177. }
  19178. if (this._sceneUbo.useUbo) {
  19179. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19180. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19181. this._sceneUbo.update();
  19182. }
  19183. };
  19184. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19185. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19186. return;
  19187. }
  19188. this._alternateViewUpdateFlag = view.updateFlag;
  19189. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19190. this._alternateViewMatrix = view;
  19191. this._alternateProjectionMatrix = projection;
  19192. if (!this._alternateTransformMatrix) {
  19193. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19194. }
  19195. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19196. if (!this._alternateSceneUbo) {
  19197. this._createAlternateUbo();
  19198. }
  19199. if (this._alternateSceneUbo.useUbo) {
  19200. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19201. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19202. this._alternateSceneUbo.update();
  19203. }
  19204. };
  19205. Scene.prototype.getSceneUniformBuffer = function () {
  19206. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19207. };
  19208. // Methods
  19209. Scene.prototype.getUniqueId = function () {
  19210. var result = Scene._uniqueIdCounter;
  19211. Scene._uniqueIdCounter++;
  19212. return result;
  19213. };
  19214. Scene.prototype.addMesh = function (newMesh) {
  19215. this.meshes.push(newMesh);
  19216. //notify the collision coordinator
  19217. if (this.collisionCoordinator) {
  19218. this.collisionCoordinator.onMeshAdded(newMesh);
  19219. }
  19220. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19221. };
  19222. Scene.prototype.removeMesh = function (toRemove) {
  19223. var index = this.meshes.indexOf(toRemove);
  19224. if (index !== -1) {
  19225. // Remove from the scene if mesh found
  19226. this.meshes.splice(index, 1);
  19227. }
  19228. //notify the collision coordinator
  19229. if (this.collisionCoordinator) {
  19230. this.collisionCoordinator.onMeshRemoved(toRemove);
  19231. }
  19232. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19233. return index;
  19234. };
  19235. Scene.prototype.removeSkeleton = function (toRemove) {
  19236. var index = this.skeletons.indexOf(toRemove);
  19237. if (index !== -1) {
  19238. // Remove from the scene if found
  19239. this.skeletons.splice(index, 1);
  19240. }
  19241. return index;
  19242. };
  19243. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19244. var index = this.morphTargetManagers.indexOf(toRemove);
  19245. if (index !== -1) {
  19246. // Remove from the scene if found
  19247. this.morphTargetManagers.splice(index, 1);
  19248. }
  19249. return index;
  19250. };
  19251. Scene.prototype.removeLight = function (toRemove) {
  19252. var index = this.lights.indexOf(toRemove);
  19253. if (index !== -1) {
  19254. // Remove from the scene if mesh found
  19255. this.lights.splice(index, 1);
  19256. this.sortLightsByPriority();
  19257. }
  19258. this.onLightRemovedObservable.notifyObservers(toRemove);
  19259. return index;
  19260. };
  19261. Scene.prototype.removeCamera = function (toRemove) {
  19262. var index = this.cameras.indexOf(toRemove);
  19263. if (index !== -1) {
  19264. // Remove from the scene if mesh found
  19265. this.cameras.splice(index, 1);
  19266. }
  19267. // Remove from activeCameras
  19268. var index2 = this.activeCameras.indexOf(toRemove);
  19269. if (index2 !== -1) {
  19270. // Remove from the scene if mesh found
  19271. this.activeCameras.splice(index2, 1);
  19272. }
  19273. // Reset the activeCamera
  19274. if (this.activeCamera === toRemove) {
  19275. if (this.cameras.length > 0) {
  19276. this.activeCamera = this.cameras[0];
  19277. }
  19278. else {
  19279. this.activeCamera = null;
  19280. }
  19281. }
  19282. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19283. return index;
  19284. };
  19285. Scene.prototype.addLight = function (newLight) {
  19286. this.lights.push(newLight);
  19287. this.sortLightsByPriority();
  19288. this.onNewLightAddedObservable.notifyObservers(newLight);
  19289. };
  19290. Scene.prototype.sortLightsByPriority = function () {
  19291. if (this.requireLightSorting) {
  19292. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19293. }
  19294. };
  19295. Scene.prototype.addCamera = function (newCamera) {
  19296. this.cameras.push(newCamera);
  19297. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19298. };
  19299. /**
  19300. * Switch active camera
  19301. * @param {Camera} newCamera - new active camera
  19302. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19303. */
  19304. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19305. if (attachControl === void 0) { attachControl = true; }
  19306. var canvas = this._engine.getRenderingCanvas();
  19307. if (!canvas) {
  19308. return;
  19309. }
  19310. if (this.activeCamera) {
  19311. this.activeCamera.detachControl(canvas);
  19312. }
  19313. this.activeCamera = newCamera;
  19314. if (attachControl) {
  19315. newCamera.attachControl(canvas);
  19316. }
  19317. };
  19318. /**
  19319. * sets the active camera of the scene using its ID
  19320. * @param {string} id - the camera's ID
  19321. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19322. * @see activeCamera
  19323. */
  19324. Scene.prototype.setActiveCameraByID = function (id) {
  19325. var camera = this.getCameraByID(id);
  19326. if (camera) {
  19327. this.activeCamera = camera;
  19328. return camera;
  19329. }
  19330. return null;
  19331. };
  19332. /**
  19333. * sets the active camera of the scene using its name
  19334. * @param {string} name - the camera's name
  19335. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19336. * @see activeCamera
  19337. */
  19338. Scene.prototype.setActiveCameraByName = function (name) {
  19339. var camera = this.getCameraByName(name);
  19340. if (camera) {
  19341. this.activeCamera = camera;
  19342. return camera;
  19343. }
  19344. return null;
  19345. };
  19346. /**
  19347. * get a material using its id
  19348. * @param {string} the material's ID
  19349. * @return {BABYLON.Material|null} the material or null if none found.
  19350. */
  19351. Scene.prototype.getMaterialByID = function (id) {
  19352. for (var index = 0; index < this.materials.length; index++) {
  19353. if (this.materials[index].id === id) {
  19354. return this.materials[index];
  19355. }
  19356. }
  19357. return null;
  19358. };
  19359. /**
  19360. * get a material using its name
  19361. * @param {string} the material's name
  19362. * @return {BABYLON.Material|null} the material or null if none found.
  19363. */
  19364. Scene.prototype.getMaterialByName = function (name) {
  19365. for (var index = 0; index < this.materials.length; index++) {
  19366. if (this.materials[index].name === name) {
  19367. return this.materials[index];
  19368. }
  19369. }
  19370. return null;
  19371. };
  19372. Scene.prototype.getLensFlareSystemByName = function (name) {
  19373. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19374. if (this.lensFlareSystems[index].name === name) {
  19375. return this.lensFlareSystems[index];
  19376. }
  19377. }
  19378. return null;
  19379. };
  19380. Scene.prototype.getLensFlareSystemByID = function (id) {
  19381. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19382. if (this.lensFlareSystems[index].id === id) {
  19383. return this.lensFlareSystems[index];
  19384. }
  19385. }
  19386. return null;
  19387. };
  19388. Scene.prototype.getCameraByID = function (id) {
  19389. for (var index = 0; index < this.cameras.length; index++) {
  19390. if (this.cameras[index].id === id) {
  19391. return this.cameras[index];
  19392. }
  19393. }
  19394. return null;
  19395. };
  19396. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19397. for (var index = 0; index < this.cameras.length; index++) {
  19398. if (this.cameras[index].uniqueId === uniqueId) {
  19399. return this.cameras[index];
  19400. }
  19401. }
  19402. return null;
  19403. };
  19404. /**
  19405. * get a camera using its name
  19406. * @param {string} the camera's name
  19407. * @return {BABYLON.Camera|null} the camera or null if none found.
  19408. */
  19409. Scene.prototype.getCameraByName = function (name) {
  19410. for (var index = 0; index < this.cameras.length; index++) {
  19411. if (this.cameras[index].name === name) {
  19412. return this.cameras[index];
  19413. }
  19414. }
  19415. return null;
  19416. };
  19417. /**
  19418. * get a bone using its id
  19419. * @param {string} the bone's id
  19420. * @return {BABYLON.Bone|null} the bone or null if not found
  19421. */
  19422. Scene.prototype.getBoneByID = function (id) {
  19423. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19424. var skeleton = this.skeletons[skeletonIndex];
  19425. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19426. if (skeleton.bones[boneIndex].id === id) {
  19427. return skeleton.bones[boneIndex];
  19428. }
  19429. }
  19430. }
  19431. return null;
  19432. };
  19433. /**
  19434. * get a bone using its id
  19435. * @param {string} the bone's name
  19436. * @return {BABYLON.Bone|null} the bone or null if not found
  19437. */
  19438. Scene.prototype.getBoneByName = function (name) {
  19439. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19440. var skeleton = this.skeletons[skeletonIndex];
  19441. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19442. if (skeleton.bones[boneIndex].name === name) {
  19443. return skeleton.bones[boneIndex];
  19444. }
  19445. }
  19446. }
  19447. return null;
  19448. };
  19449. /**
  19450. * get a light node using its name
  19451. * @param {string} the light's name
  19452. * @return {BABYLON.Light|null} the light or null if none found.
  19453. */
  19454. Scene.prototype.getLightByName = function (name) {
  19455. for (var index = 0; index < this.lights.length; index++) {
  19456. if (this.lights[index].name === name) {
  19457. return this.lights[index];
  19458. }
  19459. }
  19460. return null;
  19461. };
  19462. /**
  19463. * get a light node using its ID
  19464. * @param {string} the light's id
  19465. * @return {BABYLON.Light|null} the light or null if none found.
  19466. */
  19467. Scene.prototype.getLightByID = function (id) {
  19468. for (var index = 0; index < this.lights.length; index++) {
  19469. if (this.lights[index].id === id) {
  19470. return this.lights[index];
  19471. }
  19472. }
  19473. return null;
  19474. };
  19475. /**
  19476. * get a light node using its scene-generated unique ID
  19477. * @param {number} the light's unique id
  19478. * @return {BABYLON.Light|null} the light or null if none found.
  19479. */
  19480. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19481. for (var index = 0; index < this.lights.length; index++) {
  19482. if (this.lights[index].uniqueId === uniqueId) {
  19483. return this.lights[index];
  19484. }
  19485. }
  19486. return null;
  19487. };
  19488. /**
  19489. * get a particle system by id
  19490. * @param id {number} the particle system id
  19491. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19492. */
  19493. Scene.prototype.getParticleSystemByID = function (id) {
  19494. for (var index = 0; index < this.particleSystems.length; index++) {
  19495. if (this.particleSystems[index].id === id) {
  19496. return this.particleSystems[index];
  19497. }
  19498. }
  19499. return null;
  19500. };
  19501. /**
  19502. * get a geometry using its ID
  19503. * @param {string} the geometry's id
  19504. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19505. */
  19506. Scene.prototype.getGeometryByID = function (id) {
  19507. for (var index = 0; index < this._geometries.length; index++) {
  19508. if (this._geometries[index].id === id) {
  19509. return this._geometries[index];
  19510. }
  19511. }
  19512. return null;
  19513. };
  19514. /**
  19515. * add a new geometry to this scene.
  19516. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19517. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19518. * @return {boolean} was the geometry added or not
  19519. */
  19520. Scene.prototype.pushGeometry = function (geometry, force) {
  19521. if (!force && this.getGeometryByID(geometry.id)) {
  19522. return false;
  19523. }
  19524. this._geometries.push(geometry);
  19525. //notify the collision coordinator
  19526. if (this.collisionCoordinator) {
  19527. this.collisionCoordinator.onGeometryAdded(geometry);
  19528. }
  19529. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19530. return true;
  19531. };
  19532. /**
  19533. * Removes an existing geometry
  19534. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19535. * @return {boolean} was the geometry removed or not
  19536. */
  19537. Scene.prototype.removeGeometry = function (geometry) {
  19538. var index = this._geometries.indexOf(geometry);
  19539. if (index > -1) {
  19540. this._geometries.splice(index, 1);
  19541. //notify the collision coordinator
  19542. if (this.collisionCoordinator) {
  19543. this.collisionCoordinator.onGeometryDeleted(geometry);
  19544. }
  19545. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19546. return true;
  19547. }
  19548. return false;
  19549. };
  19550. Scene.prototype.getGeometries = function () {
  19551. return this._geometries;
  19552. };
  19553. /**
  19554. * Get the first added mesh found of a given ID
  19555. * @param {string} id - the id to search for
  19556. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19557. */
  19558. Scene.prototype.getMeshByID = function (id) {
  19559. for (var index = 0; index < this.meshes.length; index++) {
  19560. if (this.meshes[index].id === id) {
  19561. return this.meshes[index];
  19562. }
  19563. }
  19564. return null;
  19565. };
  19566. Scene.prototype.getMeshesByID = function (id) {
  19567. return this.meshes.filter(function (m) {
  19568. return m.id === id;
  19569. });
  19570. };
  19571. /**
  19572. * Get a mesh with its auto-generated unique id
  19573. * @param {number} uniqueId - the unique id to search for
  19574. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19575. */
  19576. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19577. for (var index = 0; index < this.meshes.length; index++) {
  19578. if (this.meshes[index].uniqueId === uniqueId) {
  19579. return this.meshes[index];
  19580. }
  19581. }
  19582. return null;
  19583. };
  19584. /**
  19585. * Get a the last added mesh found of a given ID
  19586. * @param {string} id - the id to search for
  19587. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19588. */
  19589. Scene.prototype.getLastMeshByID = function (id) {
  19590. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19591. if (this.meshes[index].id === id) {
  19592. return this.meshes[index];
  19593. }
  19594. }
  19595. return null;
  19596. };
  19597. /**
  19598. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19599. * @param {string} id - the id to search for
  19600. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19601. */
  19602. Scene.prototype.getLastEntryByID = function (id) {
  19603. var index;
  19604. for (index = this.meshes.length - 1; index >= 0; index--) {
  19605. if (this.meshes[index].id === id) {
  19606. return this.meshes[index];
  19607. }
  19608. }
  19609. for (index = this.cameras.length - 1; index >= 0; index--) {
  19610. if (this.cameras[index].id === id) {
  19611. return this.cameras[index];
  19612. }
  19613. }
  19614. for (index = this.lights.length - 1; index >= 0; index--) {
  19615. if (this.lights[index].id === id) {
  19616. return this.lights[index];
  19617. }
  19618. }
  19619. return null;
  19620. };
  19621. Scene.prototype.getNodeByID = function (id) {
  19622. var mesh = this.getMeshByID(id);
  19623. if (mesh) {
  19624. return mesh;
  19625. }
  19626. var light = this.getLightByID(id);
  19627. if (light) {
  19628. return light;
  19629. }
  19630. var camera = this.getCameraByID(id);
  19631. if (camera) {
  19632. return camera;
  19633. }
  19634. var bone = this.getBoneByID(id);
  19635. return bone;
  19636. };
  19637. Scene.prototype.getNodeByName = function (name) {
  19638. var mesh = this.getMeshByName(name);
  19639. if (mesh) {
  19640. return mesh;
  19641. }
  19642. var light = this.getLightByName(name);
  19643. if (light) {
  19644. return light;
  19645. }
  19646. var camera = this.getCameraByName(name);
  19647. if (camera) {
  19648. return camera;
  19649. }
  19650. var bone = this.getBoneByName(name);
  19651. return bone;
  19652. };
  19653. Scene.prototype.getMeshByName = function (name) {
  19654. for (var index = 0; index < this.meshes.length; index++) {
  19655. if (this.meshes[index].name === name) {
  19656. return this.meshes[index];
  19657. }
  19658. }
  19659. return null;
  19660. };
  19661. Scene.prototype.getSoundByName = function (name) {
  19662. var index;
  19663. if (BABYLON.AudioEngine) {
  19664. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19665. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19666. return this.mainSoundTrack.soundCollection[index];
  19667. }
  19668. }
  19669. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19670. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19671. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19672. return this.soundTracks[sdIndex].soundCollection[index];
  19673. }
  19674. }
  19675. }
  19676. }
  19677. return null;
  19678. };
  19679. Scene.prototype.getLastSkeletonByID = function (id) {
  19680. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19681. if (this.skeletons[index].id === id) {
  19682. return this.skeletons[index];
  19683. }
  19684. }
  19685. return null;
  19686. };
  19687. Scene.prototype.getSkeletonById = function (id) {
  19688. for (var index = 0; index < this.skeletons.length; index++) {
  19689. if (this.skeletons[index].id === id) {
  19690. return this.skeletons[index];
  19691. }
  19692. }
  19693. return null;
  19694. };
  19695. Scene.prototype.getSkeletonByName = function (name) {
  19696. for (var index = 0; index < this.skeletons.length; index++) {
  19697. if (this.skeletons[index].name === name) {
  19698. return this.skeletons[index];
  19699. }
  19700. }
  19701. return null;
  19702. };
  19703. Scene.prototype.getMorphTargetManagerById = function (id) {
  19704. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19705. if (this.morphTargetManagers[index].uniqueId === id) {
  19706. return this.morphTargetManagers[index];
  19707. }
  19708. }
  19709. return null;
  19710. };
  19711. Scene.prototype.isActiveMesh = function (mesh) {
  19712. return (this._activeMeshes.indexOf(mesh) !== -1);
  19713. };
  19714. /**
  19715. * Return a the first highlight layer of the scene with a given name.
  19716. * @param name The name of the highlight layer to look for.
  19717. * @return The highlight layer if found otherwise null.
  19718. */
  19719. Scene.prototype.getHighlightLayerByName = function (name) {
  19720. for (var index = 0; index < this.highlightLayers.length; index++) {
  19721. if (this.highlightLayers[index].name === name) {
  19722. return this.highlightLayers[index];
  19723. }
  19724. }
  19725. return null;
  19726. };
  19727. Object.defineProperty(Scene.prototype, "uid", {
  19728. /**
  19729. * Return a unique id as a string which can serve as an identifier for the scene
  19730. */
  19731. get: function () {
  19732. if (!this._uid) {
  19733. this._uid = BABYLON.Tools.RandomId();
  19734. }
  19735. return this._uid;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. /**
  19741. * Add an externaly attached data from its key.
  19742. * This method call will fail and return false, if such key already exists.
  19743. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19744. * @param key the unique key that identifies the data
  19745. * @param data the data object to associate to the key for this Engine instance
  19746. * @return true if no such key were already present and the data was added successfully, false otherwise
  19747. */
  19748. Scene.prototype.addExternalData = function (key, data) {
  19749. if (!this._externalData) {
  19750. this._externalData = new BABYLON.StringDictionary();
  19751. }
  19752. return this._externalData.add(key, data);
  19753. };
  19754. /**
  19755. * Get an externaly attached data from its key
  19756. * @param key the unique key that identifies the data
  19757. * @return the associated data, if present (can be null), or undefined if not present
  19758. */
  19759. Scene.prototype.getExternalData = function (key) {
  19760. if (!this._externalData) {
  19761. return null;
  19762. }
  19763. return this._externalData.get(key);
  19764. };
  19765. /**
  19766. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19767. * @param key the unique key that identifies the data
  19768. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19769. * @return the associated data, can be null if the factory returned null.
  19770. */
  19771. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19772. if (!this._externalData) {
  19773. this._externalData = new BABYLON.StringDictionary();
  19774. }
  19775. return this._externalData.getOrAddWithFactory(key, factory);
  19776. };
  19777. /**
  19778. * Remove an externaly attached data from the Engine instance
  19779. * @param key the unique key that identifies the data
  19780. * @return true if the data was successfully removed, false if it doesn't exist
  19781. */
  19782. Scene.prototype.removeExternalData = function (key) {
  19783. return this._externalData.remove(key);
  19784. };
  19785. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19786. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19787. var material = subMesh.getMaterial();
  19788. if (mesh.showSubMeshesBoundingBox) {
  19789. var boundingInfo = subMesh.getBoundingInfo();
  19790. if (boundingInfo) {
  19791. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19792. }
  19793. }
  19794. if (material) {
  19795. // Render targets
  19796. if (material.getRenderTargetTextures) {
  19797. if (this._processedMaterials.indexOf(material) === -1) {
  19798. this._processedMaterials.push(material);
  19799. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19800. }
  19801. }
  19802. // Dispatch
  19803. this._activeIndices.addCount(subMesh.indexCount, false);
  19804. this._renderingManager.dispatch(subMesh);
  19805. }
  19806. }
  19807. };
  19808. Scene.prototype._isInIntermediateRendering = function () {
  19809. return this._intermediateRendering;
  19810. };
  19811. /**
  19812. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19813. */
  19814. Scene.prototype.freezeActiveMeshes = function () {
  19815. this._evaluateActiveMeshes();
  19816. this._activeMeshesFrozen = true;
  19817. return this;
  19818. };
  19819. /**
  19820. * Use this function to restart evaluating active meshes on every frame
  19821. */
  19822. Scene.prototype.unfreezeActiveMeshes = function () {
  19823. this._activeMeshesFrozen = false;
  19824. return this;
  19825. };
  19826. Scene.prototype._evaluateActiveMeshes = function () {
  19827. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19828. return;
  19829. }
  19830. if (!this.activeCamera) {
  19831. return;
  19832. }
  19833. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  19834. this.activeCamera._activeMeshes.reset();
  19835. this._activeMeshes.reset();
  19836. this._renderingManager.reset();
  19837. this._processedMaterials.reset();
  19838. this._activeParticleSystems.reset();
  19839. this._activeSkeletons.reset();
  19840. this._softwareSkinnedMeshes.reset();
  19841. if (this._boundingBoxRenderer) {
  19842. this._boundingBoxRenderer.reset();
  19843. }
  19844. // Meshes
  19845. var meshes;
  19846. var len;
  19847. if (this._selectionOctree) {
  19848. var selection = this._selectionOctree.select(this._frustumPlanes);
  19849. meshes = selection.data;
  19850. len = selection.length;
  19851. }
  19852. else {
  19853. len = this.meshes.length;
  19854. meshes = this.meshes;
  19855. }
  19856. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19857. var mesh = meshes[meshIndex];
  19858. if (mesh.isBlocked) {
  19859. continue;
  19860. }
  19861. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19862. if (!mesh.isReady() || !mesh.isEnabled()) {
  19863. continue;
  19864. }
  19865. mesh.computeWorldMatrix();
  19866. // Intersections
  19867. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19868. this._meshesForIntersections.pushNoDuplicate(mesh);
  19869. }
  19870. // Switch to current LOD
  19871. var meshLOD = mesh.getLOD(this.activeCamera);
  19872. if (!meshLOD) {
  19873. continue;
  19874. }
  19875. mesh._preActivate();
  19876. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19877. this._activeMeshes.push(mesh);
  19878. this.activeCamera._activeMeshes.push(mesh);
  19879. mesh._activate(this._renderId);
  19880. if (meshLOD !== mesh) {
  19881. meshLOD._activate(this._renderId);
  19882. }
  19883. this._activeMesh(mesh, meshLOD);
  19884. }
  19885. }
  19886. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  19887. // Particle systems
  19888. if (this.particlesEnabled) {
  19889. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  19890. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19891. var particleSystem = this.particleSystems[particleIndex];
  19892. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19893. continue;
  19894. }
  19895. var emitter = particleSystem.emitter;
  19896. if (!emitter.position || emitter.isEnabled()) {
  19897. this._activeParticleSystems.push(particleSystem);
  19898. particleSystem.animate();
  19899. this._renderingManager.dispatchParticles(particleSystem);
  19900. }
  19901. }
  19902. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  19903. }
  19904. };
  19905. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19906. if (mesh.skeleton && this.skeletonsEnabled) {
  19907. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19908. mesh.skeleton.prepare();
  19909. }
  19910. if (!mesh.computeBonesUsingShaders) {
  19911. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19912. }
  19913. }
  19914. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19915. var boundingInfo = sourceMesh.getBoundingInfo();
  19916. if (boundingInfo) {
  19917. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19918. }
  19919. }
  19920. if (mesh && mesh.subMeshes) {
  19921. // Submeshes Octrees
  19922. var len;
  19923. var subMeshes;
  19924. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19925. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19926. len = intersections.length;
  19927. subMeshes = intersections.data;
  19928. }
  19929. else {
  19930. subMeshes = mesh.subMeshes;
  19931. len = subMeshes.length;
  19932. }
  19933. for (var subIndex = 0; subIndex < len; subIndex++) {
  19934. var subMesh = subMeshes[subIndex];
  19935. this._evaluateSubMesh(subMesh, mesh);
  19936. }
  19937. }
  19938. };
  19939. Scene.prototype.updateTransformMatrix = function (force) {
  19940. if (!this.activeCamera) {
  19941. return;
  19942. }
  19943. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19944. };
  19945. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19946. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19947. };
  19948. Scene.prototype._renderForCamera = function (camera) {
  19949. if (camera && camera._skipRendering) {
  19950. return;
  19951. }
  19952. var engine = this._engine;
  19953. this.activeCamera = camera;
  19954. if (!this.activeCamera)
  19955. throw new Error("Active camera not set");
  19956. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19957. // Viewport
  19958. engine.setViewport(this.activeCamera.viewport);
  19959. // Camera
  19960. this.resetCachedMaterial();
  19961. this._renderId++;
  19962. this.activeCamera.update();
  19963. this.updateTransformMatrix();
  19964. if (camera._alternateCamera) {
  19965. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19966. this._alternateRendering = true;
  19967. }
  19968. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19969. // Meshes
  19970. this._evaluateActiveMeshes();
  19971. // Software skinning
  19972. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19973. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19974. mesh.applySkeleton(mesh.skeleton);
  19975. }
  19976. // Render targets
  19977. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19978. var needsRestoreFrameBuffer = false;
  19979. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19980. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19981. }
  19982. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19983. this._intermediateRendering = true;
  19984. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19985. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19986. var renderTarget = this._renderTargets.data[renderIndex];
  19987. if (renderTarget._shouldRender()) {
  19988. this._renderId++;
  19989. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19990. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19991. }
  19992. }
  19993. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19994. this._intermediateRendering = false;
  19995. this._renderId++;
  19996. needsRestoreFrameBuffer = true; // Restore back buffer
  19997. }
  19998. // Render HighlightLayer Texture
  19999. var stencilState = this._engine.getStencilBuffer();
  20000. var renderhighlights = false;
  20001. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20002. this._intermediateRendering = true;
  20003. for (var i = 0; i < this.highlightLayers.length; i++) {
  20004. var highlightLayer = this.highlightLayers[i];
  20005. if (highlightLayer.shouldRender() &&
  20006. (!highlightLayer.camera ||
  20007. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20008. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20009. renderhighlights = true;
  20010. var renderTarget = highlightLayer._mainTexture;
  20011. if (renderTarget._shouldRender()) {
  20012. this._renderId++;
  20013. renderTarget.render(false, false);
  20014. needsRestoreFrameBuffer = true;
  20015. }
  20016. }
  20017. }
  20018. this._intermediateRendering = false;
  20019. this._renderId++;
  20020. }
  20021. if (needsRestoreFrameBuffer) {
  20022. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20023. }
  20024. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20025. // Prepare Frame
  20026. this.postProcessManager._prepareFrame();
  20027. // Backgrounds
  20028. var layerIndex;
  20029. var layer;
  20030. if (this.layers.length) {
  20031. engine.setDepthBuffer(false);
  20032. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20033. layer = this.layers[layerIndex];
  20034. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20035. layer.render();
  20036. }
  20037. }
  20038. engine.setDepthBuffer(true);
  20039. }
  20040. // Activate HighlightLayer stencil
  20041. if (renderhighlights) {
  20042. this._engine.setStencilBuffer(true);
  20043. }
  20044. // Render
  20045. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20046. this._renderingManager.render(null, null, true, true);
  20047. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20048. // Restore HighlightLayer stencil
  20049. if (renderhighlights) {
  20050. this._engine.setStencilBuffer(stencilState);
  20051. }
  20052. // Bounding boxes
  20053. if (this._boundingBoxRenderer) {
  20054. this._boundingBoxRenderer.render();
  20055. }
  20056. // Lens flares
  20057. if (this.lensFlaresEnabled) {
  20058. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20059. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20060. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20061. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20062. lensFlareSystem.render();
  20063. }
  20064. }
  20065. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20066. }
  20067. // Foregrounds
  20068. if (this.layers.length) {
  20069. engine.setDepthBuffer(false);
  20070. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20071. layer = this.layers[layerIndex];
  20072. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20073. layer.render();
  20074. }
  20075. }
  20076. engine.setDepthBuffer(true);
  20077. }
  20078. // Highlight Layer
  20079. if (renderhighlights) {
  20080. engine.setDepthBuffer(false);
  20081. for (var i = 0; i < this.highlightLayers.length; i++) {
  20082. if (this.highlightLayers[i].shouldRender()) {
  20083. this.highlightLayers[i].render();
  20084. }
  20085. }
  20086. engine.setDepthBuffer(true);
  20087. }
  20088. // Finalize frame
  20089. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20090. // Reset some special arrays
  20091. this._renderTargets.reset();
  20092. this._alternateRendering = false;
  20093. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20094. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20095. };
  20096. Scene.prototype._processSubCameras = function (camera) {
  20097. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20098. this._renderForCamera(camera);
  20099. return;
  20100. }
  20101. // Update camera
  20102. if (this.activeCamera) {
  20103. this.activeCamera.update();
  20104. }
  20105. // rig cameras
  20106. for (var index = 0; index < camera._rigCameras.length; index++) {
  20107. this._renderForCamera(camera._rigCameras[index]);
  20108. }
  20109. this.activeCamera = camera;
  20110. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20111. };
  20112. Scene.prototype._checkIntersections = function () {
  20113. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20114. var sourceMesh = this._meshesForIntersections.data[index];
  20115. if (!sourceMesh.actionManager) {
  20116. continue;
  20117. }
  20118. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20119. var action = sourceMesh.actionManager.actions[actionIndex];
  20120. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20121. var parameters = action.getTriggerParameter();
  20122. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20123. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20124. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20125. if (areIntersecting && currentIntersectionInProgress === -1) {
  20126. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20127. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20128. sourceMesh._intersectionsInProgress.push(otherMesh);
  20129. }
  20130. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20131. sourceMesh._intersectionsInProgress.push(otherMesh);
  20132. }
  20133. }
  20134. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20135. //They intersected, and now they don't.
  20136. //is this trigger an exit trigger? execute an event.
  20137. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20138. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20139. }
  20140. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20141. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20142. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20143. }
  20144. }
  20145. }
  20146. }
  20147. }
  20148. };
  20149. Scene.prototype.render = function () {
  20150. if (this.isDisposed) {
  20151. return;
  20152. }
  20153. this._activeParticles.fetchNewFrame();
  20154. this._totalVertices.fetchNewFrame();
  20155. this._activeIndices.fetchNewFrame();
  20156. this._activeBones.fetchNewFrame();
  20157. this._meshesForIntersections.reset();
  20158. this.resetCachedMaterial();
  20159. this.onBeforeAnimationsObservable.notifyObservers(this);
  20160. // Actions
  20161. if (this.actionManager) {
  20162. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20163. }
  20164. //Simplification Queue
  20165. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20166. this.simplificationQueue.executeNext();
  20167. }
  20168. if (this._engine.isDeterministicLockStep()) {
  20169. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  20170. var defaultTimeStep = (60.0 / 1000.0);
  20171. if (this._physicsEngine) {
  20172. defaultTimeStep = this._physicsEngine.getTimeStep();
  20173. }
  20174. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20175. this._timeAccumulator += deltaTime;
  20176. // compute the amount of fixed steps we should have taken since the last step
  20177. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  20178. internalSteps = Math.min(internalSteps, maxSubSteps);
  20179. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  20180. this.onBeforeStepObservable.notifyObservers(this);
  20181. // Animations
  20182. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  20183. this._animate();
  20184. this.onAfterAnimationsObservable.notifyObservers(this);
  20185. // Physics
  20186. if (this._physicsEngine) {
  20187. this.onBeforePhysicsObservable.notifyObservers(this);
  20188. this._physicsEngine._step(defaultTimeStep);
  20189. this.onAfterPhysicsObservable.notifyObservers(this);
  20190. }
  20191. this._timeAccumulator -= defaultTimeStep;
  20192. this.onAfterStepObservable.notifyObservers(this);
  20193. this._currentStepId++;
  20194. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  20195. this._evaluateActiveMeshes();
  20196. }
  20197. }
  20198. }
  20199. else {
  20200. // Animations
  20201. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20202. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20203. this._animate();
  20204. this.onAfterAnimationsObservable.notifyObservers(this);
  20205. // Physics
  20206. if (this._physicsEngine) {
  20207. this.onBeforePhysicsObservable.notifyObservers(this);
  20208. this._physicsEngine._step(deltaTime / 1000.0);
  20209. this.onAfterPhysicsObservable.notifyObservers(this);
  20210. }
  20211. }
  20212. // Before render
  20213. this.onBeforeRenderObservable.notifyObservers(this);
  20214. // Customs render targets
  20215. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20216. var engine = this.getEngine();
  20217. var currentActiveCamera = this.activeCamera;
  20218. if (this.renderTargetsEnabled) {
  20219. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20220. this._intermediateRendering = true;
  20221. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20222. var renderTarget = this.customRenderTargets[customIndex];
  20223. if (renderTarget._shouldRender()) {
  20224. this._renderId++;
  20225. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20226. if (!this.activeCamera)
  20227. throw new Error("Active camera not set");
  20228. // Viewport
  20229. engine.setViewport(this.activeCamera.viewport);
  20230. // Camera
  20231. this.updateTransformMatrix();
  20232. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20233. }
  20234. }
  20235. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20236. this._intermediateRendering = false;
  20237. this._renderId++;
  20238. }
  20239. // Restore back buffer
  20240. if (this.customRenderTargets.length > 0) {
  20241. engine.restoreDefaultFramebuffer();
  20242. }
  20243. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20244. this.activeCamera = currentActiveCamera;
  20245. // Procedural textures
  20246. if (this.proceduralTexturesEnabled) {
  20247. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20248. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20249. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20250. if (proceduralTexture._shouldRender()) {
  20251. proceduralTexture.render();
  20252. }
  20253. }
  20254. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20255. }
  20256. // Clear
  20257. if (this.autoClearDepthAndStencil || this.autoClear) {
  20258. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20259. }
  20260. // Shadows
  20261. if (this.shadowsEnabled) {
  20262. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20263. var light = this.lights[lightIndex];
  20264. var shadowGenerator = light.getShadowGenerator();
  20265. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20266. var shadowMap = (shadowGenerator.getShadowMap());
  20267. if (this.textures.indexOf(shadowMap) !== -1) {
  20268. this._renderTargets.push(shadowMap);
  20269. }
  20270. }
  20271. }
  20272. }
  20273. // Depth renderer
  20274. if (this._depthRenderer) {
  20275. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20276. }
  20277. // Geometry renderer
  20278. if (this._geometryBufferRenderer) {
  20279. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20280. }
  20281. // RenderPipeline
  20282. if (this._postProcessRenderPipelineManager) {
  20283. this._postProcessRenderPipelineManager.update();
  20284. }
  20285. // Multi-cameras?
  20286. if (this.activeCameras.length > 0) {
  20287. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20288. if (cameraIndex > 0) {
  20289. this._engine.clear(null, false, true, true);
  20290. }
  20291. this._processSubCameras(this.activeCameras[cameraIndex]);
  20292. }
  20293. }
  20294. else {
  20295. if (!this.activeCamera) {
  20296. throw new Error("No camera defined");
  20297. }
  20298. this._processSubCameras(this.activeCamera);
  20299. }
  20300. // Intersection checks
  20301. this._checkIntersections();
  20302. // Update the audio listener attached to the camera
  20303. if (BABYLON.AudioEngine) {
  20304. this._updateAudioParameters();
  20305. }
  20306. // After render
  20307. if (this.afterRender) {
  20308. this.afterRender();
  20309. }
  20310. this.onAfterRenderObservable.notifyObservers(this);
  20311. // Cleaning
  20312. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20313. var data = this._toBeDisposed.data[index];
  20314. if (data) {
  20315. data.dispose();
  20316. }
  20317. this._toBeDisposed[index] = null;
  20318. }
  20319. this._toBeDisposed.reset();
  20320. if (this.dumpNextRenderTargets) {
  20321. this.dumpNextRenderTargets = false;
  20322. }
  20323. this._activeBones.addCount(0, true);
  20324. this._activeIndices.addCount(0, true);
  20325. this._activeParticles.addCount(0, true);
  20326. };
  20327. Scene.prototype._updateAudioParameters = function () {
  20328. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20329. return;
  20330. }
  20331. var listeningCamera;
  20332. var audioEngine = BABYLON.Engine.audioEngine;
  20333. if (this.activeCameras.length > 0) {
  20334. listeningCamera = this.activeCameras[0];
  20335. }
  20336. else {
  20337. listeningCamera = this.activeCamera;
  20338. }
  20339. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20340. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20341. // for VR cameras
  20342. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20343. listeningCamera = listeningCamera.rigCameras[0];
  20344. }
  20345. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20346. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20347. cameraDirection.normalize();
  20348. // To avoid some errors on GearVR
  20349. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20350. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20351. }
  20352. var i;
  20353. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20354. var sound = this.mainSoundTrack.soundCollection[i];
  20355. if (sound.useCustomAttenuation) {
  20356. sound.updateDistanceFromListener();
  20357. }
  20358. }
  20359. for (i = 0; i < this.soundTracks.length; i++) {
  20360. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20361. sound = this.soundTracks[i].soundCollection[j];
  20362. if (sound.useCustomAttenuation) {
  20363. sound.updateDistanceFromListener();
  20364. }
  20365. }
  20366. }
  20367. }
  20368. };
  20369. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20370. // Audio
  20371. get: function () {
  20372. return this._audioEnabled;
  20373. },
  20374. set: function (value) {
  20375. this._audioEnabled = value;
  20376. if (BABYLON.AudioEngine) {
  20377. if (this._audioEnabled) {
  20378. this._enableAudio();
  20379. }
  20380. else {
  20381. this._disableAudio();
  20382. }
  20383. }
  20384. },
  20385. enumerable: true,
  20386. configurable: true
  20387. });
  20388. Scene.prototype._disableAudio = function () {
  20389. var i;
  20390. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20391. this.mainSoundTrack.soundCollection[i].pause();
  20392. }
  20393. for (i = 0; i < this.soundTracks.length; i++) {
  20394. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20395. this.soundTracks[i].soundCollection[j].pause();
  20396. }
  20397. }
  20398. };
  20399. Scene.prototype._enableAudio = function () {
  20400. var i;
  20401. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20402. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20403. this.mainSoundTrack.soundCollection[i].play();
  20404. }
  20405. }
  20406. for (i = 0; i < this.soundTracks.length; i++) {
  20407. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20408. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20409. this.soundTracks[i].soundCollection[j].play();
  20410. }
  20411. }
  20412. }
  20413. };
  20414. Object.defineProperty(Scene.prototype, "headphone", {
  20415. get: function () {
  20416. return this._headphone;
  20417. },
  20418. set: function (value) {
  20419. this._headphone = value;
  20420. if (BABYLON.AudioEngine) {
  20421. if (this._headphone) {
  20422. this._switchAudioModeForHeadphones();
  20423. }
  20424. else {
  20425. this._switchAudioModeForNormalSpeakers();
  20426. }
  20427. }
  20428. },
  20429. enumerable: true,
  20430. configurable: true
  20431. });
  20432. Scene.prototype._switchAudioModeForHeadphones = function () {
  20433. this.mainSoundTrack.switchPanningModelToHRTF();
  20434. for (var i = 0; i < this.soundTracks.length; i++) {
  20435. this.soundTracks[i].switchPanningModelToHRTF();
  20436. }
  20437. };
  20438. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20439. this.mainSoundTrack.switchPanningModelToEqualPower();
  20440. for (var i = 0; i < this.soundTracks.length; i++) {
  20441. this.soundTracks[i].switchPanningModelToEqualPower();
  20442. }
  20443. };
  20444. Scene.prototype.enableDepthRenderer = function () {
  20445. if (this._depthRenderer) {
  20446. return this._depthRenderer;
  20447. }
  20448. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20449. return this._depthRenderer;
  20450. };
  20451. Scene.prototype.disableDepthRenderer = function () {
  20452. if (!this._depthRenderer) {
  20453. return;
  20454. }
  20455. this._depthRenderer.dispose();
  20456. this._depthRenderer = null;
  20457. };
  20458. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20459. if (ratio === void 0) { ratio = 1; }
  20460. if (this._geometryBufferRenderer) {
  20461. return this._geometryBufferRenderer;
  20462. }
  20463. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20464. if (!this._geometryBufferRenderer.isSupported) {
  20465. this._geometryBufferRenderer = null;
  20466. }
  20467. return this._geometryBufferRenderer;
  20468. };
  20469. Scene.prototype.disableGeometryBufferRenderer = function () {
  20470. if (!this._geometryBufferRenderer) {
  20471. return;
  20472. }
  20473. this._geometryBufferRenderer.dispose();
  20474. this._geometryBufferRenderer = null;
  20475. };
  20476. Scene.prototype.freezeMaterials = function () {
  20477. for (var i = 0; i < this.materials.length; i++) {
  20478. this.materials[i].freeze();
  20479. }
  20480. };
  20481. Scene.prototype.unfreezeMaterials = function () {
  20482. for (var i = 0; i < this.materials.length; i++) {
  20483. this.materials[i].unfreeze();
  20484. }
  20485. };
  20486. Scene.prototype.dispose = function () {
  20487. this.beforeRender = null;
  20488. this.afterRender = null;
  20489. this.skeletons = [];
  20490. this.morphTargetManagers = [];
  20491. this.importedMeshesFiles = new Array();
  20492. this.resetCachedMaterial();
  20493. if (this._depthRenderer) {
  20494. this._depthRenderer.dispose();
  20495. }
  20496. if (this._gamepadManager) {
  20497. this._gamepadManager.dispose();
  20498. this._gamepadManager = null;
  20499. }
  20500. // Smart arrays
  20501. if (this.activeCamera) {
  20502. this.activeCamera._activeMeshes.dispose();
  20503. this.activeCamera = null;
  20504. }
  20505. this._activeMeshes.dispose();
  20506. this._renderingManager.dispose();
  20507. this._processedMaterials.dispose();
  20508. this._activeParticleSystems.dispose();
  20509. this._activeSkeletons.dispose();
  20510. this._softwareSkinnedMeshes.dispose();
  20511. this._renderTargets.dispose();
  20512. if (this._boundingBoxRenderer) {
  20513. this._boundingBoxRenderer.dispose();
  20514. }
  20515. this._meshesForIntersections.dispose();
  20516. this._toBeDisposed.dispose();
  20517. // Debug layer
  20518. if (this._debugLayer) {
  20519. this._debugLayer.hide();
  20520. }
  20521. // Events
  20522. this.onDisposeObservable.notifyObservers(this);
  20523. this.onDisposeObservable.clear();
  20524. this.onBeforeRenderObservable.clear();
  20525. this.onAfterRenderObservable.clear();
  20526. this.OnBeforeRenderTargetsRenderObservable.clear();
  20527. this.OnAfterRenderTargetsRenderObservable.clear();
  20528. this.onAfterStepObservable.clear();
  20529. this.onBeforeStepObservable.clear();
  20530. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20531. this.onAfterActiveMeshesEvaluationObservable.clear();
  20532. this.onBeforeParticlesRenderingObservable.clear();
  20533. this.onAfterParticlesRenderingObservable.clear();
  20534. this.onBeforeSpritesRenderingObservable.clear();
  20535. this.onAfterSpritesRenderingObservable.clear();
  20536. this.onBeforeDrawPhaseObservable.clear();
  20537. this.onAfterDrawPhaseObservable.clear();
  20538. this.onBeforePhysicsObservable.clear();
  20539. this.onAfterPhysicsObservable.clear();
  20540. this.onBeforeAnimationsObservable.clear();
  20541. this.onAfterAnimationsObservable.clear();
  20542. this.onDataLoadedObservable.clear();
  20543. this.detachControl();
  20544. // Release sounds & sounds tracks
  20545. if (BABYLON.AudioEngine) {
  20546. this.disposeSounds();
  20547. }
  20548. // VR Helper
  20549. if (this.VRHelper) {
  20550. this.VRHelper.dispose();
  20551. }
  20552. // Detach cameras
  20553. var canvas = this._engine.getRenderingCanvas();
  20554. if (canvas) {
  20555. var index;
  20556. for (index = 0; index < this.cameras.length; index++) {
  20557. this.cameras[index].detachControl(canvas);
  20558. }
  20559. }
  20560. // Release lights
  20561. while (this.lights.length) {
  20562. this.lights[0].dispose();
  20563. }
  20564. // Release meshes
  20565. while (this.meshes.length) {
  20566. this.meshes[0].dispose(true);
  20567. }
  20568. // Release cameras
  20569. while (this.cameras.length) {
  20570. this.cameras[0].dispose();
  20571. }
  20572. // Release materials
  20573. if (this.defaultMaterial) {
  20574. this.defaultMaterial.dispose();
  20575. }
  20576. while (this.multiMaterials.length) {
  20577. this.multiMaterials[0].dispose();
  20578. }
  20579. while (this.materials.length) {
  20580. this.materials[0].dispose();
  20581. }
  20582. // Release particles
  20583. while (this.particleSystems.length) {
  20584. this.particleSystems[0].dispose();
  20585. }
  20586. // Release sprites
  20587. while (this.spriteManagers.length) {
  20588. this.spriteManagers[0].dispose();
  20589. }
  20590. // Release postProcesses
  20591. while (this.postProcesses.length) {
  20592. this.postProcesses[0].dispose();
  20593. }
  20594. // Release layers
  20595. while (this.layers.length) {
  20596. this.layers[0].dispose();
  20597. }
  20598. while (this.highlightLayers.length) {
  20599. this.highlightLayers[0].dispose();
  20600. }
  20601. // Release textures
  20602. while (this.textures.length) {
  20603. this.textures[0].dispose();
  20604. }
  20605. // Release UBO
  20606. this._sceneUbo.dispose();
  20607. if (this._alternateSceneUbo) {
  20608. this._alternateSceneUbo.dispose();
  20609. }
  20610. // Post-processes
  20611. this.postProcessManager.dispose();
  20612. if (this._postProcessRenderPipelineManager) {
  20613. this._postProcessRenderPipelineManager.dispose();
  20614. }
  20615. // Physics
  20616. if (this._physicsEngine) {
  20617. this.disablePhysicsEngine();
  20618. }
  20619. // Remove from engine
  20620. index = this._engine.scenes.indexOf(this);
  20621. if (index > -1) {
  20622. this._engine.scenes.splice(index, 1);
  20623. }
  20624. this._engine.wipeCaches();
  20625. this._isDisposed = true;
  20626. };
  20627. Object.defineProperty(Scene.prototype, "isDisposed", {
  20628. get: function () {
  20629. return this._isDisposed;
  20630. },
  20631. enumerable: true,
  20632. configurable: true
  20633. });
  20634. // Release sounds & sounds tracks
  20635. Scene.prototype.disposeSounds = function () {
  20636. if (!this._mainSoundTrack) {
  20637. return;
  20638. }
  20639. this.mainSoundTrack.dispose();
  20640. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20641. this.soundTracks[scIndex].dispose();
  20642. }
  20643. };
  20644. // Octrees
  20645. Scene.prototype.getWorldExtends = function () {
  20646. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20647. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20648. for (var index = 0; index < this.meshes.length; index++) {
  20649. var mesh = this.meshes[index];
  20650. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20651. continue;
  20652. }
  20653. mesh.computeWorldMatrix(true);
  20654. var boundingInfo = mesh.getBoundingInfo();
  20655. if (boundingInfo) {
  20656. var minBox = boundingInfo.boundingBox.minimumWorld;
  20657. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20658. BABYLON.Tools.CheckExtends(minBox, min, max);
  20659. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20660. }
  20661. }
  20662. return {
  20663. min: min,
  20664. max: max
  20665. };
  20666. };
  20667. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20668. if (maxCapacity === void 0) { maxCapacity = 64; }
  20669. if (maxDepth === void 0) { maxDepth = 2; }
  20670. if (!this._selectionOctree) {
  20671. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20672. }
  20673. var worldExtends = this.getWorldExtends();
  20674. // Update octree
  20675. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20676. return this._selectionOctree;
  20677. };
  20678. // Picking
  20679. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20680. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20681. var engine = this._engine;
  20682. if (!camera) {
  20683. if (!this.activeCamera)
  20684. throw new Error("Active camera not set");
  20685. camera = this.activeCamera;
  20686. }
  20687. var cameraViewport = camera.viewport;
  20688. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20689. // Moving coordinates to local viewport world
  20690. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20691. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20692. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20693. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20694. };
  20695. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20696. if (!BABYLON.PickingInfo) {
  20697. return null;
  20698. }
  20699. var engine = this._engine;
  20700. if (!camera) {
  20701. if (!this.activeCamera)
  20702. throw new Error("Active camera not set");
  20703. camera = this.activeCamera;
  20704. }
  20705. var cameraViewport = camera.viewport;
  20706. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20707. var identity = BABYLON.Matrix.Identity();
  20708. // Moving coordinates to local viewport world
  20709. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20710. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20711. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20712. };
  20713. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20714. if (!BABYLON.PickingInfo) {
  20715. return null;
  20716. }
  20717. var pickingInfo = null;
  20718. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20719. var mesh = this.meshes[meshIndex];
  20720. if (predicate) {
  20721. if (!predicate(mesh)) {
  20722. continue;
  20723. }
  20724. }
  20725. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20726. continue;
  20727. }
  20728. var world = mesh.getWorldMatrix();
  20729. var ray = rayFunction(world);
  20730. var result = mesh.intersects(ray, fastCheck);
  20731. if (!result || !result.hit)
  20732. continue;
  20733. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20734. continue;
  20735. pickingInfo = result;
  20736. if (fastCheck) {
  20737. break;
  20738. }
  20739. }
  20740. return pickingInfo || new BABYLON.PickingInfo();
  20741. };
  20742. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20743. if (!BABYLON.PickingInfo) {
  20744. return null;
  20745. }
  20746. var pickingInfos = new Array();
  20747. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20748. var mesh = this.meshes[meshIndex];
  20749. if (predicate) {
  20750. if (!predicate(mesh)) {
  20751. continue;
  20752. }
  20753. }
  20754. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20755. continue;
  20756. }
  20757. var world = mesh.getWorldMatrix();
  20758. var ray = rayFunction(world);
  20759. var result = mesh.intersects(ray, false);
  20760. if (!result || !result.hit)
  20761. continue;
  20762. pickingInfos.push(result);
  20763. }
  20764. return pickingInfos;
  20765. };
  20766. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20767. if (!BABYLON.PickingInfo) {
  20768. return null;
  20769. }
  20770. var pickingInfo = null;
  20771. if (!camera) {
  20772. if (!this.activeCamera) {
  20773. return null;
  20774. }
  20775. camera = this.activeCamera;
  20776. }
  20777. if (this.spriteManagers.length > 0) {
  20778. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20779. var spriteManager = this.spriteManagers[spriteIndex];
  20780. if (!spriteManager.isPickable) {
  20781. continue;
  20782. }
  20783. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20784. if (!result || !result.hit)
  20785. continue;
  20786. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20787. continue;
  20788. pickingInfo = result;
  20789. if (fastCheck) {
  20790. break;
  20791. }
  20792. }
  20793. }
  20794. return pickingInfo || new BABYLON.PickingInfo();
  20795. };
  20796. /** Launch a ray to try to pick a mesh in the scene
  20797. * @param x position on screen
  20798. * @param y position on screen
  20799. * @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
  20800. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20801. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20802. */
  20803. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20804. var _this = this;
  20805. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20806. };
  20807. /** Launch a ray to try to pick a sprite in the scene
  20808. * @param x position on screen
  20809. * @param y position on screen
  20810. * @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
  20811. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20812. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20813. */
  20814. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20815. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20816. if (!ray) {
  20817. return null;
  20818. }
  20819. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20820. };
  20821. /** Use the given ray to pick a mesh in the scene
  20822. * @param ray The ray to use to pick meshes
  20823. * @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
  20824. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20825. */
  20826. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20827. var _this = this;
  20828. return this._internalPick(function (world) {
  20829. if (!_this._pickWithRayInverseMatrix) {
  20830. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20831. }
  20832. world.invertToRef(_this._pickWithRayInverseMatrix);
  20833. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20834. }, predicate, fastCheck);
  20835. };
  20836. /**
  20837. * Launch a ray to try to pick a mesh in the scene
  20838. * @param x X position on screen
  20839. * @param y Y position on screen
  20840. * @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
  20841. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20842. */
  20843. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20844. var _this = this;
  20845. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20846. };
  20847. /**
  20848. * Launch a ray to try to pick a mesh in the scene
  20849. * @param ray Ray to use
  20850. * @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
  20851. */
  20852. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20853. var _this = this;
  20854. return this._internalMultiPick(function (world) {
  20855. if (!_this._pickWithRayInverseMatrix) {
  20856. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20857. }
  20858. world.invertToRef(_this._pickWithRayInverseMatrix);
  20859. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20860. }, predicate);
  20861. };
  20862. Scene.prototype.setPointerOverMesh = function (mesh) {
  20863. if (this._pointerOverMesh === mesh) {
  20864. return;
  20865. }
  20866. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20867. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20868. }
  20869. this._pointerOverMesh = mesh;
  20870. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20871. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20872. }
  20873. };
  20874. Scene.prototype.getPointerOverMesh = function () {
  20875. return this._pointerOverMesh;
  20876. };
  20877. Scene.prototype.setPointerOverSprite = function (sprite) {
  20878. if (this._pointerOverSprite === sprite) {
  20879. return;
  20880. }
  20881. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20882. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20883. }
  20884. this._pointerOverSprite = sprite;
  20885. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20886. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20887. }
  20888. };
  20889. Scene.prototype.getPointerOverSprite = function () {
  20890. return this._pointerOverSprite;
  20891. };
  20892. // Physics
  20893. Scene.prototype.getPhysicsEngine = function () {
  20894. return this._physicsEngine;
  20895. };
  20896. /**
  20897. * Enables physics to the current scene
  20898. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20899. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20900. * @return {boolean} was the physics engine initialized
  20901. */
  20902. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20903. if (gravity === void 0) { gravity = null; }
  20904. if (this._physicsEngine) {
  20905. return true;
  20906. }
  20907. try {
  20908. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20909. return true;
  20910. }
  20911. catch (e) {
  20912. BABYLON.Tools.Error(e.message);
  20913. return false;
  20914. }
  20915. };
  20916. Scene.prototype.disablePhysicsEngine = function () {
  20917. if (!this._physicsEngine) {
  20918. return;
  20919. }
  20920. this._physicsEngine.dispose();
  20921. this._physicsEngine = null;
  20922. };
  20923. Scene.prototype.isPhysicsEnabled = function () {
  20924. return this._physicsEngine !== undefined;
  20925. };
  20926. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20927. var mesh = compound.parts[0].mesh;
  20928. if (mesh.physicsImpostor) {
  20929. mesh.physicsImpostor.dispose();
  20930. mesh.physicsImpostor = null;
  20931. }
  20932. };
  20933. // Misc.
  20934. Scene.prototype._rebuildGeometries = function () {
  20935. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20936. var geometry = _a[_i];
  20937. geometry._rebuild();
  20938. }
  20939. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20940. var mesh = _c[_b];
  20941. mesh._rebuild();
  20942. }
  20943. if (this.postProcessManager) {
  20944. this.postProcessManager._rebuild();
  20945. }
  20946. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20947. var layer = _e[_d];
  20948. layer._rebuild();
  20949. }
  20950. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20951. var highlightLayer = _g[_f];
  20952. highlightLayer._rebuild();
  20953. }
  20954. if (this._boundingBoxRenderer) {
  20955. this._boundingBoxRenderer._rebuild();
  20956. }
  20957. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20958. var system = _j[_h];
  20959. system.rebuild();
  20960. }
  20961. if (this._postProcessRenderPipelineManager) {
  20962. this._postProcessRenderPipelineManager._rebuild();
  20963. }
  20964. };
  20965. Scene.prototype._rebuildTextures = function () {
  20966. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20967. var texture = _a[_i];
  20968. texture._rebuild();
  20969. }
  20970. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20971. };
  20972. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20973. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20974. if (replace === void 0) { replace = false; }
  20975. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20976. // Dispose existing camera or light in replace mode.
  20977. if (replace) {
  20978. if (this.activeCamera) {
  20979. this.activeCamera.dispose();
  20980. this.activeCamera = null;
  20981. }
  20982. if (this.lights) {
  20983. for (var i = 0; i < this.lights.length; i++) {
  20984. this.lights[i].dispose();
  20985. }
  20986. }
  20987. }
  20988. // Light
  20989. if (this.lights.length === 0) {
  20990. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20991. }
  20992. // Camera
  20993. if (!this.activeCamera) {
  20994. var worldExtends = this.getWorldExtends();
  20995. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20996. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20997. var camera;
  20998. var radius = worldSize.length() * 1.5;
  20999. if (createArcRotateCamera) {
  21000. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21001. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21002. arcRotateCamera.wheelPrecision = 100 / radius;
  21003. camera = arcRotateCamera;
  21004. }
  21005. else {
  21006. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21007. freeCamera.setTarget(worldCenter);
  21008. camera = freeCamera;
  21009. }
  21010. camera.minZ = radius * 0.01;
  21011. camera.maxZ = radius * 100;
  21012. camera.speed = radius * 0.2;
  21013. this.activeCamera = camera;
  21014. var canvas = this.getEngine().getRenderingCanvas();
  21015. if (attachCameraControls && canvas) {
  21016. camera.attachControl(canvas);
  21017. }
  21018. }
  21019. };
  21020. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21021. if (pbr === void 0) { pbr = false; }
  21022. if (scale === void 0) { scale = 1000; }
  21023. if (blur === void 0) { blur = 0; }
  21024. if (environmentTexture) {
  21025. this.environmentTexture = environmentTexture;
  21026. }
  21027. if (!this.environmentTexture) {
  21028. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21029. return null;
  21030. }
  21031. // Skybox
  21032. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21033. if (pbr) {
  21034. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  21035. hdrSkyboxMaterial.backFaceCulling = false;
  21036. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21037. if (hdrSkyboxMaterial.reflectionTexture) {
  21038. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21039. }
  21040. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  21041. hdrSkyboxMaterial.disableLighting = true;
  21042. hdrSkyboxMaterial.twoSidedLighting = true;
  21043. hdrSkybox.infiniteDistance = true;
  21044. hdrSkybox.material = hdrSkyboxMaterial;
  21045. }
  21046. else {
  21047. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  21048. skyboxMaterial.backFaceCulling = false;
  21049. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21050. if (skyboxMaterial.reflectionTexture) {
  21051. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21052. }
  21053. skyboxMaterial.disableLighting = true;
  21054. hdrSkybox.infiniteDistance = true;
  21055. hdrSkybox.material = skyboxMaterial;
  21056. }
  21057. return hdrSkybox;
  21058. };
  21059. Scene.prototype.createDefaultEnvironment = function (options) {
  21060. if (BABYLON.EnvironmentHelper) {
  21061. return new BABYLON.EnvironmentHelper(options, this);
  21062. }
  21063. return null;
  21064. };
  21065. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  21066. if (webVROptions === void 0) { webVROptions = {}; }
  21067. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  21068. };
  21069. // Tags
  21070. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21071. if (tagsQuery === undefined) {
  21072. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21073. return list;
  21074. }
  21075. var listByTags = [];
  21076. forEach = forEach || (function (item) { return; });
  21077. for (var i in list) {
  21078. var item = list[i];
  21079. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21080. listByTags.push(item);
  21081. forEach(item);
  21082. }
  21083. }
  21084. return listByTags;
  21085. };
  21086. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21087. return this._getByTags(this.meshes, tagsQuery, forEach);
  21088. };
  21089. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21090. return this._getByTags(this.cameras, tagsQuery, forEach);
  21091. };
  21092. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21093. return this._getByTags(this.lights, tagsQuery, forEach);
  21094. };
  21095. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21096. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21097. };
  21098. /**
  21099. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21100. * This allowed control for front to back rendering or reversly depending of the special needs.
  21101. *
  21102. * @param renderingGroupId The rendering group id corresponding to its index
  21103. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21104. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21105. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21106. */
  21107. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21108. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21109. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21110. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21111. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21112. };
  21113. /**
  21114. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21115. *
  21116. * @param renderingGroupId The rendering group id corresponding to its index
  21117. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21118. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21119. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21120. */
  21121. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21122. if (depth === void 0) { depth = true; }
  21123. if (stencil === void 0) { stencil = true; }
  21124. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21125. };
  21126. /**
  21127. * Will flag all materials as dirty to trigger new shader compilation
  21128. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21129. */
  21130. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21131. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21132. var material = _a[_i];
  21133. if (predicate && !predicate(material)) {
  21134. continue;
  21135. }
  21136. material.markAsDirty(flag);
  21137. }
  21138. };
  21139. // Statics
  21140. Scene._FOGMODE_NONE = 0;
  21141. Scene._FOGMODE_EXP = 1;
  21142. Scene._FOGMODE_EXP2 = 2;
  21143. Scene._FOGMODE_LINEAR = 3;
  21144. Scene._uniqueIdCounter = 0;
  21145. Scene.MinDeltaTime = 1.0;
  21146. Scene.MaxDeltaTime = 1000.0;
  21147. /** The distance in pixel that you have to move to prevent some events */
  21148. Scene.DragMovementThreshold = 10; // in pixels
  21149. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21150. Scene.LongPressDelay = 500; // in milliseconds
  21151. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21152. Scene.DoubleClickDelay = 300; // in milliseconds
  21153. /** If you need to check double click without raising a single click at first click, enable this flag */
  21154. Scene.ExclusiveDoubleClickMode = false;
  21155. return Scene;
  21156. }());
  21157. BABYLON.Scene = Scene;
  21158. })(BABYLON || (BABYLON = {}));
  21159. //# sourceMappingURL=babylon.scene.js.map
  21160. var BABYLON;
  21161. (function (BABYLON) {
  21162. var Buffer = /** @class */ (function () {
  21163. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21164. if (instanced === void 0) { instanced = false; }
  21165. if (engine instanceof BABYLON.Mesh) {
  21166. this._engine = engine.getScene().getEngine();
  21167. }
  21168. else {
  21169. this._engine = engine;
  21170. }
  21171. this._updatable = updatable;
  21172. this._data = data;
  21173. this._strideSize = stride;
  21174. if (!postponeInternalCreation) {
  21175. this.create();
  21176. }
  21177. this._instanced = instanced;
  21178. this._instanceDivisor = instanced ? 1 : 0;
  21179. }
  21180. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21181. // a lot of these parameters are ignored as they are overriden by the buffer
  21182. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21183. };
  21184. // Properties
  21185. Buffer.prototype.isUpdatable = function () {
  21186. return this._updatable;
  21187. };
  21188. Buffer.prototype.getData = function () {
  21189. return this._data;
  21190. };
  21191. Buffer.prototype.getBuffer = function () {
  21192. return this._buffer;
  21193. };
  21194. Buffer.prototype.getStrideSize = function () {
  21195. return this._strideSize;
  21196. };
  21197. Buffer.prototype.getIsInstanced = function () {
  21198. return this._instanced;
  21199. };
  21200. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21201. get: function () {
  21202. return this._instanceDivisor;
  21203. },
  21204. set: function (value) {
  21205. this._instanceDivisor = value;
  21206. if (value == 0) {
  21207. this._instanced = false;
  21208. }
  21209. else {
  21210. this._instanced = true;
  21211. }
  21212. },
  21213. enumerable: true,
  21214. configurable: true
  21215. });
  21216. // Methods
  21217. Buffer.prototype.create = function (data) {
  21218. if (data === void 0) { data = null; }
  21219. if (!data && this._buffer) {
  21220. return; // nothing to do
  21221. }
  21222. data = data || this._data;
  21223. if (!data) {
  21224. return;
  21225. }
  21226. if (!this._buffer) {
  21227. if (this._updatable) {
  21228. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21229. this._data = data;
  21230. }
  21231. else {
  21232. this._buffer = this._engine.createVertexBuffer(data);
  21233. }
  21234. }
  21235. else if (this._updatable) {
  21236. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21237. this._data = data;
  21238. }
  21239. };
  21240. Buffer.prototype._rebuild = function () {
  21241. this._buffer = null;
  21242. this.create(this._data);
  21243. };
  21244. Buffer.prototype.update = function (data) {
  21245. this.create(data);
  21246. };
  21247. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21248. if (!this._buffer) {
  21249. return;
  21250. }
  21251. if (this._updatable) {
  21252. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21253. this._data = null;
  21254. }
  21255. };
  21256. Buffer.prototype.dispose = function () {
  21257. if (!this._buffer) {
  21258. return;
  21259. }
  21260. if (this._engine._releaseBuffer(this._buffer)) {
  21261. this._buffer = null;
  21262. }
  21263. };
  21264. return Buffer;
  21265. }());
  21266. BABYLON.Buffer = Buffer;
  21267. })(BABYLON || (BABYLON = {}));
  21268. //# sourceMappingURL=babylon.buffer.js.map
  21269. var BABYLON;
  21270. (function (BABYLON) {
  21271. var VertexBuffer = /** @class */ (function () {
  21272. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21273. if (!stride) {
  21274. // Deduce stride from kind
  21275. switch (kind) {
  21276. case VertexBuffer.PositionKind:
  21277. stride = 3;
  21278. break;
  21279. case VertexBuffer.NormalKind:
  21280. stride = 3;
  21281. break;
  21282. case VertexBuffer.UVKind:
  21283. case VertexBuffer.UV2Kind:
  21284. case VertexBuffer.UV3Kind:
  21285. case VertexBuffer.UV4Kind:
  21286. case VertexBuffer.UV5Kind:
  21287. case VertexBuffer.UV6Kind:
  21288. stride = 2;
  21289. break;
  21290. case VertexBuffer.TangentKind:
  21291. case VertexBuffer.ColorKind:
  21292. stride = 4;
  21293. break;
  21294. case VertexBuffer.MatricesIndicesKind:
  21295. case VertexBuffer.MatricesIndicesExtraKind:
  21296. stride = 4;
  21297. break;
  21298. case VertexBuffer.MatricesWeightsKind:
  21299. case VertexBuffer.MatricesWeightsExtraKind:
  21300. default:
  21301. stride = 4;
  21302. break;
  21303. }
  21304. }
  21305. if (data instanceof BABYLON.Buffer) {
  21306. if (!stride) {
  21307. stride = data.getStrideSize();
  21308. }
  21309. this._buffer = data;
  21310. this._ownsBuffer = false;
  21311. }
  21312. else {
  21313. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21314. this._ownsBuffer = true;
  21315. }
  21316. this._stride = stride;
  21317. this._offset = offset ? offset : 0;
  21318. this._size = size ? size : stride;
  21319. this._kind = kind;
  21320. }
  21321. VertexBuffer.prototype._rebuild = function () {
  21322. if (!this._buffer) {
  21323. return;
  21324. }
  21325. this._buffer._rebuild();
  21326. };
  21327. /**
  21328. * Returns the kind of the VertexBuffer (string).
  21329. */
  21330. VertexBuffer.prototype.getKind = function () {
  21331. return this._kind;
  21332. };
  21333. // Properties
  21334. /**
  21335. * Boolean : is the VertexBuffer updatable ?
  21336. */
  21337. VertexBuffer.prototype.isUpdatable = function () {
  21338. return this._buffer.isUpdatable();
  21339. };
  21340. /**
  21341. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21342. */
  21343. VertexBuffer.prototype.getData = function () {
  21344. return this._buffer.getData();
  21345. };
  21346. /**
  21347. * Returns the WebGLBuffer associated to the VertexBuffer.
  21348. */
  21349. VertexBuffer.prototype.getBuffer = function () {
  21350. return this._buffer.getBuffer();
  21351. };
  21352. /**
  21353. * Returns the stride of the VertexBuffer (integer).
  21354. */
  21355. VertexBuffer.prototype.getStrideSize = function () {
  21356. return this._stride;
  21357. };
  21358. /**
  21359. * Returns the offset (integer).
  21360. */
  21361. VertexBuffer.prototype.getOffset = function () {
  21362. return this._offset;
  21363. };
  21364. /**
  21365. * Returns the VertexBuffer total size (integer).
  21366. */
  21367. VertexBuffer.prototype.getSize = function () {
  21368. return this._size;
  21369. };
  21370. /**
  21371. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21372. */
  21373. VertexBuffer.prototype.getIsInstanced = function () {
  21374. return this._buffer.getIsInstanced();
  21375. };
  21376. /**
  21377. * Returns the instancing divisor, zero for non-instanced (integer).
  21378. */
  21379. VertexBuffer.prototype.getInstanceDivisor = function () {
  21380. return this._buffer.instanceDivisor;
  21381. };
  21382. // Methods
  21383. /**
  21384. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21385. * Returns the created WebGLBuffer.
  21386. */
  21387. VertexBuffer.prototype.create = function (data) {
  21388. return this._buffer.create(data);
  21389. };
  21390. /**
  21391. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21392. * Returns the updated WebGLBuffer.
  21393. */
  21394. VertexBuffer.prototype.update = function (data) {
  21395. return this._buffer.update(data);
  21396. };
  21397. /**
  21398. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21399. * Returns the directly updated WebGLBuffer.
  21400. */
  21401. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21402. return this._buffer.updateDirectly(data, offset);
  21403. };
  21404. /**
  21405. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21406. */
  21407. VertexBuffer.prototype.dispose = function () {
  21408. if (this._ownsBuffer) {
  21409. this._buffer.dispose();
  21410. }
  21411. };
  21412. Object.defineProperty(VertexBuffer, "PositionKind", {
  21413. get: function () {
  21414. return VertexBuffer._PositionKind;
  21415. },
  21416. enumerable: true,
  21417. configurable: true
  21418. });
  21419. Object.defineProperty(VertexBuffer, "NormalKind", {
  21420. get: function () {
  21421. return VertexBuffer._NormalKind;
  21422. },
  21423. enumerable: true,
  21424. configurable: true
  21425. });
  21426. Object.defineProperty(VertexBuffer, "TangentKind", {
  21427. get: function () {
  21428. return VertexBuffer._TangentKind;
  21429. },
  21430. enumerable: true,
  21431. configurable: true
  21432. });
  21433. Object.defineProperty(VertexBuffer, "UVKind", {
  21434. get: function () {
  21435. return VertexBuffer._UVKind;
  21436. },
  21437. enumerable: true,
  21438. configurable: true
  21439. });
  21440. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21441. get: function () {
  21442. return VertexBuffer._UV2Kind;
  21443. },
  21444. enumerable: true,
  21445. configurable: true
  21446. });
  21447. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21448. get: function () {
  21449. return VertexBuffer._UV3Kind;
  21450. },
  21451. enumerable: true,
  21452. configurable: true
  21453. });
  21454. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21455. get: function () {
  21456. return VertexBuffer._UV4Kind;
  21457. },
  21458. enumerable: true,
  21459. configurable: true
  21460. });
  21461. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21462. get: function () {
  21463. return VertexBuffer._UV5Kind;
  21464. },
  21465. enumerable: true,
  21466. configurable: true
  21467. });
  21468. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21469. get: function () {
  21470. return VertexBuffer._UV6Kind;
  21471. },
  21472. enumerable: true,
  21473. configurable: true
  21474. });
  21475. Object.defineProperty(VertexBuffer, "ColorKind", {
  21476. get: function () {
  21477. return VertexBuffer._ColorKind;
  21478. },
  21479. enumerable: true,
  21480. configurable: true
  21481. });
  21482. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21483. get: function () {
  21484. return VertexBuffer._MatricesIndicesKind;
  21485. },
  21486. enumerable: true,
  21487. configurable: true
  21488. });
  21489. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21490. get: function () {
  21491. return VertexBuffer._MatricesWeightsKind;
  21492. },
  21493. enumerable: true,
  21494. configurable: true
  21495. });
  21496. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21497. get: function () {
  21498. return VertexBuffer._MatricesIndicesExtraKind;
  21499. },
  21500. enumerable: true,
  21501. configurable: true
  21502. });
  21503. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21504. get: function () {
  21505. return VertexBuffer._MatricesWeightsExtraKind;
  21506. },
  21507. enumerable: true,
  21508. configurable: true
  21509. });
  21510. // Enums
  21511. VertexBuffer._PositionKind = "position";
  21512. VertexBuffer._NormalKind = "normal";
  21513. VertexBuffer._TangentKind = "tangent";
  21514. VertexBuffer._UVKind = "uv";
  21515. VertexBuffer._UV2Kind = "uv2";
  21516. VertexBuffer._UV3Kind = "uv3";
  21517. VertexBuffer._UV4Kind = "uv4";
  21518. VertexBuffer._UV5Kind = "uv5";
  21519. VertexBuffer._UV6Kind = "uv6";
  21520. VertexBuffer._ColorKind = "color";
  21521. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21522. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21523. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21524. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21525. return VertexBuffer;
  21526. }());
  21527. BABYLON.VertexBuffer = VertexBuffer;
  21528. })(BABYLON || (BABYLON = {}));
  21529. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21530. var BABYLON;
  21531. (function (BABYLON) {
  21532. var InternalTexture = /** @class */ (function () {
  21533. function InternalTexture(engine, dataSource) {
  21534. this.onLoadedObservable = new BABYLON.Observable();
  21535. // Private
  21536. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21537. this._references = 1;
  21538. this._engine = engine;
  21539. this._dataSource = dataSource;
  21540. this._webGLTexture = engine._createTexture();
  21541. }
  21542. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21543. get: function () {
  21544. return this._dataSource;
  21545. },
  21546. enumerable: true,
  21547. configurable: true
  21548. });
  21549. InternalTexture.prototype.incrementReferences = function () {
  21550. this._references++;
  21551. };
  21552. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21553. if (depth === void 0) { depth = 1; }
  21554. this.width = width;
  21555. this.height = height;
  21556. this.depth = depth;
  21557. this.baseWidth = width;
  21558. this.baseHeight = height;
  21559. this.baseDepth = depth;
  21560. this._size = width * height * depth;
  21561. };
  21562. InternalTexture.prototype._rebuild = function () {
  21563. var _this = this;
  21564. var proxy;
  21565. this.isReady = false;
  21566. this._cachedCoordinatesMode = null;
  21567. this._cachedWrapU = null;
  21568. this._cachedWrapV = null;
  21569. this._cachedAnisotropicFilteringLevel = null;
  21570. switch (this._dataSource) {
  21571. case InternalTexture.DATASOURCE_TEMP:
  21572. return;
  21573. case InternalTexture.DATASOURCE_URL:
  21574. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21575. _this.isReady = true;
  21576. }, null, this._buffer, undefined, this.format);
  21577. proxy._swapAndDie(this);
  21578. return;
  21579. case InternalTexture.DATASOURCE_RAW:
  21580. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21581. proxy._swapAndDie(this);
  21582. this.isReady = true;
  21583. return;
  21584. case InternalTexture.DATASOURCE_RAW3D:
  21585. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21586. proxy._swapAndDie(this);
  21587. this.isReady = true;
  21588. return;
  21589. case InternalTexture.DATASOURCE_DYNAMIC:
  21590. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21591. proxy._swapAndDie(this);
  21592. // The engine will make sure to update content so no need to flag it as isReady = true
  21593. return;
  21594. case InternalTexture.DATASOURCE_RENDERTARGET:
  21595. var options = new BABYLON.RenderTargetCreationOptions();
  21596. options.generateDepthBuffer = this._generateDepthBuffer;
  21597. options.generateMipMaps = this.generateMipMaps;
  21598. options.generateStencilBuffer = this._generateStencilBuffer;
  21599. options.samplingMode = this.samplingMode;
  21600. options.type = this.type;
  21601. if (this.isCube) {
  21602. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21603. }
  21604. else {
  21605. var size = {
  21606. width: this.width,
  21607. height: this.height
  21608. };
  21609. proxy = this._engine.createRenderTargetTexture(size, options);
  21610. }
  21611. proxy._swapAndDie(this);
  21612. this.isReady = true;
  21613. return;
  21614. case InternalTexture.DATASOURCE_CUBE:
  21615. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21616. _this.isReady = true;
  21617. }, null, this.format, this._extension);
  21618. proxy._swapAndDie(this);
  21619. return;
  21620. case InternalTexture.DATASOURCE_CUBERAW:
  21621. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21622. proxy._swapAndDie(this);
  21623. this.isReady = true;
  21624. return;
  21625. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21626. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21627. if (proxy) {
  21628. proxy._swapAndDie(_this);
  21629. }
  21630. _this.isReady = true;
  21631. }, null, this.format, this._extension);
  21632. return;
  21633. }
  21634. };
  21635. InternalTexture.prototype._swapAndDie = function (target) {
  21636. target._webGLTexture = this._webGLTexture;
  21637. if (this._framebuffer) {
  21638. target._framebuffer = this._framebuffer;
  21639. }
  21640. if (this._depthStencilBuffer) {
  21641. target._depthStencilBuffer = this._depthStencilBuffer;
  21642. }
  21643. if (this._lodTextureHigh) {
  21644. if (target._lodTextureHigh) {
  21645. target._lodTextureHigh.dispose();
  21646. }
  21647. target._lodTextureHigh = this._lodTextureHigh;
  21648. }
  21649. if (this._lodTextureMid) {
  21650. if (target._lodTextureMid) {
  21651. target._lodTextureMid.dispose();
  21652. }
  21653. target._lodTextureMid = this._lodTextureMid;
  21654. }
  21655. if (this._lodTextureLow) {
  21656. if (target._lodTextureLow) {
  21657. target._lodTextureLow.dispose();
  21658. }
  21659. target._lodTextureLow = this._lodTextureLow;
  21660. }
  21661. var cache = this._engine.getLoadedTexturesCache();
  21662. var index = cache.indexOf(this);
  21663. if (index !== -1) {
  21664. cache.splice(index, 1);
  21665. }
  21666. };
  21667. InternalTexture.prototype.dispose = function () {
  21668. if (!this._webGLTexture) {
  21669. return;
  21670. }
  21671. this._references--;
  21672. if (this._references === 0) {
  21673. this._engine._releaseTexture(this);
  21674. this._webGLTexture = null;
  21675. }
  21676. };
  21677. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21678. InternalTexture.DATASOURCE_URL = 1;
  21679. InternalTexture.DATASOURCE_TEMP = 2;
  21680. InternalTexture.DATASOURCE_RAW = 3;
  21681. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21682. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21683. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21684. InternalTexture.DATASOURCE_CUBE = 7;
  21685. InternalTexture.DATASOURCE_CUBERAW = 8;
  21686. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21687. InternalTexture.DATASOURCE_RAW3D = 10;
  21688. return InternalTexture;
  21689. }());
  21690. BABYLON.InternalTexture = InternalTexture;
  21691. })(BABYLON || (BABYLON = {}));
  21692. //# sourceMappingURL=babylon.internalTexture.js.map
  21693. var BABYLON;
  21694. (function (BABYLON) {
  21695. var BaseTexture = /** @class */ (function () {
  21696. function BaseTexture(scene) {
  21697. this._hasAlpha = false;
  21698. this.getAlphaFromRGB = false;
  21699. this.level = 1;
  21700. this.coordinatesIndex = 0;
  21701. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21702. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21703. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21704. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21705. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21706. this.isCube = false;
  21707. this.is3D = false;
  21708. this.gammaSpace = true;
  21709. this.invertZ = false;
  21710. this.lodLevelInAlpha = false;
  21711. this.lodGenerationOffset = 0.0;
  21712. this.lodGenerationScale = 0.8;
  21713. this.isRenderTarget = false;
  21714. this.animations = new Array();
  21715. /**
  21716. * An event triggered when the texture is disposed.
  21717. * @type {BABYLON.Observable}
  21718. */
  21719. this.onDisposeObservable = new BABYLON.Observable();
  21720. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21721. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21722. if (this._scene) {
  21723. this._scene.textures.push(this);
  21724. }
  21725. this._uid = null;
  21726. }
  21727. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21728. get: function () {
  21729. return this._hasAlpha;
  21730. },
  21731. set: function (value) {
  21732. if (this._hasAlpha === value) {
  21733. return;
  21734. }
  21735. this._hasAlpha = value;
  21736. if (this._scene) {
  21737. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21738. }
  21739. },
  21740. enumerable: true,
  21741. configurable: true
  21742. });
  21743. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21744. get: function () {
  21745. return this._coordinatesMode;
  21746. },
  21747. set: function (value) {
  21748. if (this._coordinatesMode === value) {
  21749. return;
  21750. }
  21751. this._coordinatesMode = value;
  21752. if (this._scene) {
  21753. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21754. }
  21755. },
  21756. enumerable: true,
  21757. configurable: true
  21758. });
  21759. Object.defineProperty(BaseTexture.prototype, "uid", {
  21760. get: function () {
  21761. if (!this._uid) {
  21762. this._uid = BABYLON.Tools.RandomId();
  21763. }
  21764. return this._uid;
  21765. },
  21766. enumerable: true,
  21767. configurable: true
  21768. });
  21769. BaseTexture.prototype.toString = function () {
  21770. return this.name;
  21771. };
  21772. BaseTexture.prototype.getClassName = function () {
  21773. return "BaseTexture";
  21774. };
  21775. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21776. set: function (callback) {
  21777. if (this._onDisposeObserver) {
  21778. this.onDisposeObservable.remove(this._onDisposeObserver);
  21779. }
  21780. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21781. },
  21782. enumerable: true,
  21783. configurable: true
  21784. });
  21785. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21786. get: function () {
  21787. return true;
  21788. },
  21789. enumerable: true,
  21790. configurable: true
  21791. });
  21792. BaseTexture.prototype.getScene = function () {
  21793. return this._scene;
  21794. };
  21795. BaseTexture.prototype.getTextureMatrix = function () {
  21796. return BABYLON.Matrix.IdentityReadOnly;
  21797. };
  21798. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21799. return BABYLON.Matrix.IdentityReadOnly;
  21800. };
  21801. BaseTexture.prototype.getInternalTexture = function () {
  21802. return this._texture;
  21803. };
  21804. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21805. return !this.isBlocking || this.isReady();
  21806. };
  21807. BaseTexture.prototype.isReady = function () {
  21808. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21809. this.delayLoad();
  21810. return false;
  21811. }
  21812. if (this._texture) {
  21813. return this._texture.isReady;
  21814. }
  21815. return false;
  21816. };
  21817. BaseTexture.prototype.getSize = function () {
  21818. if (this._texture && this._texture.width) {
  21819. return new BABYLON.Size(this._texture.width, this._texture.height);
  21820. }
  21821. if (this._texture && this._texture._size) {
  21822. return new BABYLON.Size(this._texture._size, this._texture._size);
  21823. }
  21824. return BABYLON.Size.Zero();
  21825. };
  21826. BaseTexture.prototype.getBaseSize = function () {
  21827. if (!this.isReady() || !this._texture)
  21828. return BABYLON.Size.Zero();
  21829. if (this._texture._size) {
  21830. return new BABYLON.Size(this._texture._size, this._texture._size);
  21831. }
  21832. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21833. };
  21834. BaseTexture.prototype.scale = function (ratio) {
  21835. };
  21836. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21837. get: function () {
  21838. return false;
  21839. },
  21840. enumerable: true,
  21841. configurable: true
  21842. });
  21843. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21844. if (!this._scene) {
  21845. return null;
  21846. }
  21847. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21848. for (var index = 0; index < texturesCache.length; index++) {
  21849. var texturesCacheEntry = texturesCache[index];
  21850. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21851. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21852. texturesCacheEntry.incrementReferences();
  21853. return texturesCacheEntry;
  21854. }
  21855. }
  21856. }
  21857. return null;
  21858. };
  21859. BaseTexture.prototype._rebuild = function () {
  21860. };
  21861. BaseTexture.prototype.delayLoad = function () {
  21862. };
  21863. BaseTexture.prototype.clone = function () {
  21864. return null;
  21865. };
  21866. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21867. get: function () {
  21868. if (!this._texture) {
  21869. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21870. }
  21871. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21872. },
  21873. enumerable: true,
  21874. configurable: true
  21875. });
  21876. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21877. get: function () {
  21878. if (!this._texture) {
  21879. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21880. }
  21881. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21882. },
  21883. enumerable: true,
  21884. configurable: true
  21885. });
  21886. BaseTexture.prototype.readPixels = function (faceIndex) {
  21887. if (faceIndex === void 0) { faceIndex = 0; }
  21888. if (!this._texture) {
  21889. return null;
  21890. }
  21891. var size = this.getSize();
  21892. var scene = this.getScene();
  21893. if (!scene) {
  21894. return null;
  21895. }
  21896. var engine = scene.getEngine();
  21897. if (this._texture.isCube) {
  21898. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21899. }
  21900. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21901. };
  21902. BaseTexture.prototype.releaseInternalTexture = function () {
  21903. if (this._texture) {
  21904. this._texture.dispose();
  21905. this._texture = null;
  21906. }
  21907. };
  21908. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21909. get: function () {
  21910. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21911. return null;
  21912. }
  21913. if (!this._texture._sphericalPolynomial) {
  21914. this._texture._sphericalPolynomial =
  21915. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21916. }
  21917. return this._texture._sphericalPolynomial;
  21918. },
  21919. set: function (value) {
  21920. if (this._texture) {
  21921. this._texture._sphericalPolynomial = value;
  21922. }
  21923. },
  21924. enumerable: true,
  21925. configurable: true
  21926. });
  21927. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21928. get: function () {
  21929. if (this._texture) {
  21930. return this._texture._lodTextureHigh;
  21931. }
  21932. return null;
  21933. },
  21934. enumerable: true,
  21935. configurable: true
  21936. });
  21937. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21938. get: function () {
  21939. if (this._texture) {
  21940. return this._texture._lodTextureMid;
  21941. }
  21942. return null;
  21943. },
  21944. enumerable: true,
  21945. configurable: true
  21946. });
  21947. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21948. get: function () {
  21949. if (this._texture) {
  21950. return this._texture._lodTextureLow;
  21951. }
  21952. return null;
  21953. },
  21954. enumerable: true,
  21955. configurable: true
  21956. });
  21957. BaseTexture.prototype.dispose = function () {
  21958. if (!this._scene) {
  21959. return;
  21960. }
  21961. // Animations
  21962. this._scene.stopAnimation(this);
  21963. // Remove from scene
  21964. this._scene._removePendingData(this);
  21965. var index = this._scene.textures.indexOf(this);
  21966. if (index >= 0) {
  21967. this._scene.textures.splice(index, 1);
  21968. }
  21969. if (this._texture === undefined) {
  21970. return;
  21971. }
  21972. // Release
  21973. this.releaseInternalTexture();
  21974. // Callback
  21975. this.onDisposeObservable.notifyObservers(this);
  21976. this.onDisposeObservable.clear();
  21977. };
  21978. BaseTexture.prototype.serialize = function () {
  21979. if (!this.name) {
  21980. return null;
  21981. }
  21982. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21983. // Animations
  21984. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21985. return serializationObject;
  21986. };
  21987. BaseTexture.WhenAllReady = function (textures, callback) {
  21988. var numRemaining = textures.length;
  21989. if (numRemaining === 0) {
  21990. callback();
  21991. return;
  21992. }
  21993. var _loop_1 = function () {
  21994. texture = textures[i];
  21995. if (texture.isReady()) {
  21996. if (--numRemaining === 0) {
  21997. callback();
  21998. }
  21999. }
  22000. else {
  22001. onLoadObservable = texture.onLoadObservable;
  22002. var onLoadCallback_1 = function () {
  22003. onLoadObservable.removeCallback(onLoadCallback_1);
  22004. if (--numRemaining === 0) {
  22005. callback();
  22006. }
  22007. };
  22008. onLoadObservable.add(onLoadCallback_1);
  22009. }
  22010. };
  22011. var texture, onLoadObservable;
  22012. for (var i = 0; i < textures.length; i++) {
  22013. _loop_1();
  22014. }
  22015. };
  22016. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22017. __decorate([
  22018. BABYLON.serialize()
  22019. ], BaseTexture.prototype, "name", void 0);
  22020. __decorate([
  22021. BABYLON.serialize("hasAlpha")
  22022. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22023. __decorate([
  22024. BABYLON.serialize()
  22025. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22026. __decorate([
  22027. BABYLON.serialize()
  22028. ], BaseTexture.prototype, "level", void 0);
  22029. __decorate([
  22030. BABYLON.serialize()
  22031. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22032. __decorate([
  22033. BABYLON.serialize("coordinatesMode")
  22034. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  22035. __decorate([
  22036. BABYLON.serialize()
  22037. ], BaseTexture.prototype, "wrapU", void 0);
  22038. __decorate([
  22039. BABYLON.serialize()
  22040. ], BaseTexture.prototype, "wrapV", void 0);
  22041. __decorate([
  22042. BABYLON.serialize()
  22043. ], BaseTexture.prototype, "wrapR", void 0);
  22044. __decorate([
  22045. BABYLON.serialize()
  22046. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22047. __decorate([
  22048. BABYLON.serialize()
  22049. ], BaseTexture.prototype, "isCube", void 0);
  22050. __decorate([
  22051. BABYLON.serialize()
  22052. ], BaseTexture.prototype, "is3D", void 0);
  22053. __decorate([
  22054. BABYLON.serialize()
  22055. ], BaseTexture.prototype, "gammaSpace", void 0);
  22056. __decorate([
  22057. BABYLON.serialize()
  22058. ], BaseTexture.prototype, "invertZ", void 0);
  22059. __decorate([
  22060. BABYLON.serialize()
  22061. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  22062. __decorate([
  22063. BABYLON.serialize()
  22064. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  22065. __decorate([
  22066. BABYLON.serialize()
  22067. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  22068. __decorate([
  22069. BABYLON.serialize()
  22070. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22071. return BaseTexture;
  22072. }());
  22073. BABYLON.BaseTexture = BaseTexture;
  22074. })(BABYLON || (BABYLON = {}));
  22075. //# sourceMappingURL=babylon.baseTexture.js.map
  22076. var BABYLON;
  22077. (function (BABYLON) {
  22078. var Texture = /** @class */ (function (_super) {
  22079. __extends(Texture, _super);
  22080. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  22081. if (noMipmap === void 0) { noMipmap = false; }
  22082. if (invertY === void 0) { invertY = true; }
  22083. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22084. if (onLoad === void 0) { onLoad = null; }
  22085. if (onError === void 0) { onError = null; }
  22086. if (buffer === void 0) { buffer = null; }
  22087. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22088. var _this = _super.call(this, scene) || this;
  22089. _this.uOffset = 0;
  22090. _this.vOffset = 0;
  22091. _this.uScale = 1.0;
  22092. _this.vScale = 1.0;
  22093. _this.uAng = 0;
  22094. _this.vAng = 0;
  22095. _this.wAng = 0;
  22096. _this._isBlocking = true;
  22097. _this.name = url || "";
  22098. _this.url = url;
  22099. _this._noMipmap = noMipmap;
  22100. _this._invertY = invertY;
  22101. _this._samplingMode = samplingMode;
  22102. _this._buffer = buffer;
  22103. _this._deleteBuffer = deleteBuffer;
  22104. if (format) {
  22105. _this._format = format;
  22106. }
  22107. scene = _this.getScene();
  22108. if (!scene) {
  22109. return _this;
  22110. }
  22111. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22112. var load = function () {
  22113. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22114. _this.onLoadObservable.notifyObservers(_this);
  22115. }
  22116. if (onLoad) {
  22117. onLoad();
  22118. }
  22119. if (!_this.isBlocking && scene) {
  22120. scene.resetCachedMaterial();
  22121. }
  22122. };
  22123. if (!_this.url) {
  22124. _this._delayedOnLoad = load;
  22125. _this._delayedOnError = onError;
  22126. return _this;
  22127. }
  22128. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22129. if (!_this._texture) {
  22130. if (!scene.useDelayedTextureLoading) {
  22131. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22132. if (deleteBuffer) {
  22133. delete _this._buffer;
  22134. }
  22135. }
  22136. else {
  22137. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22138. _this._delayedOnLoad = load;
  22139. _this._delayedOnError = onError;
  22140. }
  22141. }
  22142. else {
  22143. if (_this._texture.isReady) {
  22144. BABYLON.Tools.SetImmediate(function () { return load(); });
  22145. }
  22146. else {
  22147. _this._texture.onLoadedObservable.add(load);
  22148. }
  22149. }
  22150. return _this;
  22151. }
  22152. Object.defineProperty(Texture.prototype, "noMipmap", {
  22153. get: function () {
  22154. return this._noMipmap;
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. Object.defineProperty(Texture.prototype, "isBlocking", {
  22160. get: function () {
  22161. return this._isBlocking;
  22162. },
  22163. set: function (value) {
  22164. this._isBlocking = value;
  22165. },
  22166. enumerable: true,
  22167. configurable: true
  22168. });
  22169. Object.defineProperty(Texture.prototype, "samplingMode", {
  22170. get: function () {
  22171. return this._samplingMode;
  22172. },
  22173. enumerable: true,
  22174. configurable: true
  22175. });
  22176. Texture.prototype.updateURL = function (url) {
  22177. this.url = url;
  22178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22179. this.delayLoad();
  22180. };
  22181. Texture.prototype.delayLoad = function () {
  22182. var _this = this;
  22183. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22184. return;
  22185. }
  22186. var scene = this.getScene();
  22187. if (!scene) {
  22188. return;
  22189. }
  22190. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22191. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22192. if (!this._texture) {
  22193. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22194. if (this._deleteBuffer) {
  22195. delete this._buffer;
  22196. }
  22197. }
  22198. else {
  22199. if (this._texture.isReady) {
  22200. BABYLON.Tools.SetImmediate(function () {
  22201. if (!_this._delayedOnLoad) {
  22202. return;
  22203. }
  22204. _this._delayedOnLoad();
  22205. });
  22206. }
  22207. else {
  22208. if (this._delayedOnLoad) {
  22209. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22210. }
  22211. }
  22212. }
  22213. };
  22214. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22215. if (!this._texture) {
  22216. return;
  22217. }
  22218. var scene = this.getScene();
  22219. if (!scene) {
  22220. return;
  22221. }
  22222. this._samplingMode = samplingMode;
  22223. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22224. };
  22225. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22226. x *= this.uScale;
  22227. y *= this.vScale;
  22228. x -= 0.5 * this.uScale;
  22229. y -= 0.5 * this.vScale;
  22230. z -= 0.5;
  22231. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22232. t.x += 0.5 * this.uScale + this.uOffset;
  22233. t.y += 0.5 * this.vScale + this.vOffset;
  22234. t.z += 0.5;
  22235. };
  22236. Texture.prototype.getTextureMatrix = function () {
  22237. var _this = this;
  22238. if (this.uOffset === this._cachedUOffset &&
  22239. this.vOffset === this._cachedVOffset &&
  22240. this.uScale === this._cachedUScale &&
  22241. this.vScale === this._cachedVScale &&
  22242. this.uAng === this._cachedUAng &&
  22243. this.vAng === this._cachedVAng &&
  22244. this.wAng === this._cachedWAng) {
  22245. return this._cachedTextureMatrix;
  22246. }
  22247. this._cachedUOffset = this.uOffset;
  22248. this._cachedVOffset = this.vOffset;
  22249. this._cachedUScale = this.uScale;
  22250. this._cachedVScale = this.vScale;
  22251. this._cachedUAng = this.uAng;
  22252. this._cachedVAng = this.vAng;
  22253. this._cachedWAng = this.wAng;
  22254. if (!this._cachedTextureMatrix) {
  22255. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22256. this._rowGenerationMatrix = new BABYLON.Matrix();
  22257. this._t0 = BABYLON.Vector3.Zero();
  22258. this._t1 = BABYLON.Vector3.Zero();
  22259. this._t2 = BABYLON.Vector3.Zero();
  22260. }
  22261. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22262. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22263. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22264. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22265. this._t1.subtractInPlace(this._t0);
  22266. this._t2.subtractInPlace(this._t0);
  22267. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22268. this._cachedTextureMatrix.m[0] = this._t1.x;
  22269. this._cachedTextureMatrix.m[1] = this._t1.y;
  22270. this._cachedTextureMatrix.m[2] = this._t1.z;
  22271. this._cachedTextureMatrix.m[4] = this._t2.x;
  22272. this._cachedTextureMatrix.m[5] = this._t2.y;
  22273. this._cachedTextureMatrix.m[6] = this._t2.z;
  22274. this._cachedTextureMatrix.m[8] = this._t0.x;
  22275. this._cachedTextureMatrix.m[9] = this._t0.y;
  22276. this._cachedTextureMatrix.m[10] = this._t0.z;
  22277. var scene = this.getScene();
  22278. if (!scene) {
  22279. return this._cachedTextureMatrix;
  22280. }
  22281. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22282. return mat.hasTexture(_this);
  22283. });
  22284. return this._cachedTextureMatrix;
  22285. };
  22286. Texture.prototype.getReflectionTextureMatrix = function () {
  22287. var _this = this;
  22288. var scene = this.getScene();
  22289. if (!scene) {
  22290. return this._cachedTextureMatrix;
  22291. }
  22292. if (this.uOffset === this._cachedUOffset &&
  22293. this.vOffset === this._cachedVOffset &&
  22294. this.uScale === this._cachedUScale &&
  22295. this.vScale === this._cachedVScale &&
  22296. this.coordinatesMode === this._cachedCoordinatesMode) {
  22297. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22298. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22299. return this._cachedTextureMatrix;
  22300. }
  22301. }
  22302. else {
  22303. return this._cachedTextureMatrix;
  22304. }
  22305. }
  22306. if (!this._cachedTextureMatrix) {
  22307. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22308. }
  22309. if (!this._projectionModeMatrix) {
  22310. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22311. }
  22312. this._cachedUOffset = this.uOffset;
  22313. this._cachedVOffset = this.vOffset;
  22314. this._cachedUScale = this.uScale;
  22315. this._cachedVScale = this.vScale;
  22316. this._cachedCoordinatesMode = this.coordinatesMode;
  22317. switch (this.coordinatesMode) {
  22318. case Texture.PLANAR_MODE:
  22319. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22320. this._cachedTextureMatrix[0] = this.uScale;
  22321. this._cachedTextureMatrix[5] = this.vScale;
  22322. this._cachedTextureMatrix[12] = this.uOffset;
  22323. this._cachedTextureMatrix[13] = this.vOffset;
  22324. break;
  22325. case Texture.PROJECTION_MODE:
  22326. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22327. this._projectionModeMatrix.m[0] = 0.5;
  22328. this._projectionModeMatrix.m[5] = -0.5;
  22329. this._projectionModeMatrix.m[10] = 0.0;
  22330. this._projectionModeMatrix.m[12] = 0.5;
  22331. this._projectionModeMatrix.m[13] = 0.5;
  22332. this._projectionModeMatrix.m[14] = 1.0;
  22333. this._projectionModeMatrix.m[15] = 1.0;
  22334. var projectionMatrix = scene.getProjectionMatrix();
  22335. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22336. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22337. break;
  22338. default:
  22339. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22340. break;
  22341. }
  22342. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22343. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22344. });
  22345. return this._cachedTextureMatrix;
  22346. };
  22347. Texture.prototype.clone = function () {
  22348. var _this = this;
  22349. return BABYLON.SerializationHelper.Clone(function () {
  22350. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22351. }, this);
  22352. };
  22353. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22354. get: function () {
  22355. if (!this._onLoadObservable) {
  22356. this._onLoadObservable = new BABYLON.Observable();
  22357. }
  22358. return this._onLoadObservable;
  22359. },
  22360. enumerable: true,
  22361. configurable: true
  22362. });
  22363. Texture.prototype.serialize = function () {
  22364. var serializationObject = _super.prototype.serialize.call(this);
  22365. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22366. serializationObject.base64String = this._buffer;
  22367. serializationObject.name = serializationObject.name.replace("data:", "");
  22368. }
  22369. return serializationObject;
  22370. };
  22371. Texture.prototype.getClassName = function () {
  22372. return "Texture";
  22373. };
  22374. Texture.prototype.dispose = function () {
  22375. _super.prototype.dispose.call(this);
  22376. if (this.onLoadObservable) {
  22377. this.onLoadObservable.clear();
  22378. this._onLoadObservable = null;
  22379. }
  22380. this._delayedOnLoad = null;
  22381. this._delayedOnError = null;
  22382. };
  22383. // Statics
  22384. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22385. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22386. if (onLoad === void 0) { onLoad = null; }
  22387. if (onError === void 0) { onError = null; }
  22388. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22389. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22390. };
  22391. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22392. if (parsedTexture.customType) {
  22393. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22394. // Update Sampling Mode
  22395. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22396. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22397. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22398. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22399. }
  22400. }
  22401. return parsedCustomTexture;
  22402. }
  22403. if (parsedTexture.isCube) {
  22404. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22405. }
  22406. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22407. return null;
  22408. }
  22409. var texture = BABYLON.SerializationHelper.Parse(function () {
  22410. if (parsedTexture.mirrorPlane) {
  22411. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22412. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22413. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22414. return mirrorTexture;
  22415. }
  22416. else if (parsedTexture.isRenderTarget) {
  22417. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22418. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22419. return renderTargetTexture;
  22420. }
  22421. else {
  22422. var texture;
  22423. if (parsedTexture.base64String) {
  22424. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22425. }
  22426. else {
  22427. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22428. }
  22429. return texture;
  22430. }
  22431. }, parsedTexture, scene);
  22432. // Update Sampling Mode
  22433. if (parsedTexture.samplingMode) {
  22434. var sampling = parsedTexture.samplingMode;
  22435. if (texture._samplingMode !== sampling) {
  22436. texture.updateSamplingMode(sampling);
  22437. }
  22438. }
  22439. // Animations
  22440. if (parsedTexture.animations) {
  22441. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22442. var parsedAnimation = parsedTexture.animations[animationIndex];
  22443. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22444. }
  22445. }
  22446. return texture;
  22447. };
  22448. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22449. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22450. if (noMipmap === void 0) { noMipmap = false; }
  22451. if (invertY === void 0) { invertY = true; }
  22452. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22453. if (onLoad === void 0) { onLoad = null; }
  22454. if (onError === void 0) { onError = null; }
  22455. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22456. if (name.substr(0, 5) !== "data:") {
  22457. name = "data:" + name;
  22458. }
  22459. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22460. };
  22461. // Constants
  22462. Texture.NEAREST_SAMPLINGMODE = 1;
  22463. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22464. Texture.BILINEAR_SAMPLINGMODE = 2;
  22465. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22466. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22467. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22468. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22469. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22470. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22471. Texture.NEAREST_LINEAR = 7;
  22472. Texture.NEAREST_NEAREST = 8;
  22473. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22474. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22475. Texture.LINEAR_LINEAR = 11;
  22476. Texture.LINEAR_NEAREST = 12;
  22477. Texture.EXPLICIT_MODE = 0;
  22478. Texture.SPHERICAL_MODE = 1;
  22479. Texture.PLANAR_MODE = 2;
  22480. Texture.CUBIC_MODE = 3;
  22481. Texture.PROJECTION_MODE = 4;
  22482. Texture.SKYBOX_MODE = 5;
  22483. Texture.INVCUBIC_MODE = 6;
  22484. Texture.EQUIRECTANGULAR_MODE = 7;
  22485. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22486. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22487. Texture.CLAMP_ADDRESSMODE = 0;
  22488. Texture.WRAP_ADDRESSMODE = 1;
  22489. Texture.MIRROR_ADDRESSMODE = 2;
  22490. __decorate([
  22491. BABYLON.serialize()
  22492. ], Texture.prototype, "url", void 0);
  22493. __decorate([
  22494. BABYLON.serialize()
  22495. ], Texture.prototype, "uOffset", void 0);
  22496. __decorate([
  22497. BABYLON.serialize()
  22498. ], Texture.prototype, "vOffset", void 0);
  22499. __decorate([
  22500. BABYLON.serialize()
  22501. ], Texture.prototype, "uScale", void 0);
  22502. __decorate([
  22503. BABYLON.serialize()
  22504. ], Texture.prototype, "vScale", void 0);
  22505. __decorate([
  22506. BABYLON.serialize()
  22507. ], Texture.prototype, "uAng", void 0);
  22508. __decorate([
  22509. BABYLON.serialize()
  22510. ], Texture.prototype, "vAng", void 0);
  22511. __decorate([
  22512. BABYLON.serialize()
  22513. ], Texture.prototype, "wAng", void 0);
  22514. __decorate([
  22515. BABYLON.serialize()
  22516. ], Texture.prototype, "isBlocking", null);
  22517. return Texture;
  22518. }(BABYLON.BaseTexture));
  22519. BABYLON.Texture = Texture;
  22520. })(BABYLON || (BABYLON = {}));
  22521. //# sourceMappingURL=babylon.texture.js.map
  22522. var BABYLON;
  22523. (function (BABYLON) {
  22524. var _InstancesBatch = /** @class */ (function () {
  22525. function _InstancesBatch() {
  22526. this.mustReturn = false;
  22527. this.visibleInstances = new Array();
  22528. this.renderSelf = new Array();
  22529. }
  22530. return _InstancesBatch;
  22531. }());
  22532. BABYLON._InstancesBatch = _InstancesBatch;
  22533. var Mesh = /** @class */ (function (_super) {
  22534. __extends(Mesh, _super);
  22535. /**
  22536. * @constructor
  22537. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22538. * @param {Scene} scene The scene to add this mesh to.
  22539. * @param {Node} parent The parent of this mesh, if it has one
  22540. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22541. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22542. * When false, achieved by calling a clone(), also passing False.
  22543. * This will make creation of children, recursive.
  22544. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22545. */
  22546. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22547. if (scene === void 0) { scene = null; }
  22548. if (parent === void 0) { parent = null; }
  22549. if (source === void 0) { source = null; }
  22550. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22551. var _this = _super.call(this, name, scene) || this;
  22552. // Events
  22553. /**
  22554. * An event triggered before rendering the mesh
  22555. * @type {BABYLON.Observable}
  22556. */
  22557. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22558. /**
  22559. * An event triggered after rendering the mesh
  22560. * @type {BABYLON.Observable}
  22561. */
  22562. _this.onAfterRenderObservable = new BABYLON.Observable();
  22563. /**
  22564. * An event triggered before drawing the mesh
  22565. * @type {BABYLON.Observable}
  22566. */
  22567. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22568. // Members
  22569. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22570. _this.instances = new Array();
  22571. _this._LODLevels = new Array();
  22572. _this._visibleInstances = {};
  22573. _this._renderIdForInstances = new Array();
  22574. _this._batchCache = new _InstancesBatch();
  22575. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22576. // Use by builder only to know what orientation were the mesh build in.
  22577. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22578. _this.overrideMaterialSideOrientation = null;
  22579. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22580. // Will be used to save a source mesh reference, If any
  22581. _this._source = null;
  22582. scene = _this.getScene();
  22583. if (source) {
  22584. // Source mesh
  22585. _this._source = source;
  22586. // Geometry
  22587. if (source._geometry) {
  22588. source._geometry.applyToMesh(_this);
  22589. }
  22590. // Deep copy
  22591. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22592. // Tags
  22593. if (BABYLON.Tags.HasTags(source)) {
  22594. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22595. }
  22596. _this.metadata = source.metadata;
  22597. // Parent
  22598. _this.parent = source.parent;
  22599. // Pivot
  22600. _this.setPivotMatrix(source.getPivotMatrix());
  22601. _this.id = name + "." + source.id;
  22602. // Material
  22603. _this.material = source.material;
  22604. var index;
  22605. if (!doNotCloneChildren) {
  22606. // Children
  22607. for (index = 0; index < scene.meshes.length; index++) {
  22608. var mesh = scene.meshes[index];
  22609. if (mesh.parent === source) {
  22610. // doNotCloneChildren is always going to be False
  22611. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22612. }
  22613. }
  22614. }
  22615. // Physics clone
  22616. var physicsEngine = _this.getScene().getPhysicsEngine();
  22617. if (clonePhysicsImpostor && physicsEngine) {
  22618. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22619. if (impostor) {
  22620. _this.physicsImpostor = impostor.clone(_this);
  22621. }
  22622. }
  22623. // Particles
  22624. for (index = 0; index < scene.particleSystems.length; index++) {
  22625. var system = scene.particleSystems[index];
  22626. if (system.emitter === source) {
  22627. system.clone(system.name, _this);
  22628. }
  22629. }
  22630. _this.computeWorldMatrix(true);
  22631. }
  22632. // Parent
  22633. if (parent !== null) {
  22634. _this.parent = parent;
  22635. }
  22636. return _this;
  22637. }
  22638. Object.defineProperty(Mesh, "FRONTSIDE", {
  22639. /**
  22640. * Mesh side orientation : usually the external or front surface
  22641. */
  22642. get: function () {
  22643. return Mesh._FRONTSIDE;
  22644. },
  22645. enumerable: true,
  22646. configurable: true
  22647. });
  22648. Object.defineProperty(Mesh, "BACKSIDE", {
  22649. /**
  22650. * Mesh side orientation : usually the internal or back surface
  22651. */
  22652. get: function () {
  22653. return Mesh._BACKSIDE;
  22654. },
  22655. enumerable: true,
  22656. configurable: true
  22657. });
  22658. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22659. /**
  22660. * Mesh side orientation : both internal and external or front and back surfaces
  22661. */
  22662. get: function () {
  22663. return Mesh._DOUBLESIDE;
  22664. },
  22665. enumerable: true,
  22666. configurable: true
  22667. });
  22668. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22669. /**
  22670. * Mesh side orientation : by default, `FRONTSIDE`
  22671. */
  22672. get: function () {
  22673. return Mesh._DEFAULTSIDE;
  22674. },
  22675. enumerable: true,
  22676. configurable: true
  22677. });
  22678. Object.defineProperty(Mesh, "NO_CAP", {
  22679. /**
  22680. * Mesh cap setting : no cap
  22681. */
  22682. get: function () {
  22683. return Mesh._NO_CAP;
  22684. },
  22685. enumerable: true,
  22686. configurable: true
  22687. });
  22688. Object.defineProperty(Mesh, "CAP_START", {
  22689. /**
  22690. * Mesh cap setting : one cap at the beginning of the mesh
  22691. */
  22692. get: function () {
  22693. return Mesh._CAP_START;
  22694. },
  22695. enumerable: true,
  22696. configurable: true
  22697. });
  22698. Object.defineProperty(Mesh, "CAP_END", {
  22699. /**
  22700. * Mesh cap setting : one cap at the end of the mesh
  22701. */
  22702. get: function () {
  22703. return Mesh._CAP_END;
  22704. },
  22705. enumerable: true,
  22706. configurable: true
  22707. });
  22708. Object.defineProperty(Mesh, "CAP_ALL", {
  22709. /**
  22710. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22711. */
  22712. get: function () {
  22713. return Mesh._CAP_ALL;
  22714. },
  22715. enumerable: true,
  22716. configurable: true
  22717. });
  22718. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22719. set: function (callback) {
  22720. if (this._onBeforeDrawObserver) {
  22721. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22722. }
  22723. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22724. },
  22725. enumerable: true,
  22726. configurable: true
  22727. });
  22728. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22729. get: function () {
  22730. return this._morphTargetManager;
  22731. },
  22732. set: function (value) {
  22733. if (this._morphTargetManager === value) {
  22734. return;
  22735. }
  22736. this._morphTargetManager = value;
  22737. this._syncGeometryWithMorphTargetManager();
  22738. },
  22739. enumerable: true,
  22740. configurable: true
  22741. });
  22742. Object.defineProperty(Mesh.prototype, "source", {
  22743. get: function () {
  22744. return this._source;
  22745. },
  22746. enumerable: true,
  22747. configurable: true
  22748. });
  22749. // Methods
  22750. /**
  22751. * Returns the string "Mesh".
  22752. */
  22753. Mesh.prototype.getClassName = function () {
  22754. return "Mesh";
  22755. };
  22756. /**
  22757. * Returns a string.
  22758. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22759. */
  22760. Mesh.prototype.toString = function (fullDetails) {
  22761. var ret = _super.prototype.toString.call(this, fullDetails);
  22762. ret += ", n vertices: " + this.getTotalVertices();
  22763. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22764. if (this.animations) {
  22765. for (var i = 0; i < this.animations.length; i++) {
  22766. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22767. }
  22768. }
  22769. if (fullDetails) {
  22770. if (this._geometry) {
  22771. var ib = this.getIndices();
  22772. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22773. if (vb && ib) {
  22774. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22775. }
  22776. }
  22777. else {
  22778. ret += ", flat shading: UNKNOWN";
  22779. }
  22780. }
  22781. return ret;
  22782. };
  22783. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22784. /**
  22785. * True if the mesh has some Levels Of Details (LOD).
  22786. * Returns a boolean.
  22787. */
  22788. get: function () {
  22789. return this._LODLevels.length > 0;
  22790. },
  22791. enumerable: true,
  22792. configurable: true
  22793. });
  22794. Mesh.prototype._sortLODLevels = function () {
  22795. this._LODLevels.sort(function (a, b) {
  22796. if (a.distance < b.distance) {
  22797. return 1;
  22798. }
  22799. if (a.distance > b.distance) {
  22800. return -1;
  22801. }
  22802. return 0;
  22803. });
  22804. };
  22805. /**
  22806. * Add a mesh as LOD level triggered at the given distance.
  22807. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22808. * @param {number} distance The distance from the center of the object to show this level
  22809. * @param {Mesh} mesh The mesh to be added as LOD level
  22810. * @return {Mesh} This mesh (for chaining)
  22811. */
  22812. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22813. if (mesh && mesh._masterMesh) {
  22814. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22815. return this;
  22816. }
  22817. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22818. this._LODLevels.push(level);
  22819. if (mesh) {
  22820. mesh._masterMesh = this;
  22821. }
  22822. this._sortLODLevels();
  22823. return this;
  22824. };
  22825. /**
  22826. * Returns the LOD level mesh at the passed distance or null if not found.
  22827. * It is related to the method `addLODLevel(distance, mesh)`.
  22828. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22829. * Returns an object Mesh or `null`.
  22830. */
  22831. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22832. for (var index = 0; index < this._LODLevels.length; index++) {
  22833. var level = this._LODLevels[index];
  22834. if (level.distance === distance) {
  22835. return level.mesh;
  22836. }
  22837. }
  22838. return null;
  22839. };
  22840. /**
  22841. * Remove a mesh from the LOD array
  22842. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22843. * @param {Mesh} mesh The mesh to be removed.
  22844. * @return {Mesh} This mesh (for chaining)
  22845. */
  22846. Mesh.prototype.removeLODLevel = function (mesh) {
  22847. for (var index = 0; index < this._LODLevels.length; index++) {
  22848. if (this._LODLevels[index].mesh === mesh) {
  22849. this._LODLevels.splice(index, 1);
  22850. if (mesh) {
  22851. mesh._masterMesh = null;
  22852. }
  22853. }
  22854. }
  22855. this._sortLODLevels();
  22856. return this;
  22857. };
  22858. /**
  22859. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22860. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22861. */
  22862. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22863. if (!this._LODLevels || this._LODLevels.length === 0) {
  22864. return this;
  22865. }
  22866. var bSphere;
  22867. if (boundingSphere) {
  22868. bSphere = boundingSphere;
  22869. }
  22870. else {
  22871. var boundingInfo = this.getBoundingInfo();
  22872. if (!boundingInfo) {
  22873. return this;
  22874. }
  22875. bSphere = boundingInfo.boundingSphere;
  22876. }
  22877. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22878. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22879. if (this.onLODLevelSelection) {
  22880. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22881. }
  22882. return this;
  22883. }
  22884. for (var index = 0; index < this._LODLevels.length; index++) {
  22885. var level = this._LODLevels[index];
  22886. if (level.distance < distanceToCamera) {
  22887. if (level.mesh) {
  22888. level.mesh._preActivate();
  22889. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22890. }
  22891. if (this.onLODLevelSelection) {
  22892. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22893. }
  22894. return level.mesh;
  22895. }
  22896. }
  22897. if (this.onLODLevelSelection) {
  22898. this.onLODLevelSelection(distanceToCamera, this, this);
  22899. }
  22900. return this;
  22901. };
  22902. Object.defineProperty(Mesh.prototype, "geometry", {
  22903. /**
  22904. * Returns the mesh internal Geometry object.
  22905. */
  22906. get: function () {
  22907. return this._geometry;
  22908. },
  22909. enumerable: true,
  22910. configurable: true
  22911. });
  22912. /**
  22913. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22914. */
  22915. Mesh.prototype.getTotalVertices = function () {
  22916. if (!this._geometry) {
  22917. return 0;
  22918. }
  22919. return this._geometry.getTotalVertices();
  22920. };
  22921. /**
  22922. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22923. * 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.
  22924. * You can force the copy with forceCopy === true
  22925. * Returns null if the mesh has no geometry or no vertex buffer.
  22926. * Possible `kind` values :
  22927. * - BABYLON.VertexBuffer.PositionKind
  22928. * - BABYLON.VertexBuffer.UVKind
  22929. * - BABYLON.VertexBuffer.UV2Kind
  22930. * - BABYLON.VertexBuffer.UV3Kind
  22931. * - BABYLON.VertexBuffer.UV4Kind
  22932. * - BABYLON.VertexBuffer.UV5Kind
  22933. * - BABYLON.VertexBuffer.UV6Kind
  22934. * - BABYLON.VertexBuffer.ColorKind
  22935. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22936. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22937. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22938. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22939. */
  22940. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22941. if (!this._geometry) {
  22942. return null;
  22943. }
  22944. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22945. };
  22946. /**
  22947. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22948. * Returns `null` if the mesh has no geometry.
  22949. * Possible `kind` values :
  22950. * - BABYLON.VertexBuffer.PositionKind
  22951. * - BABYLON.VertexBuffer.UVKind
  22952. * - BABYLON.VertexBuffer.UV2Kind
  22953. * - BABYLON.VertexBuffer.UV3Kind
  22954. * - BABYLON.VertexBuffer.UV4Kind
  22955. * - BABYLON.VertexBuffer.UV5Kind
  22956. * - BABYLON.VertexBuffer.UV6Kind
  22957. * - BABYLON.VertexBuffer.ColorKind
  22958. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22959. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22960. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22961. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22962. */
  22963. Mesh.prototype.getVertexBuffer = function (kind) {
  22964. if (!this._geometry) {
  22965. return null;
  22966. }
  22967. return this._geometry.getVertexBuffer(kind);
  22968. };
  22969. /**
  22970. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22971. * Possible `kind` values :
  22972. * - BABYLON.VertexBuffer.PositionKind
  22973. * - BABYLON.VertexBuffer.UVKind
  22974. * - BABYLON.VertexBuffer.UV2Kind
  22975. * - BABYLON.VertexBuffer.UV3Kind
  22976. * - BABYLON.VertexBuffer.UV4Kind
  22977. * - BABYLON.VertexBuffer.UV5Kind
  22978. * - BABYLON.VertexBuffer.UV6Kind
  22979. * - BABYLON.VertexBuffer.ColorKind
  22980. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22981. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22982. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22983. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22984. */
  22985. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22986. if (!this._geometry) {
  22987. if (this._delayInfo) {
  22988. return this._delayInfo.indexOf(kind) !== -1;
  22989. }
  22990. return false;
  22991. }
  22992. return this._geometry.isVerticesDataPresent(kind);
  22993. };
  22994. /**
  22995. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22996. * Possible `kind` values :
  22997. * - BABYLON.VertexBuffer.PositionKind
  22998. * - BABYLON.VertexBuffer.UVKind
  22999. * - BABYLON.VertexBuffer.UV2Kind
  23000. * - BABYLON.VertexBuffer.UV3Kind
  23001. * - BABYLON.VertexBuffer.UV4Kind
  23002. * - BABYLON.VertexBuffer.UV5Kind
  23003. * - BABYLON.VertexBuffer.UV6Kind
  23004. * - BABYLON.VertexBuffer.ColorKind
  23005. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23006. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23007. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23008. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23009. */
  23010. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  23011. if (!this._geometry) {
  23012. if (this._delayInfo) {
  23013. return this._delayInfo.indexOf(kind) !== -1;
  23014. }
  23015. return false;
  23016. }
  23017. return this._geometry.isVertexBufferUpdatable(kind);
  23018. };
  23019. /**
  23020. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23021. * Possible `kind` values :
  23022. * - BABYLON.VertexBuffer.PositionKind
  23023. * - BABYLON.VertexBuffer.UVKind
  23024. * - BABYLON.VertexBuffer.UV2Kind
  23025. * - BABYLON.VertexBuffer.UV3Kind
  23026. * - BABYLON.VertexBuffer.UV4Kind
  23027. * - BABYLON.VertexBuffer.UV5Kind
  23028. * - BABYLON.VertexBuffer.UV6Kind
  23029. * - BABYLON.VertexBuffer.ColorKind
  23030. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23031. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23032. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23033. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23034. */
  23035. Mesh.prototype.getVerticesDataKinds = function () {
  23036. if (!this._geometry) {
  23037. var result = new Array();
  23038. if (this._delayInfo) {
  23039. this._delayInfo.forEach(function (kind, index, array) {
  23040. result.push(kind);
  23041. });
  23042. }
  23043. return result;
  23044. }
  23045. return this._geometry.getVerticesDataKinds();
  23046. };
  23047. /**
  23048. * Returns a positive integer : the total number of indices in this mesh geometry.
  23049. * Returns zero if the mesh has no geometry.
  23050. */
  23051. Mesh.prototype.getTotalIndices = function () {
  23052. if (!this._geometry) {
  23053. return 0;
  23054. }
  23055. return this._geometry.getTotalIndices();
  23056. };
  23057. /**
  23058. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23059. * 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.
  23060. * Returns an empty array if the mesh has no geometry.
  23061. */
  23062. Mesh.prototype.getIndices = function (copyWhenShared) {
  23063. if (!this._geometry) {
  23064. return [];
  23065. }
  23066. return this._geometry.getIndices(copyWhenShared);
  23067. };
  23068. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23069. get: function () {
  23070. return this._masterMesh !== null && this._masterMesh !== undefined;
  23071. },
  23072. enumerable: true,
  23073. configurable: true
  23074. });
  23075. /**
  23076. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23077. */
  23078. Mesh.prototype.isReady = function () {
  23079. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23080. return false;
  23081. }
  23082. return _super.prototype.isReady.call(this);
  23083. };
  23084. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23085. /**
  23086. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23087. * This property is pertinent only for updatable parametric shapes.
  23088. */
  23089. get: function () {
  23090. return this._areNormalsFrozen;
  23091. },
  23092. enumerable: true,
  23093. configurable: true
  23094. });
  23095. /**
  23096. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23097. * It has no effect at all on other shapes.
  23098. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23099. * Returns the Mesh.
  23100. */
  23101. Mesh.prototype.freezeNormals = function () {
  23102. this._areNormalsFrozen = true;
  23103. return this;
  23104. };
  23105. /**
  23106. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23107. * It has no effect at all on other shapes.
  23108. * It reactivates the mesh normals computation if it was previously frozen.
  23109. * Returns the Mesh.
  23110. */
  23111. Mesh.prototype.unfreezeNormals = function () {
  23112. this._areNormalsFrozen = false;
  23113. return this;
  23114. };
  23115. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23116. /**
  23117. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23118. */
  23119. set: function (count) {
  23120. this._overridenInstanceCount = count;
  23121. },
  23122. enumerable: true,
  23123. configurable: true
  23124. });
  23125. // Methods
  23126. Mesh.prototype._preActivate = function () {
  23127. var sceneRenderId = this.getScene().getRenderId();
  23128. if (this._preActivateId === sceneRenderId) {
  23129. return this;
  23130. }
  23131. this._preActivateId = sceneRenderId;
  23132. this._visibleInstances = null;
  23133. return this;
  23134. };
  23135. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23136. if (this._visibleInstances) {
  23137. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23138. }
  23139. return this;
  23140. };
  23141. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23142. if (!this._visibleInstances) {
  23143. this._visibleInstances = {};
  23144. this._visibleInstances.defaultRenderId = renderId;
  23145. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23146. }
  23147. if (!this._visibleInstances[renderId]) {
  23148. this._visibleInstances[renderId] = new Array();
  23149. }
  23150. this._visibleInstances[renderId].push(instance);
  23151. return this;
  23152. };
  23153. /**
  23154. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23155. * This means the mesh underlying bounding box and sphere are recomputed.
  23156. * Returns the Mesh.
  23157. */
  23158. Mesh.prototype.refreshBoundingInfo = function () {
  23159. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23160. return this;
  23161. }
  23162. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23163. if (data) {
  23164. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23165. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23166. }
  23167. if (this.subMeshes) {
  23168. for (var index = 0; index < this.subMeshes.length; index++) {
  23169. this.subMeshes[index].refreshBoundingInfo();
  23170. }
  23171. }
  23172. this._updateBoundingInfo();
  23173. return this;
  23174. };
  23175. Mesh.prototype._createGlobalSubMesh = function (force) {
  23176. var totalVertices = this.getTotalVertices();
  23177. if (!totalVertices || !this.getIndices()) {
  23178. return null;
  23179. }
  23180. // Check if we need to recreate the submeshes
  23181. if (this.subMeshes && this.subMeshes.length > 0) {
  23182. var ib = this.getIndices();
  23183. if (!ib) {
  23184. return null;
  23185. }
  23186. var totalIndices = ib.length;
  23187. var needToRecreate = false;
  23188. if (force) {
  23189. needToRecreate = true;
  23190. }
  23191. else {
  23192. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23193. var submesh = _a[_i];
  23194. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23195. needToRecreate = true;
  23196. break;
  23197. }
  23198. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23199. needToRecreate = true;
  23200. break;
  23201. }
  23202. }
  23203. }
  23204. if (!needToRecreate) {
  23205. return this.subMeshes[0];
  23206. }
  23207. }
  23208. this.releaseSubMeshes();
  23209. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23210. };
  23211. Mesh.prototype.subdivide = function (count) {
  23212. if (count < 1) {
  23213. return;
  23214. }
  23215. var totalIndices = this.getTotalIndices();
  23216. var subdivisionSize = (totalIndices / count) | 0;
  23217. var offset = 0;
  23218. // Ensure that subdivisionSize is a multiple of 3
  23219. while (subdivisionSize % 3 !== 0) {
  23220. subdivisionSize++;
  23221. }
  23222. this.releaseSubMeshes();
  23223. for (var index = 0; index < count; index++) {
  23224. if (offset >= totalIndices) {
  23225. break;
  23226. }
  23227. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23228. offset += subdivisionSize;
  23229. }
  23230. this.synchronizeInstances();
  23231. };
  23232. /**
  23233. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23234. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23235. * The `data` are either a numeric array either a Float32Array.
  23236. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23237. * 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).
  23238. * Note that a new underlying VertexBuffer object is created each call.
  23239. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23240. *
  23241. * Possible `kind` values :
  23242. * - BABYLON.VertexBuffer.PositionKind
  23243. * - BABYLON.VertexBuffer.UVKind
  23244. * - BABYLON.VertexBuffer.UV2Kind
  23245. * - BABYLON.VertexBuffer.UV3Kind
  23246. * - BABYLON.VertexBuffer.UV4Kind
  23247. * - BABYLON.VertexBuffer.UV5Kind
  23248. * - BABYLON.VertexBuffer.UV6Kind
  23249. * - BABYLON.VertexBuffer.ColorKind
  23250. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23251. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23252. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23253. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23254. *
  23255. * Returns the Mesh.
  23256. */
  23257. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23258. if (updatable === void 0) { updatable = false; }
  23259. if (!this._geometry) {
  23260. var vertexData = new BABYLON.VertexData();
  23261. vertexData.set(data, kind);
  23262. var scene = this.getScene();
  23263. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23264. }
  23265. else {
  23266. this._geometry.setVerticesData(kind, data, updatable, stride);
  23267. }
  23268. return this;
  23269. };
  23270. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23271. if (updatable === void 0) { updatable = true; }
  23272. var vb = this.getVertexBuffer(kind);
  23273. if (!vb || vb.isUpdatable() === updatable) {
  23274. return;
  23275. }
  23276. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23277. };
  23278. /**
  23279. * Sets the mesh VertexBuffer.
  23280. * Returns the Mesh.
  23281. */
  23282. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23283. if (!this._geometry) {
  23284. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23285. }
  23286. this._geometry.setVerticesBuffer(buffer);
  23287. return this;
  23288. };
  23289. /**
  23290. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23291. * If the mesh has no geometry, it is simply returned as it is.
  23292. * The `data` are either a numeric array either a Float32Array.
  23293. * No new underlying VertexBuffer object is created.
  23294. * 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.
  23295. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23296. *
  23297. * Possible `kind` values :
  23298. * - BABYLON.VertexBuffer.PositionKind
  23299. * - BABYLON.VertexBuffer.UVKind
  23300. * - BABYLON.VertexBuffer.UV2Kind
  23301. * - BABYLON.VertexBuffer.UV3Kind
  23302. * - BABYLON.VertexBuffer.UV4Kind
  23303. * - BABYLON.VertexBuffer.UV5Kind
  23304. * - BABYLON.VertexBuffer.UV6Kind
  23305. * - BABYLON.VertexBuffer.ColorKind
  23306. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23307. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23308. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23309. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23310. *
  23311. * Returns the Mesh.
  23312. */
  23313. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23314. if (!this._geometry) {
  23315. return this;
  23316. }
  23317. if (!makeItUnique) {
  23318. this._geometry.updateVerticesData(kind, data, updateExtends);
  23319. }
  23320. else {
  23321. this.makeGeometryUnique();
  23322. this.updateVerticesData(kind, data, updateExtends, false);
  23323. }
  23324. return this;
  23325. };
  23326. /**
  23327. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23328. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23329. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23330. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23331. * Returns the Mesh.
  23332. */
  23333. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23334. if (computeNormals === void 0) { computeNormals = true; }
  23335. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23336. if (!positions) {
  23337. return this;
  23338. }
  23339. positionFunction(positions);
  23340. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23341. if (computeNormals) {
  23342. var indices = this.getIndices();
  23343. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23344. if (!normals) {
  23345. return this;
  23346. }
  23347. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23348. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23349. }
  23350. return this;
  23351. };
  23352. /**
  23353. * Creates a un-shared specific occurence of the geometry for the mesh.
  23354. * Returns the Mesh.
  23355. */
  23356. Mesh.prototype.makeGeometryUnique = function () {
  23357. if (!this._geometry) {
  23358. return this;
  23359. }
  23360. var oldGeometry = this._geometry;
  23361. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23362. oldGeometry.releaseForMesh(this, true);
  23363. geometry.applyToMesh(this);
  23364. return this;
  23365. };
  23366. /**
  23367. * Sets the mesh indices.
  23368. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23369. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23370. * This method creates a new index buffer each call.
  23371. * Returns the Mesh.
  23372. */
  23373. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23374. if (totalVertices === void 0) { totalVertices = null; }
  23375. if (updatable === void 0) { updatable = false; }
  23376. if (!this._geometry) {
  23377. var vertexData = new BABYLON.VertexData();
  23378. vertexData.indices = indices;
  23379. var scene = this.getScene();
  23380. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23381. }
  23382. else {
  23383. this._geometry.setIndices(indices, totalVertices, updatable);
  23384. }
  23385. return this;
  23386. };
  23387. /**
  23388. * Update the current index buffer
  23389. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23390. * Returns the Mesh.
  23391. */
  23392. Mesh.prototype.updateIndices = function (indices, offset) {
  23393. if (!this._geometry) {
  23394. return this;
  23395. }
  23396. this._geometry.updateIndices(indices, offset);
  23397. return this;
  23398. };
  23399. /**
  23400. * Invert the geometry to move from a right handed system to a left handed one.
  23401. * Returns the Mesh.
  23402. */
  23403. Mesh.prototype.toLeftHanded = function () {
  23404. if (!this._geometry) {
  23405. return this;
  23406. }
  23407. this._geometry.toLeftHanded();
  23408. return this;
  23409. };
  23410. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23411. if (!this._geometry) {
  23412. return this;
  23413. }
  23414. var engine = this.getScene().getEngine();
  23415. // Wireframe
  23416. var indexToBind;
  23417. if (this._unIndexed) {
  23418. indexToBind = null;
  23419. }
  23420. else {
  23421. switch (fillMode) {
  23422. case BABYLON.Material.PointFillMode:
  23423. indexToBind = null;
  23424. break;
  23425. case BABYLON.Material.WireFrameFillMode:
  23426. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23427. break;
  23428. default:
  23429. case BABYLON.Material.TriangleFillMode:
  23430. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23431. break;
  23432. }
  23433. }
  23434. // VBOs
  23435. this._geometry._bind(effect, indexToBind);
  23436. return this;
  23437. };
  23438. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23439. if (alternate === void 0) { alternate = false; }
  23440. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23441. return this;
  23442. }
  23443. this.onBeforeDrawObservable.notifyObservers(this);
  23444. var scene = this.getScene();
  23445. var engine = scene.getEngine();
  23446. // Draw order
  23447. switch (fillMode) {
  23448. case BABYLON.Material.PointFillMode:
  23449. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23450. break;
  23451. case BABYLON.Material.WireFrameFillMode:
  23452. if (this._unIndexed) {
  23453. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23454. }
  23455. else {
  23456. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23457. }
  23458. break;
  23459. default:
  23460. if (this._unIndexed) {
  23461. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23462. }
  23463. else {
  23464. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23465. }
  23466. }
  23467. if (scene._isAlternateRenderingEnabled && !alternate) {
  23468. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23469. if (!effect || !scene.activeCamera) {
  23470. return this;
  23471. }
  23472. scene._switchToAlternateCameraConfiguration(true);
  23473. this._effectiveMaterial.bindView(effect);
  23474. this._effectiveMaterial.bindViewProjection(effect);
  23475. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23476. this._draw(subMesh, fillMode, instancesCount, true);
  23477. engine.setViewport(scene.activeCamera.viewport);
  23478. scene._switchToAlternateCameraConfiguration(false);
  23479. this._effectiveMaterial.bindView(effect);
  23480. this._effectiveMaterial.bindViewProjection(effect);
  23481. }
  23482. return this;
  23483. };
  23484. /**
  23485. * Registers for this mesh a javascript function called just before the rendering process.
  23486. * This function is passed the current mesh.
  23487. * Return the Mesh.
  23488. */
  23489. Mesh.prototype.registerBeforeRender = function (func) {
  23490. this.onBeforeRenderObservable.add(func);
  23491. return this;
  23492. };
  23493. /**
  23494. * Disposes a previously registered javascript function called before the rendering.
  23495. * This function is passed the current mesh.
  23496. * Returns the Mesh.
  23497. */
  23498. Mesh.prototype.unregisterBeforeRender = function (func) {
  23499. this.onBeforeRenderObservable.removeCallback(func);
  23500. return this;
  23501. };
  23502. /**
  23503. * Registers for this mesh a javascript function called just after the rendering is complete.
  23504. * This function is passed the current mesh.
  23505. * Returns the Mesh.
  23506. */
  23507. Mesh.prototype.registerAfterRender = function (func) {
  23508. this.onAfterRenderObservable.add(func);
  23509. return this;
  23510. };
  23511. /**
  23512. * Disposes a previously registered javascript function called after the rendering.
  23513. * This function is passed the current mesh.
  23514. * Return the Mesh.
  23515. */
  23516. Mesh.prototype.unregisterAfterRender = function (func) {
  23517. this.onAfterRenderObservable.removeCallback(func);
  23518. return this;
  23519. };
  23520. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23521. var scene = this.getScene();
  23522. this._batchCache.mustReturn = false;
  23523. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23524. this._batchCache.visibleInstances[subMeshId] = null;
  23525. if (this._visibleInstances) {
  23526. var currentRenderId = scene.getRenderId();
  23527. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23528. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23529. var selfRenderId = this._renderId;
  23530. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23531. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23532. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23533. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23534. }
  23535. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23536. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23537. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23538. this._batchCache.mustReturn = true;
  23539. return this._batchCache;
  23540. }
  23541. if (currentRenderId !== selfRenderId) {
  23542. this._batchCache.renderSelf[subMeshId] = false;
  23543. }
  23544. }
  23545. this._renderIdForInstances[subMeshId] = currentRenderId;
  23546. }
  23547. return this._batchCache;
  23548. };
  23549. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23550. var visibleInstances = batch.visibleInstances[subMesh._id];
  23551. if (!visibleInstances) {
  23552. return this;
  23553. }
  23554. var matricesCount = visibleInstances.length + 1;
  23555. var bufferSize = matricesCount * 16 * 4;
  23556. var currentInstancesBufferSize = this._instancesBufferSize;
  23557. var instancesBuffer = this._instancesBuffer;
  23558. while (this._instancesBufferSize < bufferSize) {
  23559. this._instancesBufferSize *= 2;
  23560. }
  23561. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23562. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23563. }
  23564. var offset = 0;
  23565. var instancesCount = 0;
  23566. var world = this.getWorldMatrix();
  23567. if (batch.renderSelf[subMesh._id]) {
  23568. world.copyToArray(this._instancesData, offset);
  23569. offset += 16;
  23570. instancesCount++;
  23571. }
  23572. if (visibleInstances) {
  23573. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23574. var instance = visibleInstances[instanceIndex];
  23575. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23576. offset += 16;
  23577. instancesCount++;
  23578. }
  23579. }
  23580. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23581. if (instancesBuffer) {
  23582. instancesBuffer.dispose();
  23583. }
  23584. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23585. this._instancesBuffer = instancesBuffer;
  23586. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23587. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23588. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23589. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23590. }
  23591. else {
  23592. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23593. }
  23594. this._bind(subMesh, effect, fillMode);
  23595. this._draw(subMesh, fillMode, instancesCount);
  23596. engine.unbindInstanceAttributes();
  23597. return this;
  23598. };
  23599. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23600. var scene = this.getScene();
  23601. var engine = scene.getEngine();
  23602. if (hardwareInstancedRendering) {
  23603. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23604. }
  23605. else {
  23606. if (batch.renderSelf[subMesh._id]) {
  23607. // Draw
  23608. if (onBeforeDraw) {
  23609. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23610. }
  23611. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23612. }
  23613. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23614. if (visibleInstancesForSubMesh) {
  23615. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23616. var instance = visibleInstancesForSubMesh[instanceIndex];
  23617. // World
  23618. var world = instance.getWorldMatrix();
  23619. if (onBeforeDraw) {
  23620. onBeforeDraw(true, world, effectiveMaterial);
  23621. }
  23622. // Draw
  23623. this._draw(subMesh, fillMode);
  23624. }
  23625. }
  23626. }
  23627. return this;
  23628. };
  23629. /**
  23630. * Triggers the draw call for the mesh.
  23631. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23632. * Returns the Mesh.
  23633. */
  23634. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23635. this.checkOcclusionQuery();
  23636. if (this._isOccluded) {
  23637. return this;
  23638. }
  23639. var scene = this.getScene();
  23640. // Managing instances
  23641. var batch = this._getInstancesRenderList(subMesh._id);
  23642. if (batch.mustReturn) {
  23643. return this;
  23644. }
  23645. // Checking geometry state
  23646. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23647. return this;
  23648. }
  23649. this.onBeforeRenderObservable.notifyObservers(this);
  23650. var engine = scene.getEngine();
  23651. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23652. // Material
  23653. var material = subMesh.getMaterial();
  23654. if (!material) {
  23655. return this;
  23656. }
  23657. this._effectiveMaterial = material;
  23658. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23659. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23660. return this;
  23661. }
  23662. }
  23663. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23664. return this;
  23665. }
  23666. // Alpha mode
  23667. if (enableAlphaMode) {
  23668. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23669. }
  23670. // Outline - step 1
  23671. var savedDepthWrite = engine.getDepthWrite();
  23672. if (this.renderOutline) {
  23673. engine.setDepthWrite(false);
  23674. scene.getOutlineRenderer().render(subMesh, batch);
  23675. engine.setDepthWrite(savedDepthWrite);
  23676. }
  23677. var effect;
  23678. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23679. effect = subMesh.effect;
  23680. }
  23681. else {
  23682. effect = this._effectiveMaterial.getEffect();
  23683. }
  23684. if (!effect) {
  23685. return this;
  23686. }
  23687. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23688. if (this._effectiveMaterial.forceDepthWrite) {
  23689. engine.setDepthWrite(true);
  23690. }
  23691. // Bind
  23692. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23693. if (!hardwareInstancedRendering) {
  23694. this._bind(subMesh, effect, fillMode);
  23695. }
  23696. var world = this.getWorldMatrix();
  23697. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23698. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23699. }
  23700. else {
  23701. this._effectiveMaterial.bind(world, this);
  23702. }
  23703. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23704. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23705. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23706. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23707. }
  23708. // Draw
  23709. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23710. // Unbind
  23711. this._effectiveMaterial.unbind();
  23712. // Outline - step 2
  23713. if (this.renderOutline && savedDepthWrite) {
  23714. engine.setDepthWrite(true);
  23715. engine.setColorWrite(false);
  23716. scene.getOutlineRenderer().render(subMesh, batch);
  23717. engine.setColorWrite(true);
  23718. }
  23719. // Overlay
  23720. if (this.renderOverlay) {
  23721. var currentMode = engine.getAlphaMode();
  23722. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23723. scene.getOutlineRenderer().render(subMesh, batch, true);
  23724. engine.setAlphaMode(currentMode);
  23725. }
  23726. this.onAfterRenderObservable.notifyObservers(this);
  23727. return this;
  23728. };
  23729. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23730. if (isInstance) {
  23731. effectiveMaterial.bindOnlyWorldMatrix(world);
  23732. }
  23733. return this;
  23734. };
  23735. /**
  23736. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23737. */
  23738. Mesh.prototype.getEmittedParticleSystems = function () {
  23739. var results = new Array();
  23740. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23741. var particleSystem = this.getScene().particleSystems[index];
  23742. if (particleSystem.emitter === this) {
  23743. results.push(particleSystem);
  23744. }
  23745. }
  23746. return results;
  23747. };
  23748. /**
  23749. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23750. */
  23751. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23752. var results = new Array();
  23753. var descendants = this.getDescendants();
  23754. descendants.push(this);
  23755. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23756. var particleSystem = this.getScene().particleSystems[index];
  23757. var emitter = particleSystem.emitter;
  23758. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23759. results.push(particleSystem);
  23760. }
  23761. }
  23762. return results;
  23763. };
  23764. Mesh.prototype._checkDelayState = function () {
  23765. var scene = this.getScene();
  23766. if (this._geometry) {
  23767. this._geometry.load(scene);
  23768. }
  23769. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23770. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23771. this._queueLoad(this, scene);
  23772. }
  23773. return this;
  23774. };
  23775. Mesh.prototype._queueLoad = function (mesh, scene) {
  23776. var _this = this;
  23777. scene._addPendingData(mesh);
  23778. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23779. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23780. if (data instanceof ArrayBuffer) {
  23781. _this._delayLoadingFunction(data, _this);
  23782. }
  23783. else {
  23784. _this._delayLoadingFunction(JSON.parse(data), _this);
  23785. }
  23786. _this.instances.forEach(function (instance) {
  23787. instance._syncSubMeshes();
  23788. });
  23789. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23790. scene._removePendingData(_this);
  23791. }, function () { }, scene.database, getBinaryData);
  23792. return this;
  23793. };
  23794. /**
  23795. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23796. */
  23797. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23798. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23799. return false;
  23800. }
  23801. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23802. return false;
  23803. }
  23804. this._checkDelayState();
  23805. return true;
  23806. };
  23807. /**
  23808. * Sets the mesh material by the material or multiMaterial `id` property.
  23809. * The material `id` is a string identifying the material or the multiMaterial.
  23810. * This method returns the Mesh.
  23811. */
  23812. Mesh.prototype.setMaterialByID = function (id) {
  23813. var materials = this.getScene().materials;
  23814. var index;
  23815. for (index = materials.length - 1; index > -1; index--) {
  23816. if (materials[index].id === id) {
  23817. this.material = materials[index];
  23818. return this;
  23819. }
  23820. }
  23821. // Multi
  23822. var multiMaterials = this.getScene().multiMaterials;
  23823. for (index = multiMaterials.length - 1; index > -1; index--) {
  23824. if (multiMaterials[index].id === id) {
  23825. this.material = multiMaterials[index];
  23826. return this;
  23827. }
  23828. }
  23829. return this;
  23830. };
  23831. /**
  23832. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23833. */
  23834. Mesh.prototype.getAnimatables = function () {
  23835. var results = new Array();
  23836. if (this.material) {
  23837. results.push(this.material);
  23838. }
  23839. if (this.skeleton) {
  23840. results.push(this.skeleton);
  23841. }
  23842. return results;
  23843. };
  23844. /**
  23845. * Modifies the mesh geometry according to the passed transformation matrix.
  23846. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23847. * The mesh normals are modified accordingly the same transformation.
  23848. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23849. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23850. * Returns the Mesh.
  23851. */
  23852. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23853. // Position
  23854. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23855. return this;
  23856. }
  23857. var submeshes = this.subMeshes.splice(0);
  23858. this._resetPointsArrayCache();
  23859. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23860. var temp = new Array();
  23861. var index;
  23862. for (index = 0; index < data.length; index += 3) {
  23863. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23864. }
  23865. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23866. // Normals
  23867. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23868. return this;
  23869. }
  23870. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23871. temp = [];
  23872. for (index = 0; index < data.length; index += 3) {
  23873. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23874. }
  23875. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23876. // flip faces?
  23877. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23878. this.flipFaces();
  23879. }
  23880. // Restore submeshes
  23881. this.releaseSubMeshes();
  23882. this.subMeshes = submeshes;
  23883. return this;
  23884. };
  23885. /**
  23886. * Modifies the mesh geometry according to its own current World Matrix.
  23887. * The mesh World Matrix is then reset.
  23888. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23889. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23890. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23891. * Returns the Mesh.
  23892. */
  23893. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23894. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23895. this.scaling.copyFromFloats(1, 1, 1);
  23896. this.position.copyFromFloats(0, 0, 0);
  23897. this.rotation.copyFromFloats(0, 0, 0);
  23898. //only if quaternion is already set
  23899. if (this.rotationQuaternion) {
  23900. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23901. }
  23902. this._worldMatrix = BABYLON.Matrix.Identity();
  23903. return this;
  23904. };
  23905. Object.defineProperty(Mesh.prototype, "_positions", {
  23906. // Cache
  23907. get: function () {
  23908. if (this._geometry) {
  23909. return this._geometry._positions;
  23910. }
  23911. return null;
  23912. },
  23913. enumerable: true,
  23914. configurable: true
  23915. });
  23916. Mesh.prototype._resetPointsArrayCache = function () {
  23917. if (this._geometry) {
  23918. this._geometry._resetPointsArrayCache();
  23919. }
  23920. return this;
  23921. };
  23922. Mesh.prototype._generatePointsArray = function () {
  23923. if (this._geometry) {
  23924. return this._geometry._generatePointsArray();
  23925. }
  23926. return false;
  23927. };
  23928. /**
  23929. * Returns a new Mesh object generated from the current mesh properties.
  23930. * This method must not get confused with createInstance().
  23931. * The parameter `name` is a string, the name given to the new mesh.
  23932. * The optional parameter `newParent` can be any Node object (default `null`).
  23933. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23934. * 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.
  23935. */
  23936. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23937. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23938. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23939. };
  23940. /**
  23941. * Disposes the mesh.
  23942. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23943. */
  23944. Mesh.prototype.dispose = function (doNotRecurse) {
  23945. var _this = this;
  23946. this.morphTargetManager = null;
  23947. if (this._geometry) {
  23948. this._geometry.releaseForMesh(this, true);
  23949. }
  23950. // Sources
  23951. var meshes = this.getScene().meshes;
  23952. meshes.forEach(function (mesh) {
  23953. if (mesh._source && mesh._source === _this) {
  23954. mesh._source = null;
  23955. }
  23956. });
  23957. this._source = null;
  23958. // Instances
  23959. if (this._instancesBuffer) {
  23960. this._instancesBuffer.dispose();
  23961. this._instancesBuffer = null;
  23962. }
  23963. while (this.instances.length) {
  23964. this.instances[0].dispose();
  23965. }
  23966. // Highlight layers.
  23967. var highlightLayers = this.getScene().highlightLayers;
  23968. for (var i = 0; i < highlightLayers.length; i++) {
  23969. var highlightLayer = highlightLayers[i];
  23970. if (highlightLayer) {
  23971. highlightLayer.removeMesh(this);
  23972. highlightLayer.removeExcludedMesh(this);
  23973. }
  23974. }
  23975. _super.prototype.dispose.call(this, doNotRecurse);
  23976. };
  23977. /**
  23978. * Modifies the mesh geometry according to a displacement map.
  23979. * 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.
  23980. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23981. * This method returns nothing.
  23982. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23983. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23984. * 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.
  23985. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23986. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23987. *
  23988. * Returns the Mesh.
  23989. */
  23990. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23991. var _this = this;
  23992. var scene = this.getScene();
  23993. var onload = function (img) {
  23994. // Getting height map data
  23995. var canvas = document.createElement("canvas");
  23996. var context = canvas.getContext("2d");
  23997. var heightMapWidth = img.width;
  23998. var heightMapHeight = img.height;
  23999. canvas.width = heightMapWidth;
  24000. canvas.height = heightMapHeight;
  24001. context.drawImage(img, 0, 0);
  24002. // Create VertexData from map data
  24003. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24004. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24005. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24006. //execute success callback, if set
  24007. if (onSuccess) {
  24008. onSuccess(_this);
  24009. }
  24010. };
  24011. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24012. return this;
  24013. };
  24014. /**
  24015. * Modifies the mesh geometry according to a displacementMap buffer.
  24016. * 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.
  24017. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24018. * This method returns nothing.
  24019. * 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.
  24020. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24021. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24022. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24023. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24024. *
  24025. * Returns the Mesh.
  24026. */
  24027. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24028. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24029. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24030. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24031. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24032. return this;
  24033. }
  24034. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24035. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24036. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24037. var position = BABYLON.Vector3.Zero();
  24038. var normal = BABYLON.Vector3.Zero();
  24039. var uv = BABYLON.Vector2.Zero();
  24040. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24041. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24042. for (var index = 0; index < positions.length; index += 3) {
  24043. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24044. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24045. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24046. // Compute height
  24047. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24048. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24049. var pos = (u + v * heightMapWidth) * 4;
  24050. var r = buffer[pos] / 255.0;
  24051. var g = buffer[pos + 1] / 255.0;
  24052. var b = buffer[pos + 2] / 255.0;
  24053. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24054. normal.normalize();
  24055. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24056. position = position.add(normal);
  24057. position.toArray(positions, index);
  24058. }
  24059. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24060. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24061. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24062. return this;
  24063. };
  24064. /**
  24065. * Modify the mesh to get a flat shading rendering.
  24066. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24067. * This method returns the Mesh.
  24068. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24069. */
  24070. Mesh.prototype.convertToFlatShadedMesh = function () {
  24071. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24072. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24073. var kinds = this.getVerticesDataKinds();
  24074. var vbs = {};
  24075. var data = {};
  24076. var newdata = {};
  24077. var updatableNormals = false;
  24078. var kindIndex;
  24079. var kind;
  24080. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24081. kind = kinds[kindIndex];
  24082. var vertexBuffer = this.getVertexBuffer(kind);
  24083. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24084. updatableNormals = vertexBuffer.isUpdatable();
  24085. kinds.splice(kindIndex, 1);
  24086. kindIndex--;
  24087. continue;
  24088. }
  24089. vbs[kind] = vertexBuffer;
  24090. data[kind] = vbs[kind].getData();
  24091. newdata[kind] = [];
  24092. }
  24093. // Save previous submeshes
  24094. var previousSubmeshes = this.subMeshes.slice(0);
  24095. var indices = this.getIndices();
  24096. var totalIndices = this.getTotalIndices();
  24097. // Generating unique vertices per face
  24098. var index;
  24099. for (index = 0; index < totalIndices; index++) {
  24100. var vertexIndex = indices[index];
  24101. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24102. kind = kinds[kindIndex];
  24103. var stride = vbs[kind].getStrideSize();
  24104. for (var offset = 0; offset < stride; offset++) {
  24105. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24106. }
  24107. }
  24108. }
  24109. // Updating faces & normal
  24110. var normals = [];
  24111. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24112. for (index = 0; index < totalIndices; index += 3) {
  24113. indices[index] = index;
  24114. indices[index + 1] = index + 1;
  24115. indices[index + 2] = index + 2;
  24116. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24117. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24118. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24119. var p1p2 = p1.subtract(p2);
  24120. var p3p2 = p3.subtract(p2);
  24121. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24122. // Store same normals for every vertex
  24123. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24124. normals.push(normal.x);
  24125. normals.push(normal.y);
  24126. normals.push(normal.z);
  24127. }
  24128. }
  24129. this.setIndices(indices);
  24130. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24131. // Updating vertex buffers
  24132. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24133. kind = kinds[kindIndex];
  24134. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24135. }
  24136. // Updating submeshes
  24137. this.releaseSubMeshes();
  24138. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24139. var previousOne = previousSubmeshes[submeshIndex];
  24140. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24141. }
  24142. this.synchronizeInstances();
  24143. return this;
  24144. };
  24145. /**
  24146. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24147. * In other words, more vertices, no more indices and a single bigger VBO.
  24148. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24149. * Returns the Mesh.
  24150. */
  24151. Mesh.prototype.convertToUnIndexedMesh = function () {
  24152. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24153. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24154. var kinds = this.getVerticesDataKinds();
  24155. var vbs = {};
  24156. var data = {};
  24157. var newdata = {};
  24158. var kindIndex;
  24159. var kind;
  24160. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24161. kind = kinds[kindIndex];
  24162. var vertexBuffer = this.getVertexBuffer(kind);
  24163. vbs[kind] = vertexBuffer;
  24164. data[kind] = vbs[kind].getData();
  24165. newdata[kind] = [];
  24166. }
  24167. // Save previous submeshes
  24168. var previousSubmeshes = this.subMeshes.slice(0);
  24169. var indices = this.getIndices();
  24170. var totalIndices = this.getTotalIndices();
  24171. // Generating unique vertices per face
  24172. var index;
  24173. for (index = 0; index < totalIndices; index++) {
  24174. var vertexIndex = indices[index];
  24175. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24176. kind = kinds[kindIndex];
  24177. var stride = vbs[kind].getStrideSize();
  24178. for (var offset = 0; offset < stride; offset++) {
  24179. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24180. }
  24181. }
  24182. }
  24183. // Updating indices
  24184. for (index = 0; index < totalIndices; index += 3) {
  24185. indices[index] = index;
  24186. indices[index + 1] = index + 1;
  24187. indices[index + 2] = index + 2;
  24188. }
  24189. this.setIndices(indices);
  24190. // Updating vertex buffers
  24191. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24192. kind = kinds[kindIndex];
  24193. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24194. }
  24195. // Updating submeshes
  24196. this.releaseSubMeshes();
  24197. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24198. var previousOne = previousSubmeshes[submeshIndex];
  24199. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24200. }
  24201. this._unIndexed = true;
  24202. this.synchronizeInstances();
  24203. return this;
  24204. };
  24205. /**
  24206. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24207. * This method returns the Mesh.
  24208. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24209. */
  24210. Mesh.prototype.flipFaces = function (flipNormals) {
  24211. if (flipNormals === void 0) { flipNormals = false; }
  24212. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24213. var i;
  24214. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24215. for (i = 0; i < vertex_data.normals.length; i++) {
  24216. vertex_data.normals[i] *= -1;
  24217. }
  24218. }
  24219. if (vertex_data.indices) {
  24220. var temp;
  24221. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24222. // reassign indices
  24223. temp = vertex_data.indices[i + 1];
  24224. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24225. vertex_data.indices[i + 2] = temp;
  24226. }
  24227. }
  24228. vertex_data.applyToMesh(this);
  24229. return this;
  24230. };
  24231. // Instances
  24232. /**
  24233. * Creates a new InstancedMesh object from the mesh model.
  24234. * An instance shares the same properties and the same material than its model.
  24235. * Only these properties of each instance can then be set individually :
  24236. * - position
  24237. * - rotation
  24238. * - rotationQuaternion
  24239. * - setPivotMatrix
  24240. * - scaling
  24241. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24242. * Warning : this method is not supported for Line mesh and LineSystem
  24243. */
  24244. Mesh.prototype.createInstance = function (name) {
  24245. return new BABYLON.InstancedMesh(name, this);
  24246. };
  24247. /**
  24248. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24249. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24250. * This method returns the Mesh.
  24251. */
  24252. Mesh.prototype.synchronizeInstances = function () {
  24253. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24254. var instance = this.instances[instanceIndex];
  24255. instance._syncSubMeshes();
  24256. }
  24257. return this;
  24258. };
  24259. /**
  24260. * Simplify the mesh according to the given array of settings.
  24261. * Function will return immediately and will simplify async. It returns the Mesh.
  24262. * @param settings a collection of simplification settings.
  24263. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24264. * @param type the type of simplification to run.
  24265. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24266. */
  24267. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24268. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24269. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24270. this.getScene().simplificationQueue.addTask({
  24271. settings: settings,
  24272. parallelProcessing: parallelProcessing,
  24273. mesh: this,
  24274. simplificationType: simplificationType,
  24275. successCallback: successCallback
  24276. });
  24277. return this;
  24278. };
  24279. /**
  24280. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24281. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24282. * This should be used together with the simplification to avoid disappearing triangles.
  24283. * Returns the Mesh.
  24284. * @param successCallback an optional success callback to be called after the optimization finished.
  24285. */
  24286. Mesh.prototype.optimizeIndices = function (successCallback) {
  24287. var _this = this;
  24288. var indices = this.getIndices();
  24289. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24290. if (!positions || !indices) {
  24291. return this;
  24292. }
  24293. var vectorPositions = new Array();
  24294. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24295. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24296. }
  24297. var dupes = new Array();
  24298. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24299. var realPos = vectorPositions.length - 1 - iteration;
  24300. var testedPosition = vectorPositions[realPos];
  24301. for (var j = 0; j < realPos; ++j) {
  24302. var againstPosition = vectorPositions[j];
  24303. if (testedPosition.equals(againstPosition)) {
  24304. dupes[realPos] = j;
  24305. break;
  24306. }
  24307. }
  24308. }, function () {
  24309. for (var i = 0; i < indices.length; ++i) {
  24310. indices[i] = dupes[indices[i]] || indices[i];
  24311. }
  24312. //indices are now reordered
  24313. var originalSubMeshes = _this.subMeshes.slice(0);
  24314. _this.setIndices(indices);
  24315. _this.subMeshes = originalSubMeshes;
  24316. if (successCallback) {
  24317. successCallback(_this);
  24318. }
  24319. });
  24320. return this;
  24321. };
  24322. Mesh.prototype.serialize = function (serializationObject) {
  24323. serializationObject.name = this.name;
  24324. serializationObject.id = this.id;
  24325. serializationObject.type = this.getClassName();
  24326. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24327. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24328. }
  24329. serializationObject.position = this.position.asArray();
  24330. if (this.rotationQuaternion) {
  24331. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24332. }
  24333. else if (this.rotation) {
  24334. serializationObject.rotation = this.rotation.asArray();
  24335. }
  24336. serializationObject.scaling = this.scaling.asArray();
  24337. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24338. serializationObject.isEnabled = this.isEnabled();
  24339. serializationObject.isVisible = this.isVisible;
  24340. serializationObject.infiniteDistance = this.infiniteDistance;
  24341. serializationObject.pickable = this.isPickable;
  24342. serializationObject.receiveShadows = this.receiveShadows;
  24343. serializationObject.billboardMode = this.billboardMode;
  24344. serializationObject.visibility = this.visibility;
  24345. serializationObject.checkCollisions = this.checkCollisions;
  24346. serializationObject.isBlocker = this.isBlocker;
  24347. // Parent
  24348. if (this.parent) {
  24349. serializationObject.parentId = this.parent.id;
  24350. }
  24351. // Geometry
  24352. var geometry = this._geometry;
  24353. if (geometry) {
  24354. var geometryId = geometry.id;
  24355. serializationObject.geometryId = geometryId;
  24356. // SubMeshes
  24357. serializationObject.subMeshes = [];
  24358. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24359. var subMesh = this.subMeshes[subIndex];
  24360. serializationObject.subMeshes.push({
  24361. materialIndex: subMesh.materialIndex,
  24362. verticesStart: subMesh.verticesStart,
  24363. verticesCount: subMesh.verticesCount,
  24364. indexStart: subMesh.indexStart,
  24365. indexCount: subMesh.indexCount
  24366. });
  24367. }
  24368. }
  24369. // Material
  24370. if (this.material) {
  24371. serializationObject.materialId = this.material.id;
  24372. }
  24373. else {
  24374. this.material = null;
  24375. }
  24376. // Morph targets
  24377. if (this.morphTargetManager) {
  24378. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24379. }
  24380. // Skeleton
  24381. if (this.skeleton) {
  24382. serializationObject.skeletonId = this.skeleton.id;
  24383. }
  24384. // Physics
  24385. //TODO implement correct serialization for physics impostors.
  24386. var impostor = this.getPhysicsImpostor();
  24387. if (impostor) {
  24388. serializationObject.physicsMass = impostor.getParam("mass");
  24389. serializationObject.physicsFriction = impostor.getParam("friction");
  24390. serializationObject.physicsRestitution = impostor.getParam("mass");
  24391. serializationObject.physicsImpostor = impostor.type;
  24392. }
  24393. // Metadata
  24394. if (this.metadata) {
  24395. serializationObject.metadata = this.metadata;
  24396. }
  24397. // Instances
  24398. serializationObject.instances = [];
  24399. for (var index = 0; index < this.instances.length; index++) {
  24400. var instance = this.instances[index];
  24401. var serializationInstance = {
  24402. name: instance.name,
  24403. position: instance.position.asArray(),
  24404. scaling: instance.scaling.asArray()
  24405. };
  24406. if (instance.rotationQuaternion) {
  24407. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24408. }
  24409. else if (instance.rotation) {
  24410. serializationInstance.rotation = instance.rotation.asArray();
  24411. }
  24412. serializationObject.instances.push(serializationInstance);
  24413. // Animations
  24414. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24415. serializationInstance.ranges = instance.serializeAnimationRanges();
  24416. }
  24417. //
  24418. // Animations
  24419. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24420. serializationObject.ranges = this.serializeAnimationRanges();
  24421. // Layer mask
  24422. serializationObject.layerMask = this.layerMask;
  24423. // Alpha
  24424. serializationObject.alphaIndex = this.alphaIndex;
  24425. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24426. // Overlay
  24427. serializationObject.overlayAlpha = this.overlayAlpha;
  24428. serializationObject.overlayColor = this.overlayColor.asArray();
  24429. serializationObject.renderOverlay = this.renderOverlay;
  24430. // Fog
  24431. serializationObject.applyFog = this.applyFog;
  24432. // Action Manager
  24433. if (this.actionManager) {
  24434. serializationObject.actions = this.actionManager.serialize(this.name);
  24435. }
  24436. };
  24437. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24438. if (!this.geometry) {
  24439. return;
  24440. }
  24441. this._markSubMeshesAsAttributesDirty();
  24442. var morphTargetManager = this._morphTargetManager;
  24443. if (morphTargetManager && morphTargetManager.vertexCount) {
  24444. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24445. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24446. this.morphTargetManager = null;
  24447. return;
  24448. }
  24449. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24450. var morphTarget = morphTargetManager.getActiveTarget(index);
  24451. var positions = morphTarget.getPositions();
  24452. if (!positions) {
  24453. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24454. return;
  24455. }
  24456. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24457. var normals = morphTarget.getNormals();
  24458. if (normals) {
  24459. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24460. }
  24461. var tangents = morphTarget.getTangents();
  24462. if (tangents) {
  24463. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24464. }
  24465. }
  24466. }
  24467. else {
  24468. var index = 0;
  24469. // Positions
  24470. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24471. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24472. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24473. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24474. }
  24475. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24476. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24477. }
  24478. index++;
  24479. }
  24480. }
  24481. };
  24482. // Statics
  24483. /**
  24484. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24485. * The parameter `parsedMesh` is the mesh to be copied.
  24486. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24487. */
  24488. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24489. var mesh;
  24490. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24491. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24492. }
  24493. else {
  24494. mesh = new Mesh(parsedMesh.name, scene);
  24495. }
  24496. mesh.id = parsedMesh.id;
  24497. if (BABYLON.Tags) {
  24498. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24499. }
  24500. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24501. if (parsedMesh.metadata !== undefined) {
  24502. mesh.metadata = parsedMesh.metadata;
  24503. }
  24504. if (parsedMesh.rotationQuaternion) {
  24505. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24506. }
  24507. else if (parsedMesh.rotation) {
  24508. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24509. }
  24510. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24511. if (parsedMesh.localMatrix) {
  24512. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24513. }
  24514. else if (parsedMesh.pivotMatrix) {
  24515. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24516. }
  24517. mesh.setEnabled(parsedMesh.isEnabled);
  24518. mesh.isVisible = parsedMesh.isVisible;
  24519. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24520. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24521. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24522. if (parsedMesh.applyFog !== undefined) {
  24523. mesh.applyFog = parsedMesh.applyFog;
  24524. }
  24525. if (parsedMesh.pickable !== undefined) {
  24526. mesh.isPickable = parsedMesh.pickable;
  24527. }
  24528. if (parsedMesh.alphaIndex !== undefined) {
  24529. mesh.alphaIndex = parsedMesh.alphaIndex;
  24530. }
  24531. mesh.receiveShadows = parsedMesh.receiveShadows;
  24532. mesh.billboardMode = parsedMesh.billboardMode;
  24533. if (parsedMesh.visibility !== undefined) {
  24534. mesh.visibility = parsedMesh.visibility;
  24535. }
  24536. mesh.checkCollisions = parsedMesh.checkCollisions;
  24537. if (parsedMesh.isBlocker !== undefined) {
  24538. mesh.isBlocker = parsedMesh.isBlocker;
  24539. }
  24540. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24541. // freezeWorldMatrix
  24542. if (parsedMesh.freezeWorldMatrix) {
  24543. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24544. }
  24545. // Parent
  24546. if (parsedMesh.parentId) {
  24547. mesh._waitingParentId = parsedMesh.parentId;
  24548. }
  24549. // Actions
  24550. if (parsedMesh.actions !== undefined) {
  24551. mesh._waitingActions = parsedMesh.actions;
  24552. }
  24553. // Overlay
  24554. if (parsedMesh.overlayAlpha !== undefined) {
  24555. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24556. }
  24557. if (parsedMesh.overlayColor !== undefined) {
  24558. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24559. }
  24560. if (parsedMesh.renderOverlay !== undefined) {
  24561. mesh.renderOverlay = parsedMesh.renderOverlay;
  24562. }
  24563. // Geometry
  24564. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24565. if (parsedMesh.delayLoadingFile) {
  24566. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24567. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24568. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24569. if (parsedMesh._binaryInfo) {
  24570. mesh._binaryInfo = parsedMesh._binaryInfo;
  24571. }
  24572. mesh._delayInfo = [];
  24573. if (parsedMesh.hasUVs) {
  24574. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24575. }
  24576. if (parsedMesh.hasUVs2) {
  24577. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24578. }
  24579. if (parsedMesh.hasUVs3) {
  24580. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24581. }
  24582. if (parsedMesh.hasUVs4) {
  24583. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24584. }
  24585. if (parsedMesh.hasUVs5) {
  24586. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24587. }
  24588. if (parsedMesh.hasUVs6) {
  24589. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24590. }
  24591. if (parsedMesh.hasColors) {
  24592. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24593. }
  24594. if (parsedMesh.hasMatricesIndices) {
  24595. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24596. }
  24597. if (parsedMesh.hasMatricesWeights) {
  24598. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24599. }
  24600. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24601. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24602. mesh._checkDelayState();
  24603. }
  24604. }
  24605. else {
  24606. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24607. }
  24608. // Material
  24609. if (parsedMesh.materialId) {
  24610. mesh.setMaterialByID(parsedMesh.materialId);
  24611. }
  24612. else {
  24613. mesh.material = null;
  24614. }
  24615. // Morph targets
  24616. if (parsedMesh.morphTargetManagerId > -1) {
  24617. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24618. }
  24619. // Skeleton
  24620. if (parsedMesh.skeletonId > -1) {
  24621. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24622. if (parsedMesh.numBoneInfluencers) {
  24623. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24624. }
  24625. }
  24626. // Animations
  24627. if (parsedMesh.animations) {
  24628. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24629. var parsedAnimation = parsedMesh.animations[animationIndex];
  24630. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24631. }
  24632. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24633. }
  24634. if (parsedMesh.autoAnimate) {
  24635. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24636. }
  24637. // Layer Mask
  24638. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24639. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24640. }
  24641. else {
  24642. mesh.layerMask = 0x0FFFFFFF;
  24643. }
  24644. // Physics
  24645. if (parsedMesh.physicsImpostor) {
  24646. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24647. mass: parsedMesh.physicsMass,
  24648. friction: parsedMesh.physicsFriction,
  24649. restitution: parsedMesh.physicsRestitution
  24650. }, scene);
  24651. }
  24652. // Instances
  24653. if (parsedMesh.instances) {
  24654. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24655. var parsedInstance = parsedMesh.instances[index];
  24656. var instance = mesh.createInstance(parsedInstance.name);
  24657. if (BABYLON.Tags) {
  24658. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24659. }
  24660. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24661. if (parsedInstance.parentId) {
  24662. instance._waitingParentId = parsedInstance.parentId;
  24663. }
  24664. if (parsedInstance.rotationQuaternion) {
  24665. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24666. }
  24667. else if (parsedInstance.rotation) {
  24668. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24669. }
  24670. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24671. instance.checkCollisions = mesh.checkCollisions;
  24672. if (parsedMesh.animations) {
  24673. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24674. parsedAnimation = parsedMesh.animations[animationIndex];
  24675. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24676. }
  24677. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24678. }
  24679. }
  24680. }
  24681. return mesh;
  24682. };
  24683. /**
  24684. * Creates a ribbon mesh.
  24685. * Please consider using the same method from the MeshBuilder class instead.
  24686. * 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.
  24687. *
  24688. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24689. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24690. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24691. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24692. * 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.
  24693. * 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.
  24694. * 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
  24695. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24696. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24698. */
  24699. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24700. if (closeArray === void 0) { closeArray = false; }
  24701. if (updatable === void 0) { updatable = false; }
  24702. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24703. pathArray: pathArray,
  24704. closeArray: closeArray,
  24705. closePath: closePath,
  24706. offset: offset,
  24707. updatable: updatable,
  24708. sideOrientation: sideOrientation,
  24709. instance: instance
  24710. }, scene);
  24711. };
  24712. /**
  24713. * Creates a plane polygonal mesh. By default, this is a disc.
  24714. * Please consider using the same method from the MeshBuilder class instead.
  24715. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24716. * 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.
  24717. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24718. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24720. */
  24721. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24722. if (scene === void 0) { scene = null; }
  24723. var options = {
  24724. radius: radius,
  24725. tessellation: tessellation,
  24726. sideOrientation: sideOrientation,
  24727. updatable: updatable
  24728. };
  24729. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24730. };
  24731. /**
  24732. * Creates a box mesh.
  24733. * Please consider using the same method from the MeshBuilder class instead.
  24734. * The parameter `size` sets the size (float) of each box side (default 1).
  24735. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24736. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24737. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24738. */
  24739. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24740. if (scene === void 0) { scene = null; }
  24741. var options = {
  24742. size: size,
  24743. sideOrientation: sideOrientation,
  24744. updatable: updatable
  24745. };
  24746. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24747. };
  24748. /**
  24749. * Creates a sphere mesh.
  24750. * Please consider using the same method from the MeshBuilder class instead.
  24751. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24752. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24753. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24754. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24755. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24756. */
  24757. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24758. var options = {
  24759. segments: segments,
  24760. diameterX: diameter,
  24761. diameterY: diameter,
  24762. diameterZ: diameter,
  24763. sideOrientation: sideOrientation,
  24764. updatable: updatable
  24765. };
  24766. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24767. };
  24768. /**
  24769. * Creates a cylinder or a cone mesh.
  24770. * Please consider using the same method from the MeshBuilder class instead.
  24771. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24772. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24773. * 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.
  24774. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24775. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24777. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24778. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24779. */
  24780. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24781. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24782. if (scene !== undefined) {
  24783. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24784. updatable = scene;
  24785. }
  24786. scene = subdivisions;
  24787. subdivisions = 1;
  24788. }
  24789. var options = {
  24790. height: height,
  24791. diameterTop: diameterTop,
  24792. diameterBottom: diameterBottom,
  24793. tessellation: tessellation,
  24794. subdivisions: subdivisions,
  24795. sideOrientation: sideOrientation,
  24796. updatable: updatable
  24797. };
  24798. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24799. };
  24800. // Torus (Code from SharpDX.org)
  24801. /**
  24802. * Creates a torus mesh.
  24803. * Please consider using the same method from the MeshBuilder class instead.
  24804. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24805. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24806. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24810. */
  24811. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24812. var options = {
  24813. diameter: diameter,
  24814. thickness: thickness,
  24815. tessellation: tessellation,
  24816. sideOrientation: sideOrientation,
  24817. updatable: updatable
  24818. };
  24819. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24820. };
  24821. /**
  24822. * Creates a torus knot mesh.
  24823. * Please consider using the same method from the MeshBuilder class instead.
  24824. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24825. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24826. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24827. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24828. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24831. */
  24832. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24833. var options = {
  24834. radius: radius,
  24835. tube: tube,
  24836. radialSegments: radialSegments,
  24837. tubularSegments: tubularSegments,
  24838. p: p,
  24839. q: q,
  24840. sideOrientation: sideOrientation,
  24841. updatable: updatable
  24842. };
  24843. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24844. };
  24845. /**
  24846. * Creates a line mesh.
  24847. * Please consider using the same method from the MeshBuilder class instead.
  24848. * 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.
  24849. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24850. * The parameter `points` is an array successive Vector3.
  24851. * 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
  24852. * When updating an instance, remember that only point positions can change, not the number of points.
  24853. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24854. */
  24855. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24856. if (scene === void 0) { scene = null; }
  24857. if (updatable === void 0) { updatable = false; }
  24858. if (instance === void 0) { instance = null; }
  24859. var options = {
  24860. points: points,
  24861. updatable: updatable,
  24862. instance: instance
  24863. };
  24864. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24865. };
  24866. /**
  24867. * Creates a dashed line mesh.
  24868. * Please consider using the same method from the MeshBuilder class instead.
  24869. * 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.
  24870. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24871. * The parameter `points` is an array successive Vector3.
  24872. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24873. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24874. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24875. * 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
  24876. * When updating an instance, remember that only point positions can change, not the number of points.
  24877. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24878. */
  24879. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24880. if (scene === void 0) { scene = null; }
  24881. var options = {
  24882. points: points,
  24883. dashSize: dashSize,
  24884. gapSize: gapSize,
  24885. dashNb: dashNb,
  24886. updatable: updatable,
  24887. instance: instance
  24888. };
  24889. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24890. };
  24891. /**
  24892. * Creates a polygon mesh.
  24893. * Please consider using the same method from the MeshBuilder class instead.
  24894. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24895. * 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.
  24896. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24898. * Remember you can only change the shape positions, not their number when updating a polygon.
  24899. */
  24900. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24901. var options = {
  24902. shape: shape,
  24903. holes: holes,
  24904. updatable: updatable,
  24905. sideOrientation: sideOrientation
  24906. };
  24907. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24908. };
  24909. /**
  24910. * Creates an extruded polygon mesh, with depth in the Y direction.
  24911. * Please consider using the same method from the MeshBuilder class instead.
  24912. */
  24913. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24914. var options = {
  24915. shape: shape,
  24916. holes: holes,
  24917. depth: depth,
  24918. updatable: updatable,
  24919. sideOrientation: sideOrientation
  24920. };
  24921. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24922. };
  24923. /**
  24924. * Creates an extruded shape mesh.
  24925. * 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.
  24926. * Please consider using the same method from the MeshBuilder class instead.
  24927. *
  24928. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24929. * 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
  24930. * extruded along the Z axis.
  24931. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24932. * 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.
  24933. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24934. * 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
  24935. * 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
  24936. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24937. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24938. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24939. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24940. */
  24941. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24942. if (scene === void 0) { scene = null; }
  24943. var options = {
  24944. shape: shape,
  24945. path: path,
  24946. scale: scale,
  24947. rotation: rotation,
  24948. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24949. sideOrientation: sideOrientation,
  24950. instance: instance,
  24951. updatable: updatable
  24952. };
  24953. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24954. };
  24955. /**
  24956. * Creates an custom extruded shape mesh.
  24957. * 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.
  24958. * Please consider using the same method from the MeshBuilder class instead.
  24959. *
  24960. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24961. * 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
  24962. * extruded along the Z axis.
  24963. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24964. * 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
  24965. * and the distance of this point from the begining of the path :
  24966. * ```javascript
  24967. * var rotationFunction = function(i, distance) {
  24968. * // do things
  24969. * return rotationValue; }
  24970. * ```
  24971. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24972. * 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
  24973. * and the distance of this point from the begining of the path :
  24974. * ```javascript
  24975. * var scaleFunction = function(i, distance) {
  24976. * // do things
  24977. * return scaleValue;}
  24978. * ```
  24979. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24980. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24981. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24982. * 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
  24983. * 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
  24984. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24985. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24986. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24988. */
  24989. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24990. var options = {
  24991. shape: shape,
  24992. path: path,
  24993. scaleFunction: scaleFunction,
  24994. rotationFunction: rotationFunction,
  24995. ribbonCloseArray: ribbonCloseArray,
  24996. ribbonClosePath: ribbonClosePath,
  24997. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24998. sideOrientation: sideOrientation,
  24999. instance: instance,
  25000. updatable: updatable
  25001. };
  25002. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25003. };
  25004. /**
  25005. * Creates lathe mesh.
  25006. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25007. * Please consider using the same method from the MeshBuilder class instead.
  25008. * 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
  25009. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25010. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25011. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25013. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25014. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25015. */
  25016. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25017. var options = {
  25018. shape: shape,
  25019. radius: radius,
  25020. tessellation: tessellation,
  25021. sideOrientation: sideOrientation,
  25022. updatable: updatable
  25023. };
  25024. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25025. };
  25026. /**
  25027. * Creates a plane mesh.
  25028. * Please consider using the same method from the MeshBuilder class instead.
  25029. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25030. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25031. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25033. */
  25034. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25035. var options = {
  25036. size: size,
  25037. width: size,
  25038. height: size,
  25039. sideOrientation: sideOrientation,
  25040. updatable: updatable
  25041. };
  25042. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25043. };
  25044. /**
  25045. * Creates a ground mesh.
  25046. * Please consider using the same method from the MeshBuilder class instead.
  25047. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25048. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25050. */
  25051. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25052. var options = {
  25053. width: width,
  25054. height: height,
  25055. subdivisions: subdivisions,
  25056. updatable: updatable
  25057. };
  25058. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25059. };
  25060. /**
  25061. * Creates a tiled ground mesh.
  25062. * Please consider using the same method from the MeshBuilder class instead.
  25063. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25064. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25065. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25066. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25067. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25068. * numbers of subdivisions on the ground width and height of each tile.
  25069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25070. */
  25071. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25072. var options = {
  25073. xmin: xmin,
  25074. zmin: zmin,
  25075. xmax: xmax,
  25076. zmax: zmax,
  25077. subdivisions: subdivisions,
  25078. precision: precision,
  25079. updatable: updatable
  25080. };
  25081. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25082. };
  25083. /**
  25084. * Creates a ground mesh from a height map.
  25085. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25086. * Please consider using the same method from the MeshBuilder class instead.
  25087. * The parameter `url` sets the URL of the height map image resource.
  25088. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25089. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25090. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25091. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25092. * 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).
  25093. * This function is passed the newly built mesh :
  25094. * ```javascript
  25095. * function(mesh) { // do things
  25096. * return; }
  25097. * ```
  25098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25099. */
  25100. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25101. var options = {
  25102. width: width,
  25103. height: height,
  25104. subdivisions: subdivisions,
  25105. minHeight: minHeight,
  25106. maxHeight: maxHeight,
  25107. updatable: updatable,
  25108. onReady: onReady
  25109. };
  25110. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25111. };
  25112. /**
  25113. * Creates a tube mesh.
  25114. * 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.
  25115. * Please consider using the same method from the MeshBuilder class instead.
  25116. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25117. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25118. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25119. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25120. * 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.
  25121. * It must return a radius value (positive float) :
  25122. * ```javascript
  25123. * var radiusFunction = function(i, distance) {
  25124. * // do things
  25125. * return radius; }
  25126. * ```
  25127. * 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
  25128. * 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
  25129. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25130. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25131. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25132. */
  25133. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25134. var options = {
  25135. path: path,
  25136. radius: radius,
  25137. tessellation: tessellation,
  25138. radiusFunction: radiusFunction,
  25139. arc: 1,
  25140. cap: cap,
  25141. updatable: updatable,
  25142. sideOrientation: sideOrientation,
  25143. instance: instance
  25144. };
  25145. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25146. };
  25147. /**
  25148. * Creates a polyhedron mesh.
  25149. * Please consider using the same method from the MeshBuilder class instead.
  25150. * 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
  25151. * to choose the wanted type.
  25152. * The parameter `size` (positive float, default 1) sets the polygon size.
  25153. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25154. * 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`.
  25155. * 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
  25156. * 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)`).
  25157. * 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
  25158. * 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.
  25159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25162. */
  25163. Mesh.CreatePolyhedron = function (name, options, scene) {
  25164. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25165. };
  25166. /**
  25167. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25168. * Please consider using the same method from the MeshBuilder class instead.
  25169. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25170. * 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`).
  25171. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25172. * 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.
  25173. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25174. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25176. */
  25177. Mesh.CreateIcoSphere = function (name, options, scene) {
  25178. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25179. };
  25180. /**
  25181. * Creates a decal mesh.
  25182. * Please consider using the same method from the MeshBuilder class instead.
  25183. * 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.
  25184. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25185. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25186. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25187. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25188. */
  25189. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25190. var options = {
  25191. position: position,
  25192. normal: normal,
  25193. size: size,
  25194. angle: angle
  25195. };
  25196. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25197. };
  25198. // Skeletons
  25199. /**
  25200. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25201. */
  25202. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25203. if (!this._sourcePositions) {
  25204. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25205. if (!source) {
  25206. return this._sourcePositions;
  25207. }
  25208. this._sourcePositions = new Float32Array(source);
  25209. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25210. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25211. }
  25212. }
  25213. return this._sourcePositions;
  25214. };
  25215. /**
  25216. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25217. */
  25218. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25219. if (!this._sourceNormals) {
  25220. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25221. if (!source) {
  25222. return this._sourceNormals;
  25223. }
  25224. this._sourceNormals = new Float32Array(source);
  25225. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25226. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25227. }
  25228. }
  25229. return this._sourceNormals;
  25230. };
  25231. /**
  25232. * Updates the vertex buffer by applying transformation from the bones.
  25233. * Returns the Mesh.
  25234. *
  25235. * @param {skeleton} skeleton to apply
  25236. */
  25237. Mesh.prototype.applySkeleton = function (skeleton) {
  25238. if (!this.geometry) {
  25239. return this;
  25240. }
  25241. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25242. return this;
  25243. }
  25244. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25245. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25246. return this;
  25247. }
  25248. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25249. return this;
  25250. }
  25251. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25252. return this;
  25253. }
  25254. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25255. return this;
  25256. }
  25257. if (!this._sourcePositions) {
  25258. var submeshes = this.subMeshes.slice();
  25259. this.setPositionsForCPUSkinning();
  25260. this.subMeshes = submeshes;
  25261. }
  25262. if (!this._sourceNormals) {
  25263. this.setNormalsForCPUSkinning();
  25264. }
  25265. // positionsData checks for not being Float32Array will only pass at most once
  25266. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25267. if (!positionsData) {
  25268. return this;
  25269. }
  25270. if (!(positionsData instanceof Float32Array)) {
  25271. positionsData = new Float32Array(positionsData);
  25272. }
  25273. // normalsData checks for not being Float32Array will only pass at most once
  25274. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25275. if (!normalsData) {
  25276. return this;
  25277. }
  25278. if (!(normalsData instanceof Float32Array)) {
  25279. normalsData = new Float32Array(normalsData);
  25280. }
  25281. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25282. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25283. if (!matricesWeightsData || !matricesIndicesData) {
  25284. return this;
  25285. }
  25286. var needExtras = this.numBoneInfluencers > 4;
  25287. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25288. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25289. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25290. return this;
  25291. }
  25292. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25293. var tempVector3 = BABYLON.Vector3.Zero();
  25294. var finalMatrix = new BABYLON.Matrix();
  25295. var tempMatrix = new BABYLON.Matrix();
  25296. var matWeightIdx = 0;
  25297. var inf;
  25298. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25299. var weight;
  25300. for (inf = 0; inf < 4; inf++) {
  25301. weight = matricesWeightsData[matWeightIdx + inf];
  25302. if (weight > 0) {
  25303. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25304. finalMatrix.addToSelf(tempMatrix);
  25305. }
  25306. else
  25307. break;
  25308. }
  25309. if (needExtras) {
  25310. for (inf = 0; inf < 4; inf++) {
  25311. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25312. if (weight > 0) {
  25313. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25314. finalMatrix.addToSelf(tempMatrix);
  25315. }
  25316. else
  25317. break;
  25318. }
  25319. }
  25320. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25321. tempVector3.toArray(positionsData, index);
  25322. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25323. tempVector3.toArray(normalsData, index);
  25324. finalMatrix.reset();
  25325. }
  25326. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25327. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25328. return this;
  25329. };
  25330. // Tools
  25331. /**
  25332. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25333. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25334. */
  25335. Mesh.MinMax = function (meshes) {
  25336. var minVector = null;
  25337. var maxVector = null;
  25338. meshes.forEach(function (mesh, index, array) {
  25339. var boundingInfo = mesh.getBoundingInfo();
  25340. if (!boundingInfo) {
  25341. return;
  25342. }
  25343. var boundingBox = boundingInfo.boundingBox;
  25344. if (!minVector || !maxVector) {
  25345. minVector = boundingBox.minimumWorld;
  25346. maxVector = boundingBox.maximumWorld;
  25347. }
  25348. else {
  25349. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25350. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25351. }
  25352. });
  25353. if (!minVector || !maxVector) {
  25354. return {
  25355. min: BABYLON.Vector3.Zero(),
  25356. max: BABYLON.Vector3.Zero()
  25357. };
  25358. }
  25359. return {
  25360. min: minVector,
  25361. max: maxVector
  25362. };
  25363. };
  25364. /**
  25365. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25366. */
  25367. Mesh.Center = function (meshesOrMinMaxVector) {
  25368. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25369. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25370. };
  25371. /**
  25372. * Merge the array of meshes into a single mesh for performance reasons.
  25373. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25374. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25375. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25376. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25377. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25378. */
  25379. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25380. if (disposeSource === void 0) { disposeSource = true; }
  25381. var index;
  25382. if (!allow32BitsIndices) {
  25383. var totalVertices = 0;
  25384. // Counting vertices
  25385. for (index = 0; index < meshes.length; index++) {
  25386. if (meshes[index]) {
  25387. totalVertices += meshes[index].getTotalVertices();
  25388. if (totalVertices > 65536) {
  25389. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25390. return null;
  25391. }
  25392. }
  25393. }
  25394. }
  25395. // Merge
  25396. var vertexData = null;
  25397. var otherVertexData;
  25398. var indiceArray = new Array();
  25399. var source = null;
  25400. for (index = 0; index < meshes.length; index++) {
  25401. if (meshes[index]) {
  25402. meshes[index].computeWorldMatrix(true);
  25403. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25404. otherVertexData.transform(meshes[index].getWorldMatrix());
  25405. if (vertexData) {
  25406. vertexData.merge(otherVertexData);
  25407. }
  25408. else {
  25409. vertexData = otherVertexData;
  25410. source = meshes[index];
  25411. }
  25412. if (subdivideWithSubMeshes) {
  25413. indiceArray.push(meshes[index].getTotalIndices());
  25414. }
  25415. }
  25416. }
  25417. source = source;
  25418. if (!meshSubclass) {
  25419. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25420. }
  25421. vertexData.applyToMesh(meshSubclass);
  25422. // Setting properties
  25423. meshSubclass.material = source.material;
  25424. meshSubclass.checkCollisions = source.checkCollisions;
  25425. // Cleaning
  25426. if (disposeSource) {
  25427. for (index = 0; index < meshes.length; index++) {
  25428. if (meshes[index]) {
  25429. meshes[index].dispose();
  25430. }
  25431. }
  25432. }
  25433. // Subdivide
  25434. if (subdivideWithSubMeshes) {
  25435. //-- Suppresions du submesh global
  25436. meshSubclass.releaseSubMeshes();
  25437. index = 0;
  25438. var offset = 0;
  25439. //-- aplique la subdivision en fonction du tableau d'indices
  25440. while (index < indiceArray.length) {
  25441. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25442. offset += indiceArray[index];
  25443. index++;
  25444. }
  25445. }
  25446. return meshSubclass;
  25447. };
  25448. // Consts
  25449. Mesh._FRONTSIDE = 0;
  25450. Mesh._BACKSIDE = 1;
  25451. Mesh._DOUBLESIDE = 2;
  25452. Mesh._DEFAULTSIDE = 0;
  25453. Mesh._NO_CAP = 0;
  25454. Mesh._CAP_START = 1;
  25455. Mesh._CAP_END = 2;
  25456. Mesh._CAP_ALL = 3;
  25457. return Mesh;
  25458. }(BABYLON.AbstractMesh));
  25459. BABYLON.Mesh = Mesh;
  25460. })(BABYLON || (BABYLON = {}));
  25461. //# sourceMappingURL=babylon.mesh.js.map
  25462. var BABYLON;
  25463. (function (BABYLON) {
  25464. var BaseSubMesh = /** @class */ (function () {
  25465. function BaseSubMesh() {
  25466. }
  25467. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25468. get: function () {
  25469. return this._materialEffect;
  25470. },
  25471. enumerable: true,
  25472. configurable: true
  25473. });
  25474. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25475. if (defines === void 0) { defines = null; }
  25476. if (this._materialEffect === effect) {
  25477. if (!effect) {
  25478. this._materialDefines = null;
  25479. }
  25480. return;
  25481. }
  25482. this._materialDefines = defines;
  25483. this._materialEffect = effect;
  25484. };
  25485. return BaseSubMesh;
  25486. }());
  25487. BABYLON.BaseSubMesh = BaseSubMesh;
  25488. var SubMesh = /** @class */ (function (_super) {
  25489. __extends(SubMesh, _super);
  25490. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25491. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25492. var _this = _super.call(this) || this;
  25493. _this.materialIndex = materialIndex;
  25494. _this.verticesStart = verticesStart;
  25495. _this.verticesCount = verticesCount;
  25496. _this.indexStart = indexStart;
  25497. _this.indexCount = indexCount;
  25498. _this._renderId = 0;
  25499. _this._mesh = mesh;
  25500. _this._renderingMesh = renderingMesh || mesh;
  25501. mesh.subMeshes.push(_this);
  25502. _this._trianglePlanes = [];
  25503. _this._id = mesh.subMeshes.length - 1;
  25504. if (createBoundingBox) {
  25505. _this.refreshBoundingInfo();
  25506. mesh.computeWorldMatrix(true);
  25507. }
  25508. return _this;
  25509. }
  25510. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25511. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25512. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25513. };
  25514. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25515. get: function () {
  25516. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25517. },
  25518. enumerable: true,
  25519. configurable: true
  25520. });
  25521. /**
  25522. * Returns the submesh BoudingInfo object.
  25523. */
  25524. SubMesh.prototype.getBoundingInfo = function () {
  25525. if (this.IsGlobal) {
  25526. return this._mesh.getBoundingInfo();
  25527. }
  25528. return this._boundingInfo;
  25529. };
  25530. /**
  25531. * Sets the submesh BoundingInfo.
  25532. * Return the SubMesh.
  25533. */
  25534. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25535. this._boundingInfo = boundingInfo;
  25536. return this;
  25537. };
  25538. /**
  25539. * Returns the mesh of the current submesh.
  25540. */
  25541. SubMesh.prototype.getMesh = function () {
  25542. return this._mesh;
  25543. };
  25544. /**
  25545. * Returns the rendering mesh of the submesh.
  25546. */
  25547. SubMesh.prototype.getRenderingMesh = function () {
  25548. return this._renderingMesh;
  25549. };
  25550. /**
  25551. * Returns the submesh material.
  25552. */
  25553. SubMesh.prototype.getMaterial = function () {
  25554. var rootMaterial = this._renderingMesh.material;
  25555. if (rootMaterial && rootMaterial.getSubMaterial) {
  25556. var multiMaterial = rootMaterial;
  25557. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25558. if (this._currentMaterial !== effectiveMaterial) {
  25559. this._currentMaterial = effectiveMaterial;
  25560. this._materialDefines = null;
  25561. }
  25562. return effectiveMaterial;
  25563. }
  25564. if (!rootMaterial) {
  25565. return this._mesh.getScene().defaultMaterial;
  25566. }
  25567. return rootMaterial;
  25568. };
  25569. // Methods
  25570. /**
  25571. * Sets a new updated BoundingInfo object to the submesh.
  25572. * Returns the SubMesh.
  25573. */
  25574. SubMesh.prototype.refreshBoundingInfo = function () {
  25575. this._lastColliderWorldVertices = null;
  25576. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25577. return this;
  25578. }
  25579. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25580. if (!data) {
  25581. this._boundingInfo = this._mesh._boundingInfo;
  25582. return this;
  25583. }
  25584. var indices = this._renderingMesh.getIndices();
  25585. var extend;
  25586. //is this the only submesh?
  25587. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25588. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25589. if (!boundingInfo) {
  25590. return this;
  25591. }
  25592. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25593. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25594. }
  25595. else {
  25596. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25597. }
  25598. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25599. return this;
  25600. };
  25601. SubMesh.prototype._checkCollision = function (collider) {
  25602. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25603. if (!boundingInfo) {
  25604. return false;
  25605. }
  25606. return boundingInfo._checkCollision(collider);
  25607. };
  25608. /**
  25609. * Updates the submesh BoundingInfo.
  25610. * Returns the Submesh.
  25611. */
  25612. SubMesh.prototype.updateBoundingInfo = function (world) {
  25613. var boundingInfo = this.getBoundingInfo();
  25614. if (!boundingInfo) {
  25615. this.refreshBoundingInfo();
  25616. boundingInfo = this.getBoundingInfo();
  25617. }
  25618. boundingInfo.update(world);
  25619. return this;
  25620. };
  25621. /**
  25622. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25623. * Boolean returned.
  25624. */
  25625. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25626. var boundingInfo = this.getBoundingInfo();
  25627. if (!boundingInfo) {
  25628. return false;
  25629. }
  25630. return boundingInfo.isInFrustum(frustumPlanes);
  25631. };
  25632. /**
  25633. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25634. * Boolean returned.
  25635. */
  25636. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25637. var boundingInfo = this.getBoundingInfo();
  25638. if (!boundingInfo) {
  25639. return false;
  25640. }
  25641. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25642. };
  25643. /**
  25644. * Renders the submesh.
  25645. * Returns it.
  25646. */
  25647. SubMesh.prototype.render = function (enableAlphaMode) {
  25648. this._renderingMesh.render(this, enableAlphaMode);
  25649. return this;
  25650. };
  25651. /**
  25652. * Returns a new Index Buffer.
  25653. * Type returned : WebGLBuffer.
  25654. */
  25655. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25656. if (!this._linesIndexBuffer) {
  25657. var linesIndices = [];
  25658. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25659. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25660. }
  25661. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25662. this.linesIndexCount = linesIndices.length;
  25663. }
  25664. return this._linesIndexBuffer;
  25665. };
  25666. /**
  25667. * True is the passed Ray intersects the submesh bounding box.
  25668. * Boolean returned.
  25669. */
  25670. SubMesh.prototype.canIntersects = function (ray) {
  25671. var boundingInfo = this.getBoundingInfo();
  25672. if (!boundingInfo) {
  25673. return false;
  25674. }
  25675. return ray.intersectsBox(boundingInfo.boundingBox);
  25676. };
  25677. /**
  25678. * Returns an object IntersectionInfo.
  25679. */
  25680. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25681. var intersectInfo = null;
  25682. // LineMesh first as it's also a Mesh...
  25683. if (this._mesh instanceof BABYLON.LinesMesh) {
  25684. var lineMesh = this._mesh;
  25685. // Line test
  25686. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25687. var p0 = positions[indices[index]];
  25688. var p1 = positions[indices[index + 1]];
  25689. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25690. if (length < 0) {
  25691. continue;
  25692. }
  25693. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25694. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25695. if (fastCheck) {
  25696. break;
  25697. }
  25698. }
  25699. }
  25700. }
  25701. else {
  25702. // Triangles test
  25703. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25704. var p0 = positions[indices[index]];
  25705. var p1 = positions[indices[index + 1]];
  25706. var p2 = positions[indices[index + 2]];
  25707. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25708. if (currentIntersectInfo) {
  25709. if (currentIntersectInfo.distance < 0) {
  25710. continue;
  25711. }
  25712. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25713. intersectInfo = currentIntersectInfo;
  25714. intersectInfo.faceId = index / 3;
  25715. if (fastCheck) {
  25716. break;
  25717. }
  25718. }
  25719. }
  25720. }
  25721. }
  25722. return intersectInfo;
  25723. };
  25724. SubMesh.prototype._rebuild = function () {
  25725. if (this._linesIndexBuffer) {
  25726. this._linesIndexBuffer = null;
  25727. }
  25728. };
  25729. // Clone
  25730. /**
  25731. * Creates a new Submesh from the passed Mesh.
  25732. */
  25733. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25734. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25735. if (!this.IsGlobal) {
  25736. var boundingInfo = this.getBoundingInfo();
  25737. if (!boundingInfo) {
  25738. return result;
  25739. }
  25740. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25741. }
  25742. return result;
  25743. };
  25744. // Dispose
  25745. /**
  25746. * Disposes the Submesh.
  25747. * Returns nothing.
  25748. */
  25749. SubMesh.prototype.dispose = function () {
  25750. if (this._linesIndexBuffer) {
  25751. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25752. this._linesIndexBuffer = null;
  25753. }
  25754. // Remove from mesh
  25755. var index = this._mesh.subMeshes.indexOf(this);
  25756. this._mesh.subMeshes.splice(index, 1);
  25757. };
  25758. // Statics
  25759. /**
  25760. * Creates a new Submesh from the passed parameters :
  25761. * - materialIndex (integer) : the index of the main mesh material.
  25762. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25763. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25764. * - mesh (Mesh) : the main mesh to create the submesh from.
  25765. * - renderingMesh (optional Mesh) : rendering mesh.
  25766. */
  25767. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25768. var minVertexIndex = Number.MAX_VALUE;
  25769. var maxVertexIndex = -Number.MAX_VALUE;
  25770. renderingMesh = (renderingMesh || mesh);
  25771. var indices = renderingMesh.getIndices();
  25772. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25773. var vertexIndex = indices[index];
  25774. if (vertexIndex < minVertexIndex)
  25775. minVertexIndex = vertexIndex;
  25776. if (vertexIndex > maxVertexIndex)
  25777. maxVertexIndex = vertexIndex;
  25778. }
  25779. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25780. };
  25781. return SubMesh;
  25782. }(BaseSubMesh));
  25783. BABYLON.SubMesh = SubMesh;
  25784. })(BABYLON || (BABYLON = {}));
  25785. //# sourceMappingURL=babylon.subMesh.js.map
  25786. var BABYLON;
  25787. (function (BABYLON) {
  25788. var EffectFallbacks = /** @class */ (function () {
  25789. function EffectFallbacks() {
  25790. this._defines = {};
  25791. this._currentRank = 32;
  25792. this._maxRank = -1;
  25793. }
  25794. EffectFallbacks.prototype.unBindMesh = function () {
  25795. this._mesh = null;
  25796. };
  25797. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25798. if (!this._defines[rank]) {
  25799. if (rank < this._currentRank) {
  25800. this._currentRank = rank;
  25801. }
  25802. if (rank > this._maxRank) {
  25803. this._maxRank = rank;
  25804. }
  25805. this._defines[rank] = new Array();
  25806. }
  25807. this._defines[rank].push(define);
  25808. };
  25809. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25810. this._meshRank = rank;
  25811. this._mesh = mesh;
  25812. if (rank < this._currentRank) {
  25813. this._currentRank = rank;
  25814. }
  25815. if (rank > this._maxRank) {
  25816. this._maxRank = rank;
  25817. }
  25818. };
  25819. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25820. get: function () {
  25821. return this._currentRank <= this._maxRank;
  25822. },
  25823. enumerable: true,
  25824. configurable: true
  25825. });
  25826. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25827. // First we try to switch to CPU skinning
  25828. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25829. this._mesh.computeBonesUsingShaders = false;
  25830. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25831. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25832. var scene = this._mesh.getScene();
  25833. for (var index = 0; index < scene.meshes.length; index++) {
  25834. var otherMesh = scene.meshes[index];
  25835. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25836. otherMesh.computeBonesUsingShaders = false;
  25837. }
  25838. }
  25839. }
  25840. else {
  25841. var currentFallbacks = this._defines[this._currentRank];
  25842. if (currentFallbacks) {
  25843. for (var index = 0; index < currentFallbacks.length; index++) {
  25844. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25845. }
  25846. }
  25847. this._currentRank++;
  25848. }
  25849. return currentDefines;
  25850. };
  25851. return EffectFallbacks;
  25852. }());
  25853. BABYLON.EffectFallbacks = EffectFallbacks;
  25854. var EffectCreationOptions = /** @class */ (function () {
  25855. function EffectCreationOptions() {
  25856. }
  25857. return EffectCreationOptions;
  25858. }());
  25859. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25860. var Effect = /** @class */ (function () {
  25861. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25862. if (samplers === void 0) { samplers = null; }
  25863. if (defines === void 0) { defines = null; }
  25864. if (fallbacks === void 0) { fallbacks = null; }
  25865. if (onCompiled === void 0) { onCompiled = null; }
  25866. if (onError === void 0) { onError = null; }
  25867. var _this = this;
  25868. this.uniqueId = 0;
  25869. this.onCompileObservable = new BABYLON.Observable();
  25870. this.onErrorObservable = new BABYLON.Observable();
  25871. this.onBindObservable = new BABYLON.Observable();
  25872. this._uniformBuffersNames = {};
  25873. this._isReady = false;
  25874. this._compilationError = "";
  25875. this.name = baseName;
  25876. if (attributesNamesOrOptions.attributes) {
  25877. var options = attributesNamesOrOptions;
  25878. this._engine = uniformsNamesOrEngine;
  25879. this._attributesNames = options.attributes;
  25880. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25881. this._samplers = options.samplers;
  25882. this.defines = options.defines;
  25883. this.onError = options.onError;
  25884. this.onCompiled = options.onCompiled;
  25885. this._fallbacks = options.fallbacks;
  25886. this._indexParameters = options.indexParameters;
  25887. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  25888. if (options.uniformBuffersNames) {
  25889. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25890. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25891. }
  25892. }
  25893. }
  25894. else {
  25895. this._engine = engine;
  25896. this.defines = defines;
  25897. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25898. this._samplers = samplers;
  25899. this._attributesNames = attributesNamesOrOptions;
  25900. this.onError = onError;
  25901. this.onCompiled = onCompiled;
  25902. this._indexParameters = indexParameters;
  25903. this._fallbacks = fallbacks;
  25904. }
  25905. this.uniqueId = Effect._uniqueIdSeed++;
  25906. var vertexSource;
  25907. var fragmentSource;
  25908. if (baseName.vertexElement) {
  25909. vertexSource = document.getElementById(baseName.vertexElement);
  25910. if (!vertexSource) {
  25911. vertexSource = baseName.vertexElement;
  25912. }
  25913. }
  25914. else {
  25915. vertexSource = baseName.vertex || baseName;
  25916. }
  25917. if (baseName.fragmentElement) {
  25918. fragmentSource = document.getElementById(baseName.fragmentElement);
  25919. if (!fragmentSource) {
  25920. fragmentSource = baseName.fragmentElement;
  25921. }
  25922. }
  25923. else {
  25924. fragmentSource = baseName.fragment || baseName;
  25925. }
  25926. this._loadVertexShader(vertexSource, function (vertexCode) {
  25927. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25928. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25929. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25930. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25931. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25932. if (baseName) {
  25933. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25934. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25935. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25936. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25937. }
  25938. else {
  25939. _this._vertexSourceCode = migratedVertexCode;
  25940. _this._fragmentSourceCode = migratedFragmentCode;
  25941. }
  25942. _this._prepareEffect();
  25943. });
  25944. });
  25945. });
  25946. });
  25947. });
  25948. });
  25949. }
  25950. Object.defineProperty(Effect.prototype, "key", {
  25951. get: function () {
  25952. return this._key;
  25953. },
  25954. enumerable: true,
  25955. configurable: true
  25956. });
  25957. // Properties
  25958. Effect.prototype.isReady = function () {
  25959. return this._isReady;
  25960. };
  25961. Effect.prototype.getEngine = function () {
  25962. return this._engine;
  25963. };
  25964. Effect.prototype.getProgram = function () {
  25965. return this._program;
  25966. };
  25967. Effect.prototype.getAttributesNames = function () {
  25968. return this._attributesNames;
  25969. };
  25970. Effect.prototype.getAttributeLocation = function (index) {
  25971. return this._attributes[index];
  25972. };
  25973. Effect.prototype.getAttributeLocationByName = function (name) {
  25974. var index = this._attributesNames.indexOf(name);
  25975. return this._attributes[index];
  25976. };
  25977. Effect.prototype.getAttributesCount = function () {
  25978. return this._attributes.length;
  25979. };
  25980. Effect.prototype.getUniformIndex = function (uniformName) {
  25981. return this._uniformsNames.indexOf(uniformName);
  25982. };
  25983. Effect.prototype.getUniform = function (uniformName) {
  25984. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25985. };
  25986. Effect.prototype.getSamplers = function () {
  25987. return this._samplers;
  25988. };
  25989. Effect.prototype.getCompilationError = function () {
  25990. return this._compilationError;
  25991. };
  25992. // Methods
  25993. Effect.prototype.executeWhenCompiled = function (func) {
  25994. if (this.isReady()) {
  25995. func(this);
  25996. return;
  25997. }
  25998. this.onCompileObservable.add(function (effect) {
  25999. func(effect);
  26000. });
  26001. };
  26002. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26003. if (BABYLON.Tools.IsWindowObjectExist()) {
  26004. // DOM element ?
  26005. if (vertex instanceof HTMLElement) {
  26006. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26007. callback(vertexCode);
  26008. return;
  26009. }
  26010. }
  26011. // Base64 encoded ?
  26012. if (vertex.substr(0, 7) === "base64:") {
  26013. var vertexBinary = window.atob(vertex.substr(7));
  26014. callback(vertexBinary);
  26015. return;
  26016. }
  26017. // Is in local store ?
  26018. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26019. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26020. return;
  26021. }
  26022. var vertexShaderUrl;
  26023. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26024. vertexShaderUrl = vertex;
  26025. }
  26026. else {
  26027. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26028. }
  26029. // Vertex shader
  26030. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26031. };
  26032. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26033. if (BABYLON.Tools.IsWindowObjectExist()) {
  26034. // DOM element ?
  26035. if (fragment instanceof HTMLElement) {
  26036. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26037. callback(fragmentCode);
  26038. return;
  26039. }
  26040. }
  26041. // Base64 encoded ?
  26042. if (fragment.substr(0, 7) === "base64:") {
  26043. var fragmentBinary = window.atob(fragment.substr(7));
  26044. callback(fragmentBinary);
  26045. return;
  26046. }
  26047. // Is in local store ?
  26048. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26049. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26050. return;
  26051. }
  26052. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26053. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26054. return;
  26055. }
  26056. var fragmentShaderUrl;
  26057. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26058. fragmentShaderUrl = fragment;
  26059. }
  26060. else {
  26061. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26062. }
  26063. // Fragment shader
  26064. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26065. };
  26066. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  26067. // Rebuild shaders source code
  26068. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  26069. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  26070. vertexCode = prefix + vertexCode;
  26071. fragmentCode = prefix + fragmentCode;
  26072. // Number lines of shaders source code
  26073. var i = 2;
  26074. var regex = /\n/gm;
  26075. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26076. i = 2;
  26077. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26078. // Dump shaders name and formatted source code
  26079. if (this.name.vertexElement) {
  26080. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  26081. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  26082. }
  26083. else if (this.name.vertex) {
  26084. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  26085. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  26086. }
  26087. else {
  26088. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  26089. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  26090. }
  26091. };
  26092. ;
  26093. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26094. var preparedSourceCode = this._processPrecision(sourceCode);
  26095. if (this._engine.webGLVersion == 1) {
  26096. callback(preparedSourceCode);
  26097. return;
  26098. }
  26099. // Already converted
  26100. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26101. callback(preparedSourceCode.replace("#version 300 es", ""));
  26102. return;
  26103. }
  26104. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26105. // Remove extensions
  26106. // #extension GL_OES_standard_derivatives : enable
  26107. // #extension GL_EXT_shader_texture_lod : enable
  26108. // #extension GL_EXT_frag_depth : enable
  26109. // #extension GL_EXT_draw_buffers : require
  26110. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26111. var result = preparedSourceCode.replace(regex, "");
  26112. // Migrate to GLSL v300
  26113. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26114. result = result.replace(/attribute[ \t]/g, "in ");
  26115. result = result.replace(/[ \t]attribute/g, " in");
  26116. if (isFragment) {
  26117. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26118. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26119. result = result.replace(/texture2D\s*\(/g, "texture(");
  26120. result = result.replace(/textureCube\s*\(/g, "texture(");
  26121. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26122. result = result.replace(/gl_FragColor/g, "glFragColor");
  26123. result = result.replace(/gl_FragData/g, "glFragData");
  26124. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26125. }
  26126. callback(result);
  26127. };
  26128. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26129. var _this = this;
  26130. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26131. var match = regex.exec(sourceCode);
  26132. var returnValue = new String(sourceCode);
  26133. while (match != null) {
  26134. var includeFile = match[1];
  26135. // Uniform declaration
  26136. if (includeFile.indexOf("__decl__") !== -1) {
  26137. includeFile = includeFile.replace(/__decl__/, "");
  26138. if (this._engine.supportsUniformBuffers) {
  26139. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26140. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26141. }
  26142. includeFile = includeFile + "Declaration";
  26143. }
  26144. if (Effect.IncludesShadersStore[includeFile]) {
  26145. // Substitution
  26146. var includeContent = Effect.IncludesShadersStore[includeFile];
  26147. if (match[2]) {
  26148. var splits = match[3].split(",");
  26149. for (var index = 0; index < splits.length; index += 2) {
  26150. var source = new RegExp(splits[index], "g");
  26151. var dest = splits[index + 1];
  26152. includeContent = includeContent.replace(source, dest);
  26153. }
  26154. }
  26155. if (match[4]) {
  26156. var indexString = match[5];
  26157. if (indexString.indexOf("..") !== -1) {
  26158. var indexSplits = indexString.split("..");
  26159. var minIndex = parseInt(indexSplits[0]);
  26160. var maxIndex = parseInt(indexSplits[1]);
  26161. var sourceIncludeContent = includeContent.slice(0);
  26162. includeContent = "";
  26163. if (isNaN(maxIndex)) {
  26164. maxIndex = this._indexParameters[indexSplits[1]];
  26165. }
  26166. for (var i = minIndex; i < maxIndex; i++) {
  26167. if (!this._engine.supportsUniformBuffers) {
  26168. // Ubo replacement
  26169. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26170. return p1 + "{X}";
  26171. });
  26172. }
  26173. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26174. }
  26175. }
  26176. else {
  26177. if (!this._engine.supportsUniformBuffers) {
  26178. // Ubo replacement
  26179. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26180. return p1 + "{X}";
  26181. });
  26182. }
  26183. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26184. }
  26185. }
  26186. // Replace
  26187. returnValue = returnValue.replace(match[0], includeContent);
  26188. }
  26189. else {
  26190. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26191. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26192. Effect.IncludesShadersStore[includeFile] = fileContent;
  26193. _this._processIncludes(returnValue, callback);
  26194. });
  26195. return;
  26196. }
  26197. match = regex.exec(sourceCode);
  26198. }
  26199. callback(returnValue);
  26200. };
  26201. Effect.prototype._processPrecision = function (source) {
  26202. if (source.indexOf("precision highp float") === -1) {
  26203. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26204. source = "precision mediump float;\n" + source;
  26205. }
  26206. else {
  26207. source = "precision highp float;\n" + source;
  26208. }
  26209. }
  26210. else {
  26211. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26212. source = source.replace("precision highp float", "precision mediump float");
  26213. }
  26214. }
  26215. return source;
  26216. };
  26217. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26218. var _this = this;
  26219. this._isReady = false;
  26220. this._vertexSourceCodeOverride = vertexSourceCode;
  26221. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26222. this.onError = function (effect, error) {
  26223. if (onError) {
  26224. onError(error);
  26225. }
  26226. };
  26227. this.onCompiled = function () {
  26228. var scenes = _this.getEngine().scenes;
  26229. for (var i = 0; i < scenes.length; i++) {
  26230. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26231. }
  26232. if (onCompiled) {
  26233. onCompiled(_this._program);
  26234. }
  26235. };
  26236. this._fallbacks = null;
  26237. this._prepareEffect();
  26238. };
  26239. Effect.prototype._prepareEffect = function () {
  26240. var attributesNames = this._attributesNames;
  26241. var defines = this.defines;
  26242. var fallbacks = this._fallbacks;
  26243. this._valueCache = {};
  26244. var previousProgram = this._program;
  26245. try {
  26246. var engine = this._engine;
  26247. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26248. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26249. }
  26250. else {
  26251. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26252. }
  26253. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26254. if (engine.webGLVersion > 1) {
  26255. for (var name in this._uniformBuffersNames) {
  26256. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26257. }
  26258. }
  26259. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26260. this._attributes = engine.getAttributes(this._program, attributesNames);
  26261. var index;
  26262. for (index = 0; index < this._samplers.length; index++) {
  26263. var sampler = this.getUniform(this._samplers[index]);
  26264. if (sampler == null) {
  26265. this._samplers.splice(index, 1);
  26266. index--;
  26267. }
  26268. }
  26269. engine.bindSamplers(this);
  26270. this._compilationError = "";
  26271. this._isReady = true;
  26272. if (this.onCompiled) {
  26273. this.onCompiled(this);
  26274. }
  26275. this.onCompileObservable.notifyObservers(this);
  26276. this.onCompileObservable.clear();
  26277. // Unbind mesh reference in fallbacks
  26278. if (this._fallbacks) {
  26279. this._fallbacks.unBindMesh();
  26280. }
  26281. if (previousProgram) {
  26282. this.getEngine()._deleteProgram(previousProgram);
  26283. }
  26284. }
  26285. catch (e) {
  26286. this._compilationError = e.message;
  26287. // Let's go through fallbacks then
  26288. BABYLON.Tools.Error("Unable to compile effect:");
  26289. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26290. return " " + uniform;
  26291. }));
  26292. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26293. return " " + attribute;
  26294. }));
  26295. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26296. BABYLON.Tools.Error("Error: " + this._compilationError);
  26297. if (previousProgram) {
  26298. this._program = previousProgram;
  26299. this._isReady = true;
  26300. if (this.onError) {
  26301. this.onError(this, this._compilationError);
  26302. }
  26303. this.onErrorObservable.notifyObservers(this);
  26304. }
  26305. if (fallbacks && fallbacks.isMoreFallbacks) {
  26306. BABYLON.Tools.Error("Trying next fallback.");
  26307. this.defines = fallbacks.reduce(this.defines);
  26308. this._prepareEffect();
  26309. }
  26310. else {
  26311. if (this.onError) {
  26312. this.onError(this, this._compilationError);
  26313. }
  26314. this.onErrorObservable.notifyObservers(this);
  26315. this.onErrorObservable.clear();
  26316. // Unbind mesh reference in fallbacks
  26317. if (this._fallbacks) {
  26318. this._fallbacks.unBindMesh();
  26319. }
  26320. }
  26321. }
  26322. };
  26323. Object.defineProperty(Effect.prototype, "isSupported", {
  26324. get: function () {
  26325. return this._compilationError === "";
  26326. },
  26327. enumerable: true,
  26328. configurable: true
  26329. });
  26330. Effect.prototype._bindTexture = function (channel, texture) {
  26331. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26332. };
  26333. Effect.prototype.setTexture = function (channel, texture) {
  26334. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26335. };
  26336. Effect.prototype.setTextureArray = function (channel, textures) {
  26337. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26338. var initialPos = this._samplers.indexOf(channel);
  26339. for (var index = 1; index < textures.length; index++) {
  26340. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26341. }
  26342. }
  26343. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26344. };
  26345. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26346. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26347. };
  26348. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26349. var cache = this._valueCache[uniformName];
  26350. var flag = matrix.updateFlag;
  26351. if (cache !== undefined && cache === flag) {
  26352. return false;
  26353. }
  26354. this._valueCache[uniformName] = flag;
  26355. return true;
  26356. };
  26357. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26358. var cache = this._valueCache[uniformName];
  26359. if (!cache) {
  26360. cache = [x, y];
  26361. this._valueCache[uniformName] = cache;
  26362. return true;
  26363. }
  26364. var changed = false;
  26365. if (cache[0] !== x) {
  26366. cache[0] = x;
  26367. changed = true;
  26368. }
  26369. if (cache[1] !== y) {
  26370. cache[1] = y;
  26371. changed = true;
  26372. }
  26373. return changed;
  26374. };
  26375. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26376. var cache = this._valueCache[uniformName];
  26377. if (!cache) {
  26378. cache = [x, y, z];
  26379. this._valueCache[uniformName] = cache;
  26380. return true;
  26381. }
  26382. var changed = false;
  26383. if (cache[0] !== x) {
  26384. cache[0] = x;
  26385. changed = true;
  26386. }
  26387. if (cache[1] !== y) {
  26388. cache[1] = y;
  26389. changed = true;
  26390. }
  26391. if (cache[2] !== z) {
  26392. cache[2] = z;
  26393. changed = true;
  26394. }
  26395. return changed;
  26396. };
  26397. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26398. var cache = this._valueCache[uniformName];
  26399. if (!cache) {
  26400. cache = [x, y, z, w];
  26401. this._valueCache[uniformName] = cache;
  26402. return true;
  26403. }
  26404. var changed = false;
  26405. if (cache[0] !== x) {
  26406. cache[0] = x;
  26407. changed = true;
  26408. }
  26409. if (cache[1] !== y) {
  26410. cache[1] = y;
  26411. changed = true;
  26412. }
  26413. if (cache[2] !== z) {
  26414. cache[2] = z;
  26415. changed = true;
  26416. }
  26417. if (cache[3] !== w) {
  26418. cache[3] = w;
  26419. changed = true;
  26420. }
  26421. return changed;
  26422. };
  26423. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26424. var bufferName = this._uniformBuffersNames[name];
  26425. if (Effect._baseCache[bufferName] === buffer) {
  26426. return;
  26427. }
  26428. Effect._baseCache[bufferName] = buffer;
  26429. this._engine.bindUniformBufferBase(buffer, bufferName);
  26430. };
  26431. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26432. this._engine.bindUniformBlock(this._program, blockName, index);
  26433. };
  26434. Effect.prototype.setIntArray = function (uniformName, array) {
  26435. this._valueCache[uniformName] = null;
  26436. this._engine.setIntArray(this.getUniform(uniformName), array);
  26437. return this;
  26438. };
  26439. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26440. this._valueCache[uniformName] = null;
  26441. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26442. return this;
  26443. };
  26444. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26445. this._valueCache[uniformName] = null;
  26446. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26447. return this;
  26448. };
  26449. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26450. this._valueCache[uniformName] = null;
  26451. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26452. return this;
  26453. };
  26454. Effect.prototype.setFloatArray = function (uniformName, array) {
  26455. this._valueCache[uniformName] = null;
  26456. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26457. return this;
  26458. };
  26459. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26460. this._valueCache[uniformName] = null;
  26461. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26462. return this;
  26463. };
  26464. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26465. this._valueCache[uniformName] = null;
  26466. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26467. return this;
  26468. };
  26469. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26470. this._valueCache[uniformName] = null;
  26471. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26472. return this;
  26473. };
  26474. Effect.prototype.setArray = function (uniformName, array) {
  26475. this._valueCache[uniformName] = null;
  26476. this._engine.setArray(this.getUniform(uniformName), array);
  26477. return this;
  26478. };
  26479. Effect.prototype.setArray2 = function (uniformName, array) {
  26480. this._valueCache[uniformName] = null;
  26481. this._engine.setArray2(this.getUniform(uniformName), array);
  26482. return this;
  26483. };
  26484. Effect.prototype.setArray3 = function (uniformName, array) {
  26485. this._valueCache[uniformName] = null;
  26486. this._engine.setArray3(this.getUniform(uniformName), array);
  26487. return this;
  26488. };
  26489. Effect.prototype.setArray4 = function (uniformName, array) {
  26490. this._valueCache[uniformName] = null;
  26491. this._engine.setArray4(this.getUniform(uniformName), array);
  26492. return this;
  26493. };
  26494. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26495. if (!matrices) {
  26496. return this;
  26497. }
  26498. this._valueCache[uniformName] = null;
  26499. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26500. return this;
  26501. };
  26502. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26503. if (this._cacheMatrix(uniformName, matrix)) {
  26504. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26505. }
  26506. return this;
  26507. };
  26508. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26509. this._valueCache[uniformName] = null;
  26510. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26511. return this;
  26512. };
  26513. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26514. this._valueCache[uniformName] = null;
  26515. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26516. return this;
  26517. };
  26518. Effect.prototype.setFloat = function (uniformName, value) {
  26519. var cache = this._valueCache[uniformName];
  26520. if (cache !== undefined && cache === value)
  26521. return this;
  26522. this._valueCache[uniformName] = value;
  26523. this._engine.setFloat(this.getUniform(uniformName), value);
  26524. return this;
  26525. };
  26526. Effect.prototype.setBool = function (uniformName, bool) {
  26527. var cache = this._valueCache[uniformName];
  26528. if (cache !== undefined && cache === bool)
  26529. return this;
  26530. this._valueCache[uniformName] = bool;
  26531. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26532. return this;
  26533. };
  26534. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26535. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26536. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26537. }
  26538. return this;
  26539. };
  26540. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26541. if (this._cacheFloat2(uniformName, x, y)) {
  26542. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26543. }
  26544. return this;
  26545. };
  26546. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26547. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26548. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26549. }
  26550. return this;
  26551. };
  26552. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26553. if (this._cacheFloat3(uniformName, x, y, z)) {
  26554. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26555. }
  26556. return this;
  26557. };
  26558. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26559. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26560. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26561. }
  26562. return this;
  26563. };
  26564. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26565. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26566. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26567. }
  26568. return this;
  26569. };
  26570. Effect.prototype.setColor3 = function (uniformName, color3) {
  26571. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26572. this._engine.setColor3(this.getUniform(uniformName), color3);
  26573. }
  26574. return this;
  26575. };
  26576. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26577. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26578. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26579. }
  26580. return this;
  26581. };
  26582. Effect.ResetCache = function () {
  26583. Effect._baseCache = {};
  26584. };
  26585. Effect._uniqueIdSeed = 0;
  26586. Effect._baseCache = {};
  26587. // Statics
  26588. Effect.ShadersStore = {};
  26589. Effect.IncludesShadersStore = {};
  26590. return Effect;
  26591. }());
  26592. BABYLON.Effect = Effect;
  26593. })(BABYLON || (BABYLON = {}));
  26594. //# sourceMappingURL=babylon.effect.js.map
  26595. var BABYLON;
  26596. (function (BABYLON) {
  26597. var MaterialHelper = /** @class */ (function () {
  26598. function MaterialHelper() {
  26599. }
  26600. MaterialHelper.BindEyePosition = function (effect, scene) {
  26601. if (scene._forcedViewPosition) {
  26602. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26603. return;
  26604. }
  26605. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26606. };
  26607. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26608. defines._needUVs = true;
  26609. defines[key] = true;
  26610. if (texture.getTextureMatrix().isIdentity(true)) {
  26611. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26612. if (texture.coordinatesIndex === 0) {
  26613. defines["MAINUV1"] = true;
  26614. }
  26615. else {
  26616. defines["MAINUV2"] = true;
  26617. }
  26618. }
  26619. else {
  26620. defines[key + "DIRECTUV"] = 0;
  26621. }
  26622. };
  26623. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26624. var matrix = texture.getTextureMatrix();
  26625. if (!matrix.isIdentity(true)) {
  26626. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26627. }
  26628. };
  26629. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26630. if (defines._areMiscDirty) {
  26631. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26632. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26633. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26634. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26635. }
  26636. };
  26637. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26638. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26639. var changed = false;
  26640. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26641. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26642. changed = true;
  26643. }
  26644. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26645. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26646. changed = true;
  26647. }
  26648. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26649. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26650. changed = true;
  26651. }
  26652. if (defines["INSTANCES"] !== useInstances) {
  26653. defines["INSTANCES"] = useInstances;
  26654. changed = true;
  26655. }
  26656. if (changed) {
  26657. defines.markAsUnprocessed();
  26658. }
  26659. };
  26660. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  26661. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26662. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  26663. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26664. return false;
  26665. }
  26666. defines._normals = defines._needNormals;
  26667. defines._uvs = defines._needUVs;
  26668. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26669. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26670. defines["TANGENT"] = true;
  26671. }
  26672. if (defines._needUVs) {
  26673. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26674. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26675. }
  26676. else {
  26677. defines["UV1"] = false;
  26678. defines["UV2"] = false;
  26679. }
  26680. if (useVertexColor) {
  26681. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26682. defines["VERTEXCOLOR"] = hasVertexColors;
  26683. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  26684. }
  26685. if (useBones) {
  26686. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26687. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26688. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26689. }
  26690. else {
  26691. defines["NUM_BONE_INFLUENCERS"] = 0;
  26692. defines["BonesPerMesh"] = 0;
  26693. }
  26694. }
  26695. if (useMorphTargets) {
  26696. var manager = mesh.morphTargetManager;
  26697. if (manager) {
  26698. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26699. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26700. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26701. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26702. }
  26703. else {
  26704. defines["MORPHTARGETS_TANGENT"] = false;
  26705. defines["MORPHTARGETS_NORMAL"] = false;
  26706. defines["MORPHTARGETS"] = false;
  26707. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26708. }
  26709. }
  26710. return true;
  26711. };
  26712. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26713. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26714. if (disableLighting === void 0) { disableLighting = false; }
  26715. if (!defines._areLightsDirty) {
  26716. return defines._needNormals;
  26717. }
  26718. var lightIndex = 0;
  26719. var needNormals = false;
  26720. var needRebuild = false;
  26721. var lightmapMode = false;
  26722. var shadowEnabled = false;
  26723. var specularEnabled = false;
  26724. if (scene.lightsEnabled && !disableLighting) {
  26725. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26726. var light = _a[_i];
  26727. needNormals = true;
  26728. if (defines["LIGHT" + lightIndex] === undefined) {
  26729. needRebuild = true;
  26730. }
  26731. defines["LIGHT" + lightIndex] = true;
  26732. defines["SPOTLIGHT" + lightIndex] = false;
  26733. defines["HEMILIGHT" + lightIndex] = false;
  26734. defines["POINTLIGHT" + lightIndex] = false;
  26735. defines["DIRLIGHT" + lightIndex] = false;
  26736. var type;
  26737. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26738. type = "SPOTLIGHT" + lightIndex;
  26739. }
  26740. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26741. type = "HEMILIGHT" + lightIndex;
  26742. }
  26743. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26744. type = "POINTLIGHT" + lightIndex;
  26745. }
  26746. else {
  26747. type = "DIRLIGHT" + lightIndex;
  26748. }
  26749. defines[type] = true;
  26750. // Specular
  26751. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26752. specularEnabled = true;
  26753. }
  26754. // Shadows
  26755. defines["SHADOW" + lightIndex] = false;
  26756. defines["SHADOWPCF" + lightIndex] = false;
  26757. defines["SHADOWESM" + lightIndex] = false;
  26758. defines["SHADOWCUBE" + lightIndex] = false;
  26759. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26760. var shadowGenerator = light.getShadowGenerator();
  26761. if (shadowGenerator) {
  26762. shadowEnabled = true;
  26763. shadowGenerator.prepareDefines(defines, lightIndex);
  26764. }
  26765. }
  26766. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26767. lightmapMode = true;
  26768. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26769. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26770. }
  26771. else {
  26772. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26773. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26774. }
  26775. lightIndex++;
  26776. if (lightIndex === maxSimultaneousLights)
  26777. break;
  26778. }
  26779. }
  26780. defines["SPECULARTERM"] = specularEnabled;
  26781. defines["SHADOWS"] = shadowEnabled;
  26782. // Resetting all other lights if any
  26783. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26784. if (defines["LIGHT" + index] !== undefined) {
  26785. defines["LIGHT" + index] = false;
  26786. defines["HEMILIGHT" + lightIndex] = false;
  26787. defines["POINTLIGHT" + lightIndex] = false;
  26788. defines["DIRLIGHT" + lightIndex] = false;
  26789. defines["SPOTLIGHT" + lightIndex] = false;
  26790. defines["SHADOW" + lightIndex] = false;
  26791. }
  26792. }
  26793. var caps = scene.getEngine().getCaps();
  26794. if (defines["SHADOWFLOAT"] === undefined) {
  26795. needRebuild = true;
  26796. }
  26797. defines["SHADOWFLOAT"] = shadowEnabled &&
  26798. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26799. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26800. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26801. if (needRebuild) {
  26802. defines.rebuild();
  26803. }
  26804. return needNormals;
  26805. };
  26806. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26807. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26808. var uniformsList;
  26809. var uniformBuffersList = null;
  26810. if (uniformsListOrOptions.uniformsNames) {
  26811. var options = uniformsListOrOptions;
  26812. uniformsList = options.uniformsNames;
  26813. uniformBuffersList = options.uniformBuffersNames;
  26814. samplersList = options.samplers;
  26815. defines = options.defines;
  26816. maxSimultaneousLights = options.maxSimultaneousLights;
  26817. }
  26818. else {
  26819. uniformsList = uniformsListOrOptions;
  26820. if (!samplersList) {
  26821. samplersList = [];
  26822. }
  26823. }
  26824. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26825. if (!defines["LIGHT" + lightIndex]) {
  26826. break;
  26827. }
  26828. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26829. if (uniformBuffersList) {
  26830. uniformBuffersList.push("Light" + lightIndex);
  26831. }
  26832. samplersList.push("shadowSampler" + lightIndex);
  26833. }
  26834. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26835. uniformsList.push("morphTargetInfluences");
  26836. }
  26837. };
  26838. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  26839. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26840. if (rank === void 0) { rank = 0; }
  26841. var lightFallbackRank = 0;
  26842. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26843. if (!defines["LIGHT" + lightIndex]) {
  26844. break;
  26845. }
  26846. if (lightIndex > 0) {
  26847. lightFallbackRank = rank + lightIndex;
  26848. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  26849. }
  26850. if (!defines["SHADOWS"]) {
  26851. if (defines["SHADOW" + lightIndex]) {
  26852. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  26853. }
  26854. if (defines["SHADOWPCF" + lightIndex]) {
  26855. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  26856. }
  26857. if (defines["SHADOWESM" + lightIndex]) {
  26858. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  26859. }
  26860. }
  26861. }
  26862. return lightFallbackRank++;
  26863. };
  26864. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26865. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26866. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26867. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26868. var manager = mesh.morphTargetManager;
  26869. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26870. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26871. for (var index = 0; index < influencers; index++) {
  26872. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26873. if (normal) {
  26874. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26875. }
  26876. if (tangent) {
  26877. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26878. }
  26879. if (attribs.length > maxAttributesCount) {
  26880. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26881. }
  26882. }
  26883. }
  26884. };
  26885. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26886. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26887. fallbacks.addCPUSkinningFallback(0, mesh);
  26888. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26889. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26890. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26891. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26892. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26893. }
  26894. }
  26895. };
  26896. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26897. if (defines["INSTANCES"]) {
  26898. attribs.push("world0");
  26899. attribs.push("world1");
  26900. attribs.push("world2");
  26901. attribs.push("world3");
  26902. }
  26903. };
  26904. // Bindings
  26905. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26906. if (light.shadowEnabled && mesh.receiveShadows) {
  26907. var shadowGenerator = light.getShadowGenerator();
  26908. if (shadowGenerator) {
  26909. shadowGenerator.bindShadowLight(lightIndex, effect);
  26910. }
  26911. }
  26912. };
  26913. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26914. light.transferToEffect(effect, lightIndex + "");
  26915. };
  26916. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26917. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26918. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26919. var lightIndex = 0;
  26920. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26921. var light = _a[_i];
  26922. var scaledIntensity = light.getScaledIntensity();
  26923. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26924. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26925. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26926. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26927. if (defines["SPECULARTERM"]) {
  26928. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26929. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26930. }
  26931. // Shadows
  26932. if (scene.shadowsEnabled) {
  26933. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26934. }
  26935. light._uniformBuffer.update();
  26936. lightIndex++;
  26937. if (lightIndex === maxSimultaneousLights)
  26938. break;
  26939. }
  26940. };
  26941. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26942. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26943. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26944. effect.setColor3("vFogColor", scene.fogColor);
  26945. }
  26946. };
  26947. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26948. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26949. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26950. if (matrices && effect) {
  26951. effect.setMatrices("mBones", matrices);
  26952. }
  26953. }
  26954. };
  26955. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26956. var manager = abstractMesh.morphTargetManager;
  26957. if (!abstractMesh || !manager) {
  26958. return;
  26959. }
  26960. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26961. };
  26962. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26963. if (defines["LOGARITHMICDEPTH"]) {
  26964. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26965. }
  26966. };
  26967. MaterialHelper.BindClipPlane = function (effect, scene) {
  26968. if (scene.clipPlane) {
  26969. var clipPlane = scene.clipPlane;
  26970. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26971. }
  26972. };
  26973. return MaterialHelper;
  26974. }());
  26975. BABYLON.MaterialHelper = MaterialHelper;
  26976. })(BABYLON || (BABYLON = {}));
  26977. //# sourceMappingURL=babylon.materialHelper.js.map
  26978. var BABYLON;
  26979. (function (BABYLON) {
  26980. var MaterialDefines = /** @class */ (function () {
  26981. function MaterialDefines() {
  26982. this._isDirty = true;
  26983. this._areLightsDirty = true;
  26984. this._areAttributesDirty = true;
  26985. this._areTexturesDirty = true;
  26986. this._areFresnelDirty = true;
  26987. this._areMiscDirty = true;
  26988. this._areImageProcessingDirty = true;
  26989. this._normals = false;
  26990. this._uvs = false;
  26991. this._needNormals = false;
  26992. this._needUVs = false;
  26993. }
  26994. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26995. get: function () {
  26996. return this._isDirty;
  26997. },
  26998. enumerable: true,
  26999. configurable: true
  27000. });
  27001. MaterialDefines.prototype.markAsProcessed = function () {
  27002. this._isDirty = false;
  27003. this._areAttributesDirty = false;
  27004. this._areTexturesDirty = false;
  27005. this._areFresnelDirty = false;
  27006. this._areLightsDirty = false;
  27007. this._areMiscDirty = false;
  27008. this._areImageProcessingDirty = false;
  27009. };
  27010. MaterialDefines.prototype.markAsUnprocessed = function () {
  27011. this._isDirty = true;
  27012. };
  27013. MaterialDefines.prototype.markAllAsDirty = function () {
  27014. this._areTexturesDirty = true;
  27015. this._areAttributesDirty = true;
  27016. this._areLightsDirty = true;
  27017. this._areFresnelDirty = true;
  27018. this._areMiscDirty = true;
  27019. this._areImageProcessingDirty = true;
  27020. this._isDirty = true;
  27021. };
  27022. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27023. this._areImageProcessingDirty = true;
  27024. this._isDirty = true;
  27025. };
  27026. MaterialDefines.prototype.markAsLightDirty = function () {
  27027. this._areLightsDirty = true;
  27028. this._isDirty = true;
  27029. };
  27030. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27031. this._areAttributesDirty = true;
  27032. this._isDirty = true;
  27033. };
  27034. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27035. this._areTexturesDirty = true;
  27036. this._isDirty = true;
  27037. };
  27038. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27039. this._areFresnelDirty = true;
  27040. this._isDirty = true;
  27041. };
  27042. MaterialDefines.prototype.markAsMiscDirty = function () {
  27043. this._areMiscDirty = true;
  27044. this._isDirty = true;
  27045. };
  27046. MaterialDefines.prototype.rebuild = function () {
  27047. if (this._keys) {
  27048. delete this._keys;
  27049. }
  27050. this._keys = [];
  27051. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27052. var key = _a[_i];
  27053. if (key[0] === "_") {
  27054. continue;
  27055. }
  27056. this._keys.push(key);
  27057. }
  27058. };
  27059. MaterialDefines.prototype.isEqual = function (other) {
  27060. if (this._keys.length !== other._keys.length) {
  27061. return false;
  27062. }
  27063. for (var index = 0; index < this._keys.length; index++) {
  27064. var prop = this._keys[index];
  27065. if (this[prop] !== other[prop]) {
  27066. return false;
  27067. }
  27068. }
  27069. return true;
  27070. };
  27071. MaterialDefines.prototype.cloneTo = function (other) {
  27072. if (this._keys.length !== other._keys.length) {
  27073. other._keys = this._keys.slice(0);
  27074. }
  27075. for (var index = 0; index < this._keys.length; index++) {
  27076. var prop = this._keys[index];
  27077. other[prop] = this[prop];
  27078. }
  27079. };
  27080. MaterialDefines.prototype.reset = function () {
  27081. for (var index = 0; index < this._keys.length; index++) {
  27082. var prop = this._keys[index];
  27083. if (typeof (this[prop]) === "number") {
  27084. this[prop] = 0;
  27085. }
  27086. else {
  27087. this[prop] = false;
  27088. }
  27089. }
  27090. };
  27091. MaterialDefines.prototype.toString = function () {
  27092. var result = "";
  27093. for (var index = 0; index < this._keys.length; index++) {
  27094. var prop = this._keys[index];
  27095. var value = this[prop];
  27096. if (typeof (value) === "number") {
  27097. result += "#define " + prop + " " + this[prop] + "\n";
  27098. }
  27099. else if (value) {
  27100. result += "#define " + prop + "\n";
  27101. }
  27102. }
  27103. return result;
  27104. };
  27105. return MaterialDefines;
  27106. }());
  27107. BABYLON.MaterialDefines = MaterialDefines;
  27108. var Material = /** @class */ (function () {
  27109. function Material(name, scene, doNotAdd) {
  27110. this.checkReadyOnEveryCall = false;
  27111. this.checkReadyOnlyOnce = false;
  27112. this.state = "";
  27113. this.alpha = 1.0;
  27114. this._backFaceCulling = true;
  27115. this.doNotSerialize = false;
  27116. this.storeEffectOnSubMeshes = false;
  27117. /**
  27118. * An event triggered when the material is disposed.
  27119. * @type {BABYLON.Observable}
  27120. */
  27121. this.onDisposeObservable = new BABYLON.Observable();
  27122. /**
  27123. * An event triggered when the material is bound.
  27124. * @type {BABYLON.Observable}
  27125. */
  27126. this.onBindObservable = new BABYLON.Observable();
  27127. /**
  27128. * An event triggered when the material is unbound.
  27129. * @type {BABYLON.Observable}
  27130. */
  27131. this.onUnBindObservable = new BABYLON.Observable();
  27132. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27133. this._needDepthPrePass = false;
  27134. this.disableDepthWrite = false;
  27135. this.forceDepthWrite = false;
  27136. this.separateCullingPass = false;
  27137. this._fogEnabled = true;
  27138. this.pointSize = 1.0;
  27139. this.zOffset = 0;
  27140. this._wasPreviouslyReady = false;
  27141. this._fillMode = Material.TriangleFillMode;
  27142. this.name = name;
  27143. this.id = name || BABYLON.Tools.RandomId();
  27144. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27145. if (this._scene.useRightHandedSystem) {
  27146. this.sideOrientation = Material.ClockWiseSideOrientation;
  27147. }
  27148. else {
  27149. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27150. }
  27151. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27152. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27153. if (!doNotAdd) {
  27154. this._scene.materials.push(this);
  27155. }
  27156. }
  27157. Object.defineProperty(Material, "TriangleFillMode", {
  27158. get: function () {
  27159. return Material._TriangleFillMode;
  27160. },
  27161. enumerable: true,
  27162. configurable: true
  27163. });
  27164. Object.defineProperty(Material, "WireFrameFillMode", {
  27165. get: function () {
  27166. return Material._WireFrameFillMode;
  27167. },
  27168. enumerable: true,
  27169. configurable: true
  27170. });
  27171. Object.defineProperty(Material, "PointFillMode", {
  27172. get: function () {
  27173. return Material._PointFillMode;
  27174. },
  27175. enumerable: true,
  27176. configurable: true
  27177. });
  27178. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27179. get: function () {
  27180. return Material._ClockWiseSideOrientation;
  27181. },
  27182. enumerable: true,
  27183. configurable: true
  27184. });
  27185. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27186. get: function () {
  27187. return Material._CounterClockWiseSideOrientation;
  27188. },
  27189. enumerable: true,
  27190. configurable: true
  27191. });
  27192. Object.defineProperty(Material, "TextureDirtyFlag", {
  27193. get: function () {
  27194. return Material._TextureDirtyFlag;
  27195. },
  27196. enumerable: true,
  27197. configurable: true
  27198. });
  27199. Object.defineProperty(Material, "LightDirtyFlag", {
  27200. get: function () {
  27201. return Material._LightDirtyFlag;
  27202. },
  27203. enumerable: true,
  27204. configurable: true
  27205. });
  27206. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27207. get: function () {
  27208. return Material._FresnelDirtyFlag;
  27209. },
  27210. enumerable: true,
  27211. configurable: true
  27212. });
  27213. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27214. get: function () {
  27215. return Material._AttributesDirtyFlag;
  27216. },
  27217. enumerable: true,
  27218. configurable: true
  27219. });
  27220. Object.defineProperty(Material, "MiscDirtyFlag", {
  27221. get: function () {
  27222. return Material._MiscDirtyFlag;
  27223. },
  27224. enumerable: true,
  27225. configurable: true
  27226. });
  27227. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27228. get: function () {
  27229. return this._backFaceCulling;
  27230. },
  27231. set: function (value) {
  27232. if (this._backFaceCulling === value) {
  27233. return;
  27234. }
  27235. this._backFaceCulling = value;
  27236. this.markAsDirty(Material.TextureDirtyFlag);
  27237. },
  27238. enumerable: true,
  27239. configurable: true
  27240. });
  27241. Object.defineProperty(Material.prototype, "onDispose", {
  27242. set: function (callback) {
  27243. if (this._onDisposeObserver) {
  27244. this.onDisposeObservable.remove(this._onDisposeObserver);
  27245. }
  27246. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27247. },
  27248. enumerable: true,
  27249. configurable: true
  27250. });
  27251. Object.defineProperty(Material.prototype, "onBind", {
  27252. set: function (callback) {
  27253. if (this._onBindObserver) {
  27254. this.onBindObservable.remove(this._onBindObserver);
  27255. }
  27256. this._onBindObserver = this.onBindObservable.add(callback);
  27257. },
  27258. enumerable: true,
  27259. configurable: true
  27260. });
  27261. Object.defineProperty(Material.prototype, "alphaMode", {
  27262. get: function () {
  27263. return this._alphaMode;
  27264. },
  27265. set: function (value) {
  27266. if (this._alphaMode === value) {
  27267. return;
  27268. }
  27269. this._alphaMode = value;
  27270. this.markAsDirty(Material.TextureDirtyFlag);
  27271. },
  27272. enumerable: true,
  27273. configurable: true
  27274. });
  27275. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27276. get: function () {
  27277. return this._needDepthPrePass;
  27278. },
  27279. set: function (value) {
  27280. if (this._needDepthPrePass === value) {
  27281. return;
  27282. }
  27283. this._needDepthPrePass = value;
  27284. if (this._needDepthPrePass) {
  27285. this.checkReadyOnEveryCall = true;
  27286. }
  27287. },
  27288. enumerable: true,
  27289. configurable: true
  27290. });
  27291. Object.defineProperty(Material.prototype, "fogEnabled", {
  27292. get: function () {
  27293. return this._fogEnabled;
  27294. },
  27295. set: function (value) {
  27296. if (this._fogEnabled === value) {
  27297. return;
  27298. }
  27299. this._fogEnabled = value;
  27300. this.markAsDirty(Material.MiscDirtyFlag);
  27301. },
  27302. enumerable: true,
  27303. configurable: true
  27304. });
  27305. Object.defineProperty(Material.prototype, "wireframe", {
  27306. get: function () {
  27307. return this._fillMode === Material.WireFrameFillMode;
  27308. },
  27309. set: function (value) {
  27310. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27311. },
  27312. enumerable: true,
  27313. configurable: true
  27314. });
  27315. Object.defineProperty(Material.prototype, "pointsCloud", {
  27316. get: function () {
  27317. return this._fillMode === Material.PointFillMode;
  27318. },
  27319. set: function (value) {
  27320. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27321. },
  27322. enumerable: true,
  27323. configurable: true
  27324. });
  27325. Object.defineProperty(Material.prototype, "fillMode", {
  27326. get: function () {
  27327. return this._fillMode;
  27328. },
  27329. set: function (value) {
  27330. if (this._fillMode === value) {
  27331. return;
  27332. }
  27333. this._fillMode = value;
  27334. this.markAsDirty(Material.MiscDirtyFlag);
  27335. },
  27336. enumerable: true,
  27337. configurable: true
  27338. });
  27339. /**
  27340. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27341. * subclasses should override adding information pertainent to themselves
  27342. */
  27343. Material.prototype.toString = function (fullDetails) {
  27344. var ret = "Name: " + this.name;
  27345. if (fullDetails) {
  27346. }
  27347. return ret;
  27348. };
  27349. /**
  27350. * Child classes can use it to update shaders
  27351. */
  27352. Material.prototype.getClassName = function () {
  27353. return "Material";
  27354. };
  27355. Object.defineProperty(Material.prototype, "isFrozen", {
  27356. get: function () {
  27357. return this.checkReadyOnlyOnce;
  27358. },
  27359. enumerable: true,
  27360. configurable: true
  27361. });
  27362. Material.prototype.freeze = function () {
  27363. this.checkReadyOnlyOnce = true;
  27364. };
  27365. Material.prototype.unfreeze = function () {
  27366. this.checkReadyOnlyOnce = false;
  27367. };
  27368. Material.prototype.isReady = function (mesh, useInstances) {
  27369. return true;
  27370. };
  27371. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27372. return false;
  27373. };
  27374. Material.prototype.getEffect = function () {
  27375. return this._effect;
  27376. };
  27377. Material.prototype.getScene = function () {
  27378. return this._scene;
  27379. };
  27380. Material.prototype.needAlphaBlending = function () {
  27381. return (this.alpha < 1.0);
  27382. };
  27383. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27384. return (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27385. };
  27386. Material.prototype.needAlphaTesting = function () {
  27387. return false;
  27388. };
  27389. Material.prototype.getAlphaTestTexture = function () {
  27390. return null;
  27391. };
  27392. Material.prototype.markDirty = function () {
  27393. this._wasPreviouslyReady = false;
  27394. };
  27395. Material.prototype._preBind = function (effect, overrideOrientation) {
  27396. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27397. var engine = this._scene.getEngine();
  27398. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27399. var reverse = orientation === Material.ClockWiseSideOrientation;
  27400. engine.enableEffect(effect ? effect : this._effect);
  27401. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27402. return reverse;
  27403. };
  27404. Material.prototype.bind = function (world, mesh) {
  27405. };
  27406. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27407. };
  27408. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27409. };
  27410. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27411. sceneUbo.bindToEffect(effect, "Scene");
  27412. };
  27413. Material.prototype.bindView = function (effect) {
  27414. if (!this._useUBO) {
  27415. effect.setMatrix("view", this.getScene().getViewMatrix());
  27416. }
  27417. else {
  27418. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27419. }
  27420. };
  27421. Material.prototype.bindViewProjection = function (effect) {
  27422. if (!this._useUBO) {
  27423. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27424. }
  27425. else {
  27426. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27427. }
  27428. };
  27429. Material.prototype._afterBind = function (mesh) {
  27430. this._scene._cachedMaterial = this;
  27431. if (mesh) {
  27432. this._scene._cachedVisibility = mesh.visibility;
  27433. }
  27434. else {
  27435. this._scene._cachedVisibility = 1;
  27436. }
  27437. if (mesh) {
  27438. this.onBindObservable.notifyObservers(mesh);
  27439. }
  27440. if (this.disableDepthWrite) {
  27441. var engine = this._scene.getEngine();
  27442. this._cachedDepthWriteState = engine.getDepthWrite();
  27443. engine.setDepthWrite(false);
  27444. }
  27445. };
  27446. Material.prototype.unbind = function () {
  27447. this.onUnBindObservable.notifyObservers(this);
  27448. if (this.disableDepthWrite) {
  27449. var engine = this._scene.getEngine();
  27450. engine.setDepthWrite(this._cachedDepthWriteState);
  27451. }
  27452. };
  27453. Material.prototype.getActiveTextures = function () {
  27454. return [];
  27455. };
  27456. Material.prototype.hasTexture = function (texture) {
  27457. return false;
  27458. };
  27459. Material.prototype.clone = function (name) {
  27460. return null;
  27461. };
  27462. Material.prototype.getBindedMeshes = function () {
  27463. var result = new Array();
  27464. for (var index = 0; index < this._scene.meshes.length; index++) {
  27465. var mesh = this._scene.meshes[index];
  27466. if (mesh.material === this) {
  27467. result.push(mesh);
  27468. }
  27469. }
  27470. return result;
  27471. };
  27472. /**
  27473. * Force shader compilation including textures ready check
  27474. */
  27475. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27476. var _this = this;
  27477. var subMesh = new BABYLON.BaseSubMesh();
  27478. var scene = this.getScene();
  27479. var engine = scene.getEngine();
  27480. var checkReady = function () {
  27481. if (!_this._scene || !_this._scene.getEngine()) {
  27482. return;
  27483. }
  27484. if (subMesh._materialDefines) {
  27485. subMesh._materialDefines._renderId = -1;
  27486. }
  27487. var alphaTestState = engine.getAlphaTesting();
  27488. var clipPlaneState = scene.clipPlane;
  27489. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27490. if (options && options.clipPlane) {
  27491. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27492. }
  27493. if (_this.storeEffectOnSubMeshes) {
  27494. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27495. if (onCompiled) {
  27496. onCompiled(_this);
  27497. }
  27498. }
  27499. else {
  27500. setTimeout(checkReady, 16);
  27501. }
  27502. }
  27503. else {
  27504. if (_this.isReady(mesh)) {
  27505. if (onCompiled) {
  27506. onCompiled(_this);
  27507. }
  27508. }
  27509. else {
  27510. setTimeout(checkReady, 16);
  27511. }
  27512. }
  27513. engine.setAlphaTesting(alphaTestState);
  27514. if (options && options.clipPlane) {
  27515. scene.clipPlane = clipPlaneState;
  27516. }
  27517. };
  27518. checkReady();
  27519. };
  27520. Material.prototype.markAsDirty = function (flag) {
  27521. if (flag & Material.TextureDirtyFlag) {
  27522. this._markAllSubMeshesAsTexturesDirty();
  27523. }
  27524. if (flag & Material.LightDirtyFlag) {
  27525. this._markAllSubMeshesAsLightsDirty();
  27526. }
  27527. if (flag & Material.FresnelDirtyFlag) {
  27528. this._markAllSubMeshesAsFresnelDirty();
  27529. }
  27530. if (flag & Material.AttributesDirtyFlag) {
  27531. this._markAllSubMeshesAsAttributesDirty();
  27532. }
  27533. if (flag & Material.MiscDirtyFlag) {
  27534. this._markAllSubMeshesAsMiscDirty();
  27535. }
  27536. this.getScene().resetCachedMaterial();
  27537. };
  27538. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27539. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27540. var mesh = _a[_i];
  27541. if (!mesh.subMeshes) {
  27542. continue;
  27543. }
  27544. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27545. var subMesh = _c[_b];
  27546. if (subMesh.getMaterial() !== this) {
  27547. continue;
  27548. }
  27549. if (!subMesh._materialDefines) {
  27550. continue;
  27551. }
  27552. func(subMesh._materialDefines);
  27553. }
  27554. }
  27555. };
  27556. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27557. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27558. };
  27559. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27560. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27561. };
  27562. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27563. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27564. };
  27565. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27566. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27567. };
  27568. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27569. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27570. };
  27571. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27572. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27573. };
  27574. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27575. // Animations
  27576. this.getScene().stopAnimation(this);
  27577. // Remove from scene
  27578. var index = this._scene.materials.indexOf(this);
  27579. if (index >= 0) {
  27580. this._scene.materials.splice(index, 1);
  27581. }
  27582. // Remove from meshes
  27583. for (index = 0; index < this._scene.meshes.length; index++) {
  27584. var mesh = this._scene.meshes[index];
  27585. if (mesh.material === this) {
  27586. mesh.material = null;
  27587. if (mesh.geometry) {
  27588. var geometry = (mesh.geometry);
  27589. if (this.storeEffectOnSubMeshes) {
  27590. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27591. var subMesh = _a[_i];
  27592. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27593. if (forceDisposeEffect && subMesh._materialEffect) {
  27594. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27595. }
  27596. }
  27597. }
  27598. else {
  27599. geometry._releaseVertexArrayObject(this._effect);
  27600. }
  27601. }
  27602. }
  27603. }
  27604. this._uniformBuffer.dispose();
  27605. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27606. if (forceDisposeEffect && this._effect) {
  27607. if (!this.storeEffectOnSubMeshes) {
  27608. this._scene.getEngine()._releaseEffect(this._effect);
  27609. }
  27610. this._effect = null;
  27611. }
  27612. // Callback
  27613. this.onDisposeObservable.notifyObservers(this);
  27614. this.onDisposeObservable.clear();
  27615. this.onBindObservable.clear();
  27616. this.onUnBindObservable.clear();
  27617. };
  27618. Material.prototype.serialize = function () {
  27619. return BABYLON.SerializationHelper.Serialize(this);
  27620. };
  27621. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27622. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27623. multiMaterial.id = parsedMultiMaterial.id;
  27624. if (BABYLON.Tags) {
  27625. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27626. }
  27627. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27628. var subMatId = parsedMultiMaterial.materials[matIndex];
  27629. if (subMatId) {
  27630. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27631. }
  27632. else {
  27633. multiMaterial.subMaterials.push(null);
  27634. }
  27635. }
  27636. return multiMaterial;
  27637. };
  27638. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27639. if (!parsedMaterial.customType) {
  27640. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27641. }
  27642. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27643. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27644. if (!BABYLON.LegacyPBRMaterial) {
  27645. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27646. return;
  27647. }
  27648. }
  27649. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27650. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27651. ;
  27652. };
  27653. Material._TriangleFillMode = 0;
  27654. Material._WireFrameFillMode = 1;
  27655. Material._PointFillMode = 2;
  27656. Material._ClockWiseSideOrientation = 0;
  27657. Material._CounterClockWiseSideOrientation = 1;
  27658. Material._TextureDirtyFlag = 1;
  27659. Material._LightDirtyFlag = 2;
  27660. Material._FresnelDirtyFlag = 4;
  27661. Material._AttributesDirtyFlag = 8;
  27662. Material._MiscDirtyFlag = 16;
  27663. __decorate([
  27664. BABYLON.serialize()
  27665. ], Material.prototype, "id", void 0);
  27666. __decorate([
  27667. BABYLON.serialize()
  27668. ], Material.prototype, "name", void 0);
  27669. __decorate([
  27670. BABYLON.serialize()
  27671. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27672. __decorate([
  27673. BABYLON.serialize()
  27674. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27675. __decorate([
  27676. BABYLON.serialize()
  27677. ], Material.prototype, "state", void 0);
  27678. __decorate([
  27679. BABYLON.serialize()
  27680. ], Material.prototype, "alpha", void 0);
  27681. __decorate([
  27682. BABYLON.serialize("backFaceCulling")
  27683. ], Material.prototype, "_backFaceCulling", void 0);
  27684. __decorate([
  27685. BABYLON.serialize()
  27686. ], Material.prototype, "sideOrientation", void 0);
  27687. __decorate([
  27688. BABYLON.serialize("alphaMode")
  27689. ], Material.prototype, "_alphaMode", void 0);
  27690. __decorate([
  27691. BABYLON.serialize()
  27692. ], Material.prototype, "_needDepthPrePass", void 0);
  27693. __decorate([
  27694. BABYLON.serialize()
  27695. ], Material.prototype, "disableDepthWrite", void 0);
  27696. __decorate([
  27697. BABYLON.serialize()
  27698. ], Material.prototype, "forceDepthWrite", void 0);
  27699. __decorate([
  27700. BABYLON.serialize()
  27701. ], Material.prototype, "separateCullingPass", void 0);
  27702. __decorate([
  27703. BABYLON.serialize("fogEnabled")
  27704. ], Material.prototype, "_fogEnabled", void 0);
  27705. __decorate([
  27706. BABYLON.serialize()
  27707. ], Material.prototype, "pointSize", void 0);
  27708. __decorate([
  27709. BABYLON.serialize()
  27710. ], Material.prototype, "zOffset", void 0);
  27711. __decorate([
  27712. BABYLON.serialize()
  27713. ], Material.prototype, "wireframe", null);
  27714. __decorate([
  27715. BABYLON.serialize()
  27716. ], Material.prototype, "pointsCloud", null);
  27717. __decorate([
  27718. BABYLON.serialize()
  27719. ], Material.prototype, "fillMode", null);
  27720. return Material;
  27721. }());
  27722. BABYLON.Material = Material;
  27723. })(BABYLON || (BABYLON = {}));
  27724. //# sourceMappingURL=babylon.material.js.map
  27725. var BABYLON;
  27726. (function (BABYLON) {
  27727. var UniformBuffer = /** @class */ (function () {
  27728. /**
  27729. * Uniform buffer objects.
  27730. *
  27731. * Handles blocks of uniform on the GPU.
  27732. *
  27733. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27734. *
  27735. * For more information, please refer to :
  27736. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27737. */
  27738. function UniformBuffer(engine, data, dynamic) {
  27739. this._engine = engine;
  27740. this._noUBO = !engine.supportsUniformBuffers;
  27741. this._dynamic = dynamic;
  27742. this._data = data || [];
  27743. this._uniformLocations = {};
  27744. this._uniformSizes = {};
  27745. this._uniformLocationPointer = 0;
  27746. this._needSync = false;
  27747. if (this._noUBO) {
  27748. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27749. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27750. this.updateFloat = this._updateFloatForEffect;
  27751. this.updateFloat2 = this._updateFloat2ForEffect;
  27752. this.updateFloat3 = this._updateFloat3ForEffect;
  27753. this.updateFloat4 = this._updateFloat4ForEffect;
  27754. this.updateMatrix = this._updateMatrixForEffect;
  27755. this.updateVector3 = this._updateVector3ForEffect;
  27756. this.updateVector4 = this._updateVector4ForEffect;
  27757. this.updateColor3 = this._updateColor3ForEffect;
  27758. this.updateColor4 = this._updateColor4ForEffect;
  27759. }
  27760. else {
  27761. this._engine._uniformBuffers.push(this);
  27762. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27763. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27764. this.updateFloat = this._updateFloatForUniform;
  27765. this.updateFloat2 = this._updateFloat2ForUniform;
  27766. this.updateFloat3 = this._updateFloat3ForUniform;
  27767. this.updateFloat4 = this._updateFloat4ForUniform;
  27768. this.updateMatrix = this._updateMatrixForUniform;
  27769. this.updateVector3 = this._updateVector3ForUniform;
  27770. this.updateVector4 = this._updateVector4ForUniform;
  27771. this.updateColor3 = this._updateColor3ForUniform;
  27772. this.updateColor4 = this._updateColor4ForUniform;
  27773. }
  27774. }
  27775. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27776. // Properties
  27777. /**
  27778. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27779. * or just falling back on setUniformXXX calls.
  27780. */
  27781. get: function () {
  27782. return !this._noUBO;
  27783. },
  27784. enumerable: true,
  27785. configurable: true
  27786. });
  27787. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27788. /**
  27789. * Indicates if the WebGL underlying uniform buffer is in sync
  27790. * with the javascript cache data.
  27791. */
  27792. get: function () {
  27793. return !this._needSync;
  27794. },
  27795. enumerable: true,
  27796. configurable: true
  27797. });
  27798. /**
  27799. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27800. * Also, a dynamic UniformBuffer will disable cache verification and always
  27801. * update the underlying WebGL uniform buffer to the GPU.
  27802. */
  27803. UniformBuffer.prototype.isDynamic = function () {
  27804. return this._dynamic !== undefined;
  27805. };
  27806. /**
  27807. * The data cache on JS side.
  27808. */
  27809. UniformBuffer.prototype.getData = function () {
  27810. return this._bufferData;
  27811. };
  27812. /**
  27813. * The underlying WebGL Uniform buffer.
  27814. */
  27815. UniformBuffer.prototype.getBuffer = function () {
  27816. return this._buffer;
  27817. };
  27818. /**
  27819. * std140 layout specifies how to align data within an UBO structure.
  27820. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27821. * for specs.
  27822. */
  27823. UniformBuffer.prototype._fillAlignment = function (size) {
  27824. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27825. // and 4x4 matrices
  27826. // TODO : change if other types are used
  27827. var alignment;
  27828. if (size <= 2) {
  27829. alignment = size;
  27830. }
  27831. else {
  27832. alignment = 4;
  27833. }
  27834. if ((this._uniformLocationPointer % alignment) !== 0) {
  27835. var oldPointer = this._uniformLocationPointer;
  27836. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27837. var diff = this._uniformLocationPointer - oldPointer;
  27838. for (var i = 0; i < diff; i++) {
  27839. this._data.push(0);
  27840. }
  27841. }
  27842. };
  27843. /**
  27844. * Adds an uniform in the buffer.
  27845. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27846. * for the layout to be correct !
  27847. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27848. * @param {number|number[]} size Data size, or data directly.
  27849. */
  27850. UniformBuffer.prototype.addUniform = function (name, size) {
  27851. if (this._noUBO) {
  27852. return;
  27853. }
  27854. if (this._uniformLocations[name] !== undefined) {
  27855. // Already existing uniform
  27856. return;
  27857. }
  27858. // This function must be called in the order of the shader layout !
  27859. // size can be the size of the uniform, or data directly
  27860. var data;
  27861. if (size instanceof Array) {
  27862. data = size;
  27863. size = data.length;
  27864. }
  27865. else {
  27866. size = size;
  27867. data = [];
  27868. // Fill with zeros
  27869. for (var i = 0; i < size; i++) {
  27870. data.push(0);
  27871. }
  27872. }
  27873. this._fillAlignment(size);
  27874. this._uniformSizes[name] = size;
  27875. this._uniformLocations[name] = this._uniformLocationPointer;
  27876. this._uniformLocationPointer += size;
  27877. for (var i = 0; i < size; i++) {
  27878. this._data.push(data[i]);
  27879. }
  27880. this._needSync = true;
  27881. };
  27882. /**
  27883. * Wrapper for addUniform.
  27884. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27885. * @param {Matrix} mat A 4x4 matrix.
  27886. */
  27887. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27888. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27889. };
  27890. /**
  27891. * Wrapper for addUniform.
  27892. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27893. * @param {number} x
  27894. * @param {number} y
  27895. */
  27896. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27897. var temp = [x, y];
  27898. this.addUniform(name, temp);
  27899. };
  27900. /**
  27901. * Wrapper for addUniform.
  27902. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27903. * @param {number} x
  27904. * @param {number} y
  27905. * @param {number} z
  27906. */
  27907. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27908. var temp = [x, y, z];
  27909. this.addUniform(name, temp);
  27910. };
  27911. /**
  27912. * Wrapper for addUniform.
  27913. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27914. * @param {Color3} color
  27915. */
  27916. UniformBuffer.prototype.addColor3 = function (name, color) {
  27917. var temp = new Array();
  27918. color.toArray(temp);
  27919. this.addUniform(name, temp);
  27920. };
  27921. /**
  27922. * Wrapper for addUniform.
  27923. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27924. * @param {Color3} color
  27925. * @param {number} alpha
  27926. */
  27927. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27928. var temp = new Array();
  27929. color.toArray(temp);
  27930. temp.push(alpha);
  27931. this.addUniform(name, temp);
  27932. };
  27933. /**
  27934. * Wrapper for addUniform.
  27935. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27936. * @param {Vector3} vector
  27937. */
  27938. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27939. var temp = new Array();
  27940. vector.toArray(temp);
  27941. this.addUniform(name, temp);
  27942. };
  27943. /**
  27944. * Wrapper for addUniform.
  27945. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27946. */
  27947. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27948. this.addUniform(name, 12);
  27949. };
  27950. /**
  27951. * Wrapper for addUniform.
  27952. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27953. */
  27954. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27955. this.addUniform(name, 8);
  27956. };
  27957. /**
  27958. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27959. */
  27960. UniformBuffer.prototype.create = function () {
  27961. if (this._noUBO) {
  27962. return;
  27963. }
  27964. if (this._buffer) {
  27965. return; // nothing to do
  27966. }
  27967. // See spec, alignment must be filled as a vec4
  27968. this._fillAlignment(4);
  27969. this._bufferData = new Float32Array(this._data);
  27970. this._rebuild();
  27971. this._needSync = true;
  27972. };
  27973. UniformBuffer.prototype._rebuild = function () {
  27974. if (this._noUBO) {
  27975. return;
  27976. }
  27977. if (this._dynamic) {
  27978. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27979. }
  27980. else {
  27981. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27982. }
  27983. };
  27984. /**
  27985. * Updates the WebGL Uniform Buffer on the GPU.
  27986. * If the `dynamic` flag is set to true, no cache comparison is done.
  27987. * Otherwise, the buffer will be updated only if the cache differs.
  27988. */
  27989. UniformBuffer.prototype.update = function () {
  27990. if (!this._buffer) {
  27991. this.create();
  27992. return;
  27993. }
  27994. if (!this._dynamic && !this._needSync) {
  27995. return;
  27996. }
  27997. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27998. this._needSync = false;
  27999. };
  28000. /**
  28001. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28002. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28003. * @param {number[]|Float32Array} data Flattened data
  28004. * @param {number} size Size of the data.
  28005. */
  28006. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28007. var location = this._uniformLocations[uniformName];
  28008. if (location === undefined) {
  28009. if (this._buffer) {
  28010. // Cannot add an uniform if the buffer is already created
  28011. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28012. return;
  28013. }
  28014. this.addUniform(uniformName, size);
  28015. location = this._uniformLocations[uniformName];
  28016. }
  28017. if (!this._buffer) {
  28018. this.create();
  28019. }
  28020. if (!this._dynamic) {
  28021. // Cache for static uniform buffers
  28022. var changed = false;
  28023. for (var i = 0; i < size; i++) {
  28024. if (this._bufferData[location + i] !== data[i]) {
  28025. changed = true;
  28026. this._bufferData[location + i] = data[i];
  28027. }
  28028. }
  28029. this._needSync = this._needSync || changed;
  28030. }
  28031. else {
  28032. // No cache for dynamic
  28033. for (var i = 0; i < size; i++) {
  28034. this._bufferData[location + i] = data[i];
  28035. }
  28036. }
  28037. };
  28038. // Update methods
  28039. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28040. // To match std140, matrix must be realigned
  28041. for (var i = 0; i < 3; i++) {
  28042. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28043. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28044. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28045. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28046. }
  28047. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28048. };
  28049. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28050. this._currentEffect.setMatrix3x3(name, matrix);
  28051. };
  28052. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28053. this._currentEffect.setMatrix2x2(name, matrix);
  28054. };
  28055. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28056. // To match std140, matrix must be realigned
  28057. for (var i = 0; i < 2; i++) {
  28058. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28059. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28060. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28061. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28062. }
  28063. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28064. };
  28065. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28066. this._currentEffect.setFloat(name, x);
  28067. };
  28068. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28069. UniformBuffer._tempBuffer[0] = x;
  28070. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28071. };
  28072. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28073. if (suffix === void 0) { suffix = ""; }
  28074. this._currentEffect.setFloat2(name + suffix, x, y);
  28075. };
  28076. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28077. if (suffix === void 0) { suffix = ""; }
  28078. UniformBuffer._tempBuffer[0] = x;
  28079. UniformBuffer._tempBuffer[1] = y;
  28080. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28081. };
  28082. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28083. if (suffix === void 0) { suffix = ""; }
  28084. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28085. };
  28086. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28087. if (suffix === void 0) { suffix = ""; }
  28088. UniformBuffer._tempBuffer[0] = x;
  28089. UniformBuffer._tempBuffer[1] = y;
  28090. UniformBuffer._tempBuffer[2] = z;
  28091. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28092. };
  28093. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28094. if (suffix === void 0) { suffix = ""; }
  28095. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28096. };
  28097. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28098. if (suffix === void 0) { suffix = ""; }
  28099. UniformBuffer._tempBuffer[0] = x;
  28100. UniformBuffer._tempBuffer[1] = y;
  28101. UniformBuffer._tempBuffer[2] = z;
  28102. UniformBuffer._tempBuffer[3] = w;
  28103. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28104. };
  28105. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28106. this._currentEffect.setMatrix(name, mat);
  28107. };
  28108. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28109. this.updateUniform(name, mat.toArray(), 16);
  28110. };
  28111. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28112. this._currentEffect.setVector3(name, vector);
  28113. };
  28114. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28115. vector.toArray(UniformBuffer._tempBuffer);
  28116. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28117. };
  28118. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28119. this._currentEffect.setVector4(name, vector);
  28120. };
  28121. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28122. vector.toArray(UniformBuffer._tempBuffer);
  28123. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28124. };
  28125. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28126. if (suffix === void 0) { suffix = ""; }
  28127. this._currentEffect.setColor3(name + suffix, color);
  28128. };
  28129. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28130. if (suffix === void 0) { suffix = ""; }
  28131. color.toArray(UniformBuffer._tempBuffer);
  28132. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28133. };
  28134. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28135. if (suffix === void 0) { suffix = ""; }
  28136. this._currentEffect.setColor4(name + suffix, color, alpha);
  28137. };
  28138. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28139. if (suffix === void 0) { suffix = ""; }
  28140. color.toArray(UniformBuffer._tempBuffer);
  28141. UniformBuffer._tempBuffer[3] = alpha;
  28142. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28143. };
  28144. /**
  28145. * Sets a sampler uniform on the effect.
  28146. * @param {string} name Name of the sampler.
  28147. * @param {Texture} texture
  28148. */
  28149. UniformBuffer.prototype.setTexture = function (name, texture) {
  28150. this._currentEffect.setTexture(name, texture);
  28151. };
  28152. /**
  28153. * Directly updates the value of the uniform in the cache AND on the GPU.
  28154. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28155. * @param {number[]|Float32Array} data Flattened data
  28156. */
  28157. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28158. this.updateUniform(uniformName, data, data.length);
  28159. this.update();
  28160. };
  28161. /**
  28162. * Binds this uniform buffer to an effect.
  28163. * @param {Effect} effect
  28164. * @param {string} name Name of the uniform block in the shader.
  28165. */
  28166. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28167. this._currentEffect = effect;
  28168. if (this._noUBO || !this._buffer) {
  28169. return;
  28170. }
  28171. effect.bindUniformBuffer(this._buffer, name);
  28172. };
  28173. /**
  28174. * Disposes the uniform buffer.
  28175. */
  28176. UniformBuffer.prototype.dispose = function () {
  28177. if (this._noUBO) {
  28178. return;
  28179. }
  28180. var index = this._engine._uniformBuffers.indexOf(this);
  28181. if (index !== -1) {
  28182. this._engine._uniformBuffers.splice(index, 1);
  28183. }
  28184. if (!this._buffer) {
  28185. return;
  28186. }
  28187. if (this._engine._releaseBuffer(this._buffer)) {
  28188. this._buffer = null;
  28189. }
  28190. };
  28191. // Pool for avoiding memory leaks
  28192. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28193. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28194. return UniformBuffer;
  28195. }());
  28196. BABYLON.UniformBuffer = UniformBuffer;
  28197. })(BABYLON || (BABYLON = {}));
  28198. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28199. var BABYLON;
  28200. (function (BABYLON) {
  28201. var PushMaterial = /** @class */ (function (_super) {
  28202. __extends(PushMaterial, _super);
  28203. function PushMaterial(name, scene) {
  28204. var _this = _super.call(this, name, scene) || this;
  28205. _this.storeEffectOnSubMeshes = true;
  28206. return _this;
  28207. }
  28208. PushMaterial.prototype.getEffect = function () {
  28209. return this._activeEffect;
  28210. };
  28211. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28212. if (!mesh) {
  28213. return false;
  28214. }
  28215. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28216. return true;
  28217. }
  28218. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28219. };
  28220. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28221. this._activeEffect.setMatrix("world", world);
  28222. };
  28223. PushMaterial.prototype.bind = function (world, mesh) {
  28224. if (!mesh) {
  28225. return;
  28226. }
  28227. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28228. };
  28229. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28230. if (effect === void 0) { effect = null; }
  28231. _super.prototype._afterBind.call(this, mesh);
  28232. this.getScene()._cachedEffect = effect;
  28233. };
  28234. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28235. if (visibility === void 0) { visibility = 1; }
  28236. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28237. };
  28238. return PushMaterial;
  28239. }(BABYLON.Material));
  28240. BABYLON.PushMaterial = PushMaterial;
  28241. })(BABYLON || (BABYLON = {}));
  28242. //# sourceMappingURL=babylon.pushMaterial.js.map
  28243. var BABYLON;
  28244. (function (BABYLON) {
  28245. var VertexData = /** @class */ (function () {
  28246. function VertexData() {
  28247. }
  28248. VertexData.prototype.set = function (data, kind) {
  28249. switch (kind) {
  28250. case BABYLON.VertexBuffer.PositionKind:
  28251. this.positions = data;
  28252. break;
  28253. case BABYLON.VertexBuffer.NormalKind:
  28254. this.normals = data;
  28255. break;
  28256. case BABYLON.VertexBuffer.TangentKind:
  28257. this.tangents = data;
  28258. break;
  28259. case BABYLON.VertexBuffer.UVKind:
  28260. this.uvs = data;
  28261. break;
  28262. case BABYLON.VertexBuffer.UV2Kind:
  28263. this.uvs2 = data;
  28264. break;
  28265. case BABYLON.VertexBuffer.UV3Kind:
  28266. this.uvs3 = data;
  28267. break;
  28268. case BABYLON.VertexBuffer.UV4Kind:
  28269. this.uvs4 = data;
  28270. break;
  28271. case BABYLON.VertexBuffer.UV5Kind:
  28272. this.uvs5 = data;
  28273. break;
  28274. case BABYLON.VertexBuffer.UV6Kind:
  28275. this.uvs6 = data;
  28276. break;
  28277. case BABYLON.VertexBuffer.ColorKind:
  28278. this.colors = data;
  28279. break;
  28280. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28281. this.matricesIndices = data;
  28282. break;
  28283. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28284. this.matricesWeights = data;
  28285. break;
  28286. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28287. this.matricesIndicesExtra = data;
  28288. break;
  28289. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28290. this.matricesWeightsExtra = data;
  28291. break;
  28292. }
  28293. };
  28294. /**
  28295. * Associates the vertexData to the passed Mesh.
  28296. * Sets it as updatable or not (default `false`).
  28297. * Returns the VertexData.
  28298. */
  28299. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28300. this._applyTo(mesh, updatable);
  28301. return this;
  28302. };
  28303. /**
  28304. * Associates the vertexData to the passed Geometry.
  28305. * Sets it as updatable or not (default `false`).
  28306. * Returns the VertexData.
  28307. */
  28308. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28309. this._applyTo(geometry, updatable);
  28310. return this;
  28311. };
  28312. /**
  28313. * Updates the associated mesh.
  28314. * Returns the VertexData.
  28315. */
  28316. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28317. this._update(mesh);
  28318. return this;
  28319. };
  28320. /**
  28321. * Updates the associated geometry.
  28322. * Returns the VertexData.
  28323. */
  28324. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28325. this._update(geometry);
  28326. return this;
  28327. };
  28328. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28329. if (updatable === void 0) { updatable = false; }
  28330. if (this.positions) {
  28331. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28332. }
  28333. if (this.normals) {
  28334. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28335. }
  28336. if (this.tangents) {
  28337. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28338. }
  28339. if (this.uvs) {
  28340. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28341. }
  28342. if (this.uvs2) {
  28343. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28344. }
  28345. if (this.uvs3) {
  28346. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28347. }
  28348. if (this.uvs4) {
  28349. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28350. }
  28351. if (this.uvs5) {
  28352. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28353. }
  28354. if (this.uvs6) {
  28355. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28356. }
  28357. if (this.colors) {
  28358. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28359. }
  28360. if (this.matricesIndices) {
  28361. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28362. }
  28363. if (this.matricesWeights) {
  28364. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28365. }
  28366. if (this.matricesIndicesExtra) {
  28367. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28368. }
  28369. if (this.matricesWeightsExtra) {
  28370. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28371. }
  28372. if (this.indices) {
  28373. meshOrGeometry.setIndices(this.indices, null, updatable);
  28374. }
  28375. return this;
  28376. };
  28377. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28378. if (this.positions) {
  28379. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28380. }
  28381. if (this.normals) {
  28382. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28383. }
  28384. if (this.tangents) {
  28385. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28386. }
  28387. if (this.uvs) {
  28388. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28389. }
  28390. if (this.uvs2) {
  28391. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28392. }
  28393. if (this.uvs3) {
  28394. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28395. }
  28396. if (this.uvs4) {
  28397. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28398. }
  28399. if (this.uvs5) {
  28400. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28401. }
  28402. if (this.uvs6) {
  28403. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28404. }
  28405. if (this.colors) {
  28406. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28407. }
  28408. if (this.matricesIndices) {
  28409. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28410. }
  28411. if (this.matricesWeights) {
  28412. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28413. }
  28414. if (this.matricesIndicesExtra) {
  28415. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28416. }
  28417. if (this.matricesWeightsExtra) {
  28418. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28419. }
  28420. if (this.indices) {
  28421. meshOrGeometry.setIndices(this.indices, null);
  28422. }
  28423. return this;
  28424. };
  28425. /**
  28426. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28427. * Returns the VertexData.
  28428. */
  28429. VertexData.prototype.transform = function (matrix) {
  28430. var transformed = BABYLON.Vector3.Zero();
  28431. var index;
  28432. if (this.positions) {
  28433. var position = BABYLON.Vector3.Zero();
  28434. for (index = 0; index < this.positions.length; index += 3) {
  28435. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28436. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28437. this.positions[index] = transformed.x;
  28438. this.positions[index + 1] = transformed.y;
  28439. this.positions[index + 2] = transformed.z;
  28440. }
  28441. }
  28442. if (this.normals) {
  28443. var normal = BABYLON.Vector3.Zero();
  28444. for (index = 0; index < this.normals.length; index += 3) {
  28445. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28446. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28447. this.normals[index] = transformed.x;
  28448. this.normals[index + 1] = transformed.y;
  28449. this.normals[index + 2] = transformed.z;
  28450. }
  28451. }
  28452. if (this.tangents) {
  28453. var tangent = BABYLON.Vector4.Zero();
  28454. var tangentTransformed = BABYLON.Vector4.Zero();
  28455. for (index = 0; index < this.tangents.length; index += 4) {
  28456. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28457. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28458. this.tangents[index] = tangentTransformed.x;
  28459. this.tangents[index + 1] = tangentTransformed.y;
  28460. this.tangents[index + 2] = tangentTransformed.z;
  28461. this.tangents[index + 3] = tangentTransformed.w;
  28462. }
  28463. }
  28464. return this;
  28465. };
  28466. /**
  28467. * Merges the passed VertexData into the current one.
  28468. * Returns the modified VertexData.
  28469. */
  28470. VertexData.prototype.merge = function (other, options) {
  28471. options = options || {};
  28472. if (other.indices) {
  28473. if (!this.indices) {
  28474. this.indices = [];
  28475. }
  28476. var offset = this.positions ? this.positions.length / 3 : 0;
  28477. for (var index = 0; index < other.indices.length; index++) {
  28478. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28479. this.indices.push(other.indices[index] + offset);
  28480. }
  28481. }
  28482. this.positions = this._mergeElement(this.positions, other.positions);
  28483. if (!this.positions) {
  28484. return this;
  28485. }
  28486. var count = this.positions.length / 3;
  28487. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28488. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28489. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28490. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28491. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28492. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28493. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28494. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28495. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28496. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28497. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28498. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28499. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28500. return this;
  28501. };
  28502. VertexData.prototype._mergeElement = function (source, other, length) {
  28503. if (length === void 0) { length = 0; }
  28504. if (!other && !source) {
  28505. return null;
  28506. }
  28507. if (!other) {
  28508. return this._mergeElement(source, new Float32Array(source.length), length);
  28509. }
  28510. if (!source) {
  28511. if (length === 0 || length === other.length) {
  28512. return other;
  28513. }
  28514. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28515. }
  28516. var len = other.length + source.length;
  28517. var isSrcTypedArray = source instanceof Float32Array;
  28518. var isOthTypedArray = other instanceof Float32Array;
  28519. // use non-loop method when the source is Float32Array
  28520. if (isSrcTypedArray) {
  28521. var ret32 = new Float32Array(len);
  28522. ret32.set(source);
  28523. ret32.set(other, source.length);
  28524. return ret32;
  28525. // source is number[], when other is also use concat
  28526. }
  28527. else if (!isOthTypedArray) {
  28528. return source.concat(other);
  28529. // source is a number[], but other is a Float32Array, loop required
  28530. }
  28531. else {
  28532. var ret = source.slice(0); // copy source to a separate array
  28533. for (var i = 0, len = other.length; i < len; i++) {
  28534. ret.push(other[i]);
  28535. }
  28536. return ret;
  28537. }
  28538. };
  28539. /**
  28540. * Serializes the VertexData.
  28541. * Returns a serialized object.
  28542. */
  28543. VertexData.prototype.serialize = function () {
  28544. var serializationObject = this.serialize();
  28545. if (this.positions) {
  28546. serializationObject.positions = this.positions;
  28547. }
  28548. if (this.normals) {
  28549. serializationObject.normals = this.normals;
  28550. }
  28551. if (this.tangents) {
  28552. serializationObject.tangents = this.tangents;
  28553. }
  28554. if (this.uvs) {
  28555. serializationObject.uvs = this.uvs;
  28556. }
  28557. if (this.uvs2) {
  28558. serializationObject.uvs2 = this.uvs2;
  28559. }
  28560. if (this.uvs3) {
  28561. serializationObject.uvs3 = this.uvs3;
  28562. }
  28563. if (this.uvs4) {
  28564. serializationObject.uvs4 = this.uvs4;
  28565. }
  28566. if (this.uvs5) {
  28567. serializationObject.uvs5 = this.uvs5;
  28568. }
  28569. if (this.uvs6) {
  28570. serializationObject.uvs6 = this.uvs6;
  28571. }
  28572. if (this.colors) {
  28573. serializationObject.colors = this.colors;
  28574. }
  28575. if (this.matricesIndices) {
  28576. serializationObject.matricesIndices = this.matricesIndices;
  28577. serializationObject.matricesIndices._isExpanded = true;
  28578. }
  28579. if (this.matricesWeights) {
  28580. serializationObject.matricesWeights = this.matricesWeights;
  28581. }
  28582. if (this.matricesIndicesExtra) {
  28583. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28584. serializationObject.matricesIndicesExtra._isExpanded = true;
  28585. }
  28586. if (this.matricesWeightsExtra) {
  28587. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28588. }
  28589. serializationObject.indices = this.indices;
  28590. return serializationObject;
  28591. };
  28592. // Statics
  28593. /**
  28594. * Returns the object VertexData associated to the passed mesh.
  28595. */
  28596. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28597. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28598. };
  28599. /**
  28600. * Returns the object VertexData associated to the passed geometry.
  28601. */
  28602. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28603. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28604. };
  28605. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28606. var result = new VertexData();
  28607. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28608. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28609. }
  28610. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28611. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28612. }
  28613. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28614. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28615. }
  28616. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28617. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28618. }
  28619. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28620. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28621. }
  28622. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28623. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28624. }
  28625. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28626. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28627. }
  28628. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28629. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28630. }
  28631. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28632. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28633. }
  28634. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28635. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28636. }
  28637. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28638. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28639. }
  28640. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28641. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28642. }
  28643. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28644. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28645. }
  28646. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28647. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28648. }
  28649. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28650. return result;
  28651. };
  28652. /**
  28653. * Creates the vertexData of the Ribbon.
  28654. */
  28655. VertexData.CreateRibbon = function (options) {
  28656. var pathArray = options.pathArray;
  28657. var closeArray = options.closeArray || false;
  28658. var closePath = options.closePath || false;
  28659. var invertUV = options.invertUV || false;
  28660. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28661. var offset = options.offset || defaultOffset;
  28662. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28663. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28664. var customUV = options.uvs;
  28665. var customColors = options.colors;
  28666. var positions = [];
  28667. var indices = [];
  28668. var normals = [];
  28669. var uvs = [];
  28670. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28671. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28672. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28673. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28674. var minlg; // minimal length among all paths from pathArray
  28675. var lg = []; // array of path lengths : nb of vertex per path
  28676. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28677. var p; // path iterator
  28678. var i; // point iterator
  28679. var j; // point iterator
  28680. // if single path in pathArray
  28681. if (pathArray.length < 2) {
  28682. var ar1 = [];
  28683. var ar2 = [];
  28684. for (i = 0; i < pathArray[0].length - offset; i++) {
  28685. ar1.push(pathArray[0][i]);
  28686. ar2.push(pathArray[0][i + offset]);
  28687. }
  28688. pathArray = [ar1, ar2];
  28689. }
  28690. // positions and horizontal distances (u)
  28691. var idc = 0;
  28692. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28693. var path;
  28694. var l;
  28695. minlg = pathArray[0].length;
  28696. var vectlg;
  28697. var dist;
  28698. for (p = 0; p < pathArray.length; p++) {
  28699. uTotalDistance[p] = 0;
  28700. us[p] = [0];
  28701. path = pathArray[p];
  28702. l = path.length;
  28703. minlg = (minlg < l) ? minlg : l;
  28704. j = 0;
  28705. while (j < l) {
  28706. positions.push(path[j].x, path[j].y, path[j].z);
  28707. if (j > 0) {
  28708. vectlg = path[j].subtract(path[j - 1]).length();
  28709. dist = vectlg + uTotalDistance[p];
  28710. us[p].push(dist);
  28711. uTotalDistance[p] = dist;
  28712. }
  28713. j++;
  28714. }
  28715. if (closePath) {
  28716. j--;
  28717. positions.push(path[0].x, path[0].y, path[0].z);
  28718. vectlg = path[j].subtract(path[0]).length();
  28719. dist = vectlg + uTotalDistance[p];
  28720. us[p].push(dist);
  28721. uTotalDistance[p] = dist;
  28722. }
  28723. lg[p] = l + closePathCorr;
  28724. idx[p] = idc;
  28725. idc += (l + closePathCorr);
  28726. }
  28727. // vertical distances (v)
  28728. var path1;
  28729. var path2;
  28730. var vertex1 = null;
  28731. var vertex2 = null;
  28732. for (i = 0; i < minlg + closePathCorr; i++) {
  28733. vTotalDistance[i] = 0;
  28734. vs[i] = [0];
  28735. for (p = 0; p < pathArray.length - 1; p++) {
  28736. path1 = pathArray[p];
  28737. path2 = pathArray[p + 1];
  28738. if (i === minlg) {
  28739. vertex1 = path1[0];
  28740. vertex2 = path2[0];
  28741. }
  28742. else {
  28743. vertex1 = path1[i];
  28744. vertex2 = path2[i];
  28745. }
  28746. vectlg = vertex2.subtract(vertex1).length();
  28747. dist = vectlg + vTotalDistance[i];
  28748. vs[i].push(dist);
  28749. vTotalDistance[i] = dist;
  28750. }
  28751. if (closeArray && vertex2 && vertex1) {
  28752. path1 = pathArray[p];
  28753. path2 = pathArray[0];
  28754. if (i === minlg) {
  28755. vertex2 = path2[0];
  28756. }
  28757. vectlg = vertex2.subtract(vertex1).length();
  28758. dist = vectlg + vTotalDistance[i];
  28759. vTotalDistance[i] = dist;
  28760. }
  28761. }
  28762. // uvs
  28763. var u;
  28764. var v;
  28765. if (customUV) {
  28766. for (p = 0; p < customUV.length; p++) {
  28767. uvs.push(customUV[p].x, customUV[p].y);
  28768. }
  28769. }
  28770. else {
  28771. for (p = 0; p < pathArray.length; p++) {
  28772. for (i = 0; i < minlg + closePathCorr; i++) {
  28773. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28774. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28775. if (invertUV) {
  28776. uvs.push(v, u);
  28777. }
  28778. else {
  28779. uvs.push(u, v);
  28780. }
  28781. }
  28782. }
  28783. }
  28784. // indices
  28785. p = 0; // path index
  28786. var pi = 0; // positions array index
  28787. var l1 = lg[p] - 1; // path1 length
  28788. var l2 = lg[p + 1] - 1; // path2 length
  28789. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28790. var shft = idx[1] - idx[0]; // shift
  28791. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28792. while (pi <= min && p < path1nb) {
  28793. // 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
  28794. indices.push(pi, pi + shft, pi + 1);
  28795. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28796. pi += 1;
  28797. if (pi === min) {
  28798. p++;
  28799. if (p === lg.length - 1) {
  28800. shft = idx[0] - idx[p];
  28801. l1 = lg[p] - 1;
  28802. l2 = lg[0] - 1;
  28803. }
  28804. else {
  28805. shft = idx[p + 1] - idx[p];
  28806. l1 = lg[p] - 1;
  28807. l2 = lg[p + 1] - 1;
  28808. }
  28809. pi = idx[p];
  28810. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28811. }
  28812. }
  28813. // normals
  28814. VertexData.ComputeNormals(positions, indices, normals);
  28815. if (closePath) {
  28816. var indexFirst = 0;
  28817. var indexLast = 0;
  28818. for (p = 0; p < pathArray.length; p++) {
  28819. indexFirst = idx[p] * 3;
  28820. if (p + 1 < pathArray.length) {
  28821. indexLast = (idx[p + 1] - 1) * 3;
  28822. }
  28823. else {
  28824. indexLast = normals.length - 3;
  28825. }
  28826. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28827. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28828. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28829. normals[indexLast] = normals[indexFirst];
  28830. normals[indexLast + 1] = normals[indexFirst + 1];
  28831. normals[indexLast + 2] = normals[indexFirst + 2];
  28832. }
  28833. }
  28834. // sides
  28835. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28836. // Colors
  28837. var colors = null;
  28838. if (customColors) {
  28839. colors = new Float32Array(customColors.length * 4);
  28840. for (var c = 0; c < customColors.length; c++) {
  28841. colors[c * 4] = customColors[c].r;
  28842. colors[c * 4 + 1] = customColors[c].g;
  28843. colors[c * 4 + 2] = customColors[c].b;
  28844. colors[c * 4 + 3] = customColors[c].a;
  28845. }
  28846. }
  28847. // Result
  28848. var vertexData = new VertexData();
  28849. var positions32 = new Float32Array(positions);
  28850. var normals32 = new Float32Array(normals);
  28851. var uvs32 = new Float32Array(uvs);
  28852. vertexData.indices = indices;
  28853. vertexData.positions = positions32;
  28854. vertexData.normals = normals32;
  28855. vertexData.uvs = uvs32;
  28856. if (colors) {
  28857. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28858. }
  28859. if (closePath) {
  28860. vertexData._idx = idx;
  28861. }
  28862. return vertexData;
  28863. };
  28864. /**
  28865. * Creates the VertexData of the Box.
  28866. */
  28867. VertexData.CreateBox = function (options) {
  28868. var normalsSource = [
  28869. new BABYLON.Vector3(0, 0, 1),
  28870. new BABYLON.Vector3(0, 0, -1),
  28871. new BABYLON.Vector3(1, 0, 0),
  28872. new BABYLON.Vector3(-1, 0, 0),
  28873. new BABYLON.Vector3(0, 1, 0),
  28874. new BABYLON.Vector3(0, -1, 0)
  28875. ];
  28876. var indices = [];
  28877. var positions = [];
  28878. var normals = [];
  28879. var uvs = [];
  28880. var width = options.width || options.size || 1;
  28881. var height = options.height || options.size || 1;
  28882. var depth = options.depth || options.size || 1;
  28883. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28884. var faceUV = options.faceUV || new Array(6);
  28885. var faceColors = options.faceColors;
  28886. var colors = [];
  28887. // default face colors and UV if undefined
  28888. for (var f = 0; f < 6; f++) {
  28889. if (faceUV[f] === undefined) {
  28890. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28891. }
  28892. if (faceColors && faceColors[f] === undefined) {
  28893. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28894. }
  28895. }
  28896. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28897. // Create each face in turn.
  28898. for (var index = 0; index < normalsSource.length; index++) {
  28899. var normal = normalsSource[index];
  28900. // Get two vectors perpendicular to the face normal and to each other.
  28901. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28902. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28903. // Six indices (two triangles) per face.
  28904. var verticesLength = positions.length / 3;
  28905. indices.push(verticesLength);
  28906. indices.push(verticesLength + 1);
  28907. indices.push(verticesLength + 2);
  28908. indices.push(verticesLength);
  28909. indices.push(verticesLength + 2);
  28910. indices.push(verticesLength + 3);
  28911. // Four vertices per face.
  28912. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28913. positions.push(vertex.x, vertex.y, vertex.z);
  28914. normals.push(normal.x, normal.y, normal.z);
  28915. uvs.push(faceUV[index].z, faceUV[index].w);
  28916. if (faceColors) {
  28917. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28918. }
  28919. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28920. positions.push(vertex.x, vertex.y, vertex.z);
  28921. normals.push(normal.x, normal.y, normal.z);
  28922. uvs.push(faceUV[index].x, faceUV[index].w);
  28923. if (faceColors) {
  28924. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28925. }
  28926. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28927. positions.push(vertex.x, vertex.y, vertex.z);
  28928. normals.push(normal.x, normal.y, normal.z);
  28929. uvs.push(faceUV[index].x, faceUV[index].y);
  28930. if (faceColors) {
  28931. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28932. }
  28933. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28934. positions.push(vertex.x, vertex.y, vertex.z);
  28935. normals.push(normal.x, normal.y, normal.z);
  28936. uvs.push(faceUV[index].z, faceUV[index].y);
  28937. if (faceColors) {
  28938. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28939. }
  28940. }
  28941. // sides
  28942. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28943. // Result
  28944. var vertexData = new VertexData();
  28945. vertexData.indices = indices;
  28946. vertexData.positions = positions;
  28947. vertexData.normals = normals;
  28948. vertexData.uvs = uvs;
  28949. if (faceColors) {
  28950. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28951. vertexData.colors = totalColors;
  28952. }
  28953. return vertexData;
  28954. };
  28955. /**
  28956. * Creates the VertexData of the Sphere.
  28957. */
  28958. VertexData.CreateSphere = function (options) {
  28959. var segments = options.segments || 32;
  28960. var diameterX = options.diameterX || options.diameter || 1;
  28961. var diameterY = options.diameterY || options.diameter || 1;
  28962. var diameterZ = options.diameterZ || options.diameter || 1;
  28963. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28964. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28965. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28966. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28967. var totalZRotationSteps = 2 + segments;
  28968. var totalYRotationSteps = 2 * totalZRotationSteps;
  28969. var indices = [];
  28970. var positions = [];
  28971. var normals = [];
  28972. var uvs = [];
  28973. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28974. var normalizedZ = zRotationStep / totalZRotationSteps;
  28975. var angleZ = normalizedZ * Math.PI * slice;
  28976. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28977. var normalizedY = yRotationStep / totalYRotationSteps;
  28978. var angleY = normalizedY * Math.PI * 2 * arc;
  28979. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28980. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28981. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28982. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28983. var vertex = complete.multiply(radius);
  28984. var normal = complete.divide(radius).normalize();
  28985. positions.push(vertex.x, vertex.y, vertex.z);
  28986. normals.push(normal.x, normal.y, normal.z);
  28987. uvs.push(normalizedY, normalizedZ);
  28988. }
  28989. if (zRotationStep > 0) {
  28990. var verticesCount = positions.length / 3;
  28991. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28992. indices.push((firstIndex));
  28993. indices.push((firstIndex + 1));
  28994. indices.push(firstIndex + totalYRotationSteps + 1);
  28995. indices.push((firstIndex + totalYRotationSteps + 1));
  28996. indices.push((firstIndex + 1));
  28997. indices.push((firstIndex + totalYRotationSteps + 2));
  28998. }
  28999. }
  29000. }
  29001. // Sides
  29002. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29003. // Result
  29004. var vertexData = new VertexData();
  29005. vertexData.indices = indices;
  29006. vertexData.positions = positions;
  29007. vertexData.normals = normals;
  29008. vertexData.uvs = uvs;
  29009. return vertexData;
  29010. };
  29011. /**
  29012. * Creates the VertexData of the Cylinder or Cone.
  29013. */
  29014. VertexData.CreateCylinder = function (options) {
  29015. var height = options.height || 2;
  29016. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29017. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29018. var tessellation = options.tessellation || 24;
  29019. var subdivisions = options.subdivisions || 1;
  29020. var hasRings = options.hasRings ? true : false;
  29021. var enclose = options.enclose ? true : false;
  29022. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29023. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29024. var faceUV = options.faceUV || new Array(3);
  29025. var faceColors = options.faceColors;
  29026. // default face colors and UV if undefined
  29027. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29028. var ringNb = (hasRings) ? subdivisions : 1;
  29029. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29030. var f;
  29031. for (f = 0; f < surfaceNb; f++) {
  29032. if (faceColors && faceColors[f] === undefined) {
  29033. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29034. }
  29035. }
  29036. for (f = 0; f < surfaceNb; f++) {
  29037. if (faceUV && faceUV[f] === undefined) {
  29038. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29039. }
  29040. }
  29041. var indices = new Array();
  29042. var positions = new Array();
  29043. var normals = new Array();
  29044. var uvs = new Array();
  29045. var colors = new Array();
  29046. var angle_step = Math.PI * 2 * arc / tessellation;
  29047. var angle;
  29048. var h;
  29049. var radius;
  29050. var tan = (diameterBottom - diameterTop) / 2 / height;
  29051. var ringVertex = BABYLON.Vector3.Zero();
  29052. var ringNormal = BABYLON.Vector3.Zero();
  29053. var ringFirstVertex = BABYLON.Vector3.Zero();
  29054. var ringFirstNormal = BABYLON.Vector3.Zero();
  29055. var quadNormal = BABYLON.Vector3.Zero();
  29056. var Y = BABYLON.Axis.Y;
  29057. // positions, normals, uvs
  29058. var i;
  29059. var j;
  29060. var r;
  29061. var ringIdx = 1;
  29062. var s = 1; // surface index
  29063. var cs = 0;
  29064. var v = 0;
  29065. for (i = 0; i <= subdivisions; i++) {
  29066. h = i / subdivisions;
  29067. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29068. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29069. for (r = 0; r < ringIdx; r++) {
  29070. if (hasRings) {
  29071. s += r;
  29072. }
  29073. if (enclose) {
  29074. s += 2 * r;
  29075. }
  29076. for (j = 0; j <= tessellation; j++) {
  29077. angle = j * angle_step;
  29078. // position
  29079. ringVertex.x = Math.cos(-angle) * radius;
  29080. ringVertex.y = -height / 2 + h * height;
  29081. ringVertex.z = Math.sin(-angle) * radius;
  29082. // normal
  29083. if (diameterTop === 0 && i === subdivisions) {
  29084. // if no top cap, reuse former normals
  29085. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29086. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29087. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29088. }
  29089. else {
  29090. ringNormal.x = ringVertex.x;
  29091. ringNormal.z = ringVertex.z;
  29092. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29093. ringNormal.normalize();
  29094. }
  29095. // keep first ring vertex values for enclose
  29096. if (j === 0) {
  29097. ringFirstVertex.copyFrom(ringVertex);
  29098. ringFirstNormal.copyFrom(ringNormal);
  29099. }
  29100. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29101. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29102. if (hasRings) {
  29103. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29104. }
  29105. else {
  29106. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29107. }
  29108. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29109. if (faceColors) {
  29110. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29111. }
  29112. }
  29113. // if enclose, add four vertices and their dedicated normals
  29114. if (arc !== 1 && enclose) {
  29115. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29116. positions.push(0, ringVertex.y, 0);
  29117. positions.push(0, ringVertex.y, 0);
  29118. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29119. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29120. quadNormal.normalize();
  29121. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29122. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29123. quadNormal.normalize();
  29124. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29125. if (hasRings) {
  29126. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29127. }
  29128. else {
  29129. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29130. }
  29131. uvs.push(faceUV[s + 1].x, v);
  29132. uvs.push(faceUV[s + 1].z, v);
  29133. if (hasRings) {
  29134. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29135. }
  29136. else {
  29137. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29138. }
  29139. uvs.push(faceUV[s + 2].x, v);
  29140. uvs.push(faceUV[s + 2].z, v);
  29141. if (faceColors) {
  29142. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29143. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29144. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29145. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29146. }
  29147. }
  29148. if (cs !== s) {
  29149. cs = s;
  29150. }
  29151. }
  29152. }
  29153. // indices
  29154. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29155. var s;
  29156. i = 0;
  29157. for (s = 0; s < subdivisions; s++) {
  29158. var i0 = 0;
  29159. var i1 = 0;
  29160. var i2 = 0;
  29161. var i3 = 0;
  29162. for (j = 0; j < tessellation; j++) {
  29163. i0 = i * (e + 1) + j;
  29164. i1 = (i + 1) * (e + 1) + j;
  29165. i2 = i * (e + 1) + (j + 1);
  29166. i3 = (i + 1) * (e + 1) + (j + 1);
  29167. indices.push(i0, i1, i2);
  29168. indices.push(i3, i2, i1);
  29169. }
  29170. if (arc !== 1 && enclose) {
  29171. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29172. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29173. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29174. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29175. }
  29176. i = (hasRings) ? (i + 2) : (i + 1);
  29177. }
  29178. // Caps
  29179. var createCylinderCap = function (isTop) {
  29180. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29181. if (radius === 0) {
  29182. return;
  29183. }
  29184. // Cap positions, normals & uvs
  29185. var angle;
  29186. var circleVector;
  29187. var i;
  29188. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29189. var c = null;
  29190. if (faceColors) {
  29191. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29192. }
  29193. // cap center
  29194. var vbase = positions.length / 3;
  29195. var offset = isTop ? height / 2 : -height / 2;
  29196. var center = new BABYLON.Vector3(0, offset, 0);
  29197. positions.push(center.x, center.y, center.z);
  29198. normals.push(0, isTop ? 1 : -1, 0);
  29199. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29200. if (c) {
  29201. colors.push(c.r, c.g, c.b, c.a);
  29202. }
  29203. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29204. for (i = 0; i <= tessellation; i++) {
  29205. angle = Math.PI * 2 * i * arc / tessellation;
  29206. var cos = Math.cos(-angle);
  29207. var sin = Math.sin(-angle);
  29208. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29209. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29210. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29211. normals.push(0, isTop ? 1 : -1, 0);
  29212. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29213. if (c) {
  29214. colors.push(c.r, c.g, c.b, c.a);
  29215. }
  29216. }
  29217. // Cap indices
  29218. for (i = 0; i < tessellation; i++) {
  29219. if (!isTop) {
  29220. indices.push(vbase);
  29221. indices.push(vbase + (i + 1));
  29222. indices.push(vbase + (i + 2));
  29223. }
  29224. else {
  29225. indices.push(vbase);
  29226. indices.push(vbase + (i + 2));
  29227. indices.push(vbase + (i + 1));
  29228. }
  29229. }
  29230. };
  29231. // add caps to geometry
  29232. createCylinderCap(false);
  29233. createCylinderCap(true);
  29234. // Sides
  29235. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29236. var vertexData = new VertexData();
  29237. vertexData.indices = indices;
  29238. vertexData.positions = positions;
  29239. vertexData.normals = normals;
  29240. vertexData.uvs = uvs;
  29241. if (faceColors) {
  29242. vertexData.colors = colors;
  29243. }
  29244. return vertexData;
  29245. };
  29246. /**
  29247. * Creates the VertexData of the Torus.
  29248. */
  29249. VertexData.CreateTorus = function (options) {
  29250. var indices = [];
  29251. var positions = [];
  29252. var normals = [];
  29253. var uvs = [];
  29254. var diameter = options.diameter || 1;
  29255. var thickness = options.thickness || 0.5;
  29256. var tessellation = options.tessellation || 16;
  29257. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29258. var stride = tessellation + 1;
  29259. for (var i = 0; i <= tessellation; i++) {
  29260. var u = i / tessellation;
  29261. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29262. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29263. for (var j = 0; j <= tessellation; j++) {
  29264. var v = 1 - j / tessellation;
  29265. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29266. var dx = Math.cos(innerAngle);
  29267. var dy = Math.sin(innerAngle);
  29268. // Create a vertex.
  29269. var normal = new BABYLON.Vector3(dx, dy, 0);
  29270. var position = normal.scale(thickness / 2);
  29271. var textureCoordinate = new BABYLON.Vector2(u, v);
  29272. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29273. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29274. positions.push(position.x, position.y, position.z);
  29275. normals.push(normal.x, normal.y, normal.z);
  29276. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29277. // And create indices for two triangles.
  29278. var nextI = (i + 1) % stride;
  29279. var nextJ = (j + 1) % stride;
  29280. indices.push(i * stride + j);
  29281. indices.push(i * stride + nextJ);
  29282. indices.push(nextI * stride + j);
  29283. indices.push(i * stride + nextJ);
  29284. indices.push(nextI * stride + nextJ);
  29285. indices.push(nextI * stride + j);
  29286. }
  29287. }
  29288. // Sides
  29289. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29290. // Result
  29291. var vertexData = new VertexData();
  29292. vertexData.indices = indices;
  29293. vertexData.positions = positions;
  29294. vertexData.normals = normals;
  29295. vertexData.uvs = uvs;
  29296. return vertexData;
  29297. };
  29298. /**
  29299. * Creates the VertexData of the LineSystem.
  29300. */
  29301. VertexData.CreateLineSystem = function (options) {
  29302. var indices = [];
  29303. var positions = [];
  29304. var lines = options.lines;
  29305. var idx = 0;
  29306. for (var l = 0; l < lines.length; l++) {
  29307. var points = lines[l];
  29308. for (var index = 0; index < points.length; index++) {
  29309. positions.push(points[index].x, points[index].y, points[index].z);
  29310. if (index > 0) {
  29311. indices.push(idx - 1);
  29312. indices.push(idx);
  29313. }
  29314. idx++;
  29315. }
  29316. }
  29317. var vertexData = new VertexData();
  29318. vertexData.indices = indices;
  29319. vertexData.positions = positions;
  29320. return vertexData;
  29321. };
  29322. /**
  29323. * Create the VertexData of the DashedLines.
  29324. */
  29325. VertexData.CreateDashedLines = function (options) {
  29326. var dashSize = options.dashSize || 3;
  29327. var gapSize = options.gapSize || 1;
  29328. var dashNb = options.dashNb || 200;
  29329. var points = options.points;
  29330. var positions = new Array();
  29331. var indices = new Array();
  29332. var curvect = BABYLON.Vector3.Zero();
  29333. var lg = 0;
  29334. var nb = 0;
  29335. var shft = 0;
  29336. var dashshft = 0;
  29337. var curshft = 0;
  29338. var idx = 0;
  29339. var i = 0;
  29340. for (i = 0; i < points.length - 1; i++) {
  29341. points[i + 1].subtractToRef(points[i], curvect);
  29342. lg += curvect.length();
  29343. }
  29344. shft = lg / dashNb;
  29345. dashshft = dashSize * shft / (dashSize + gapSize);
  29346. for (i = 0; i < points.length - 1; i++) {
  29347. points[i + 1].subtractToRef(points[i], curvect);
  29348. nb = Math.floor(curvect.length() / shft);
  29349. curvect.normalize();
  29350. for (var j = 0; j < nb; j++) {
  29351. curshft = shft * j;
  29352. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29353. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29354. indices.push(idx, idx + 1);
  29355. idx += 2;
  29356. }
  29357. }
  29358. // Result
  29359. var vertexData = new VertexData();
  29360. vertexData.positions = positions;
  29361. vertexData.indices = indices;
  29362. return vertexData;
  29363. };
  29364. /**
  29365. * Creates the VertexData of the Ground.
  29366. */
  29367. VertexData.CreateGround = function (options) {
  29368. var indices = [];
  29369. var positions = [];
  29370. var normals = [];
  29371. var uvs = [];
  29372. var row, col;
  29373. var width = options.width || 1;
  29374. var height = options.height || 1;
  29375. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29376. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29377. for (row = 0; row <= subdivisionsY; row++) {
  29378. for (col = 0; col <= subdivisionsX; col++) {
  29379. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29380. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29381. positions.push(position.x, position.y, position.z);
  29382. normals.push(normal.x, normal.y, normal.z);
  29383. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29384. }
  29385. }
  29386. for (row = 0; row < subdivisionsY; row++) {
  29387. for (col = 0; col < subdivisionsX; col++) {
  29388. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29389. indices.push(col + 1 + row * (subdivisionsX + 1));
  29390. indices.push(col + row * (subdivisionsX + 1));
  29391. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29392. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29393. indices.push(col + row * (subdivisionsX + 1));
  29394. }
  29395. }
  29396. // Result
  29397. var vertexData = new VertexData();
  29398. vertexData.indices = indices;
  29399. vertexData.positions = positions;
  29400. vertexData.normals = normals;
  29401. vertexData.uvs = uvs;
  29402. return vertexData;
  29403. };
  29404. /**
  29405. * Creates the VertexData of the TiledGround.
  29406. */
  29407. VertexData.CreateTiledGround = function (options) {
  29408. var xmin = options.xmin || -1.0;
  29409. var zmin = options.zmin || -1.0;
  29410. var xmax = options.xmax || 1.0;
  29411. var zmax = options.zmax || 1.0;
  29412. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29413. var precision = options.precision || { w: 1, h: 1 };
  29414. var indices = new Array();
  29415. var positions = new Array();
  29416. var normals = new Array();
  29417. var uvs = new Array();
  29418. var row, col, tileRow, tileCol;
  29419. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29420. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29421. precision.w = (precision.w < 1) ? 1 : precision.w;
  29422. precision.h = (precision.h < 1) ? 1 : precision.h;
  29423. var tileSize = {
  29424. 'w': (xmax - xmin) / subdivisions.w,
  29425. 'h': (zmax - zmin) / subdivisions.h
  29426. };
  29427. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29428. // Indices
  29429. var base = positions.length / 3;
  29430. var rowLength = precision.w + 1;
  29431. for (row = 0; row < precision.h; row++) {
  29432. for (col = 0; col < precision.w; col++) {
  29433. var square = [
  29434. base + col + row * rowLength,
  29435. base + (col + 1) + row * rowLength,
  29436. base + (col + 1) + (row + 1) * rowLength,
  29437. base + col + (row + 1) * rowLength
  29438. ];
  29439. indices.push(square[1]);
  29440. indices.push(square[2]);
  29441. indices.push(square[3]);
  29442. indices.push(square[0]);
  29443. indices.push(square[1]);
  29444. indices.push(square[3]);
  29445. }
  29446. }
  29447. // Position, normals and uvs
  29448. var position = BABYLON.Vector3.Zero();
  29449. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29450. for (row = 0; row <= precision.h; row++) {
  29451. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29452. for (col = 0; col <= precision.w; col++) {
  29453. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29454. position.y = 0;
  29455. positions.push(position.x, position.y, position.z);
  29456. normals.push(normal.x, normal.y, normal.z);
  29457. uvs.push(col / precision.w, row / precision.h);
  29458. }
  29459. }
  29460. }
  29461. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29462. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29463. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29464. }
  29465. }
  29466. // Result
  29467. var vertexData = new VertexData();
  29468. vertexData.indices = indices;
  29469. vertexData.positions = positions;
  29470. vertexData.normals = normals;
  29471. vertexData.uvs = uvs;
  29472. return vertexData;
  29473. };
  29474. /**
  29475. * Creates the VertexData of the Ground designed from a heightmap.
  29476. */
  29477. VertexData.CreateGroundFromHeightMap = function (options) {
  29478. var indices = [];
  29479. var positions = [];
  29480. var normals = [];
  29481. var uvs = [];
  29482. var row, col;
  29483. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29484. // Vertices
  29485. for (row = 0; row <= options.subdivisions; row++) {
  29486. for (col = 0; col <= options.subdivisions; col++) {
  29487. 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));
  29488. // Compute height
  29489. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29490. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29491. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29492. var r = options.buffer[pos] / 255.0;
  29493. var g = options.buffer[pos + 1] / 255.0;
  29494. var b = options.buffer[pos + 2] / 255.0;
  29495. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29496. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29497. // Add vertex
  29498. positions.push(position.x, position.y, position.z);
  29499. normals.push(0, 0, 0);
  29500. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29501. }
  29502. }
  29503. // Indices
  29504. for (row = 0; row < options.subdivisions; row++) {
  29505. for (col = 0; col < options.subdivisions; col++) {
  29506. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29507. indices.push(col + 1 + row * (options.subdivisions + 1));
  29508. indices.push(col + row * (options.subdivisions + 1));
  29509. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29510. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29511. indices.push(col + row * (options.subdivisions + 1));
  29512. }
  29513. }
  29514. // Normals
  29515. VertexData.ComputeNormals(positions, indices, normals);
  29516. // Result
  29517. var vertexData = new VertexData();
  29518. vertexData.indices = indices;
  29519. vertexData.positions = positions;
  29520. vertexData.normals = normals;
  29521. vertexData.uvs = uvs;
  29522. return vertexData;
  29523. };
  29524. /**
  29525. * Creates the VertexData of the Plane.
  29526. */
  29527. VertexData.CreatePlane = function (options) {
  29528. var indices = [];
  29529. var positions = [];
  29530. var normals = [];
  29531. var uvs = [];
  29532. var width = options.width || options.size || 1;
  29533. var height = options.height || options.size || 1;
  29534. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29535. // Vertices
  29536. var halfWidth = width / 2.0;
  29537. var halfHeight = height / 2.0;
  29538. positions.push(-halfWidth, -halfHeight, 0);
  29539. normals.push(0, 0, -1.0);
  29540. uvs.push(0.0, 0.0);
  29541. positions.push(halfWidth, -halfHeight, 0);
  29542. normals.push(0, 0, -1.0);
  29543. uvs.push(1.0, 0.0);
  29544. positions.push(halfWidth, halfHeight, 0);
  29545. normals.push(0, 0, -1.0);
  29546. uvs.push(1.0, 1.0);
  29547. positions.push(-halfWidth, halfHeight, 0);
  29548. normals.push(0, 0, -1.0);
  29549. uvs.push(0.0, 1.0);
  29550. // Indices
  29551. indices.push(0);
  29552. indices.push(1);
  29553. indices.push(2);
  29554. indices.push(0);
  29555. indices.push(2);
  29556. indices.push(3);
  29557. // Sides
  29558. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29559. // Result
  29560. var vertexData = new VertexData();
  29561. vertexData.indices = indices;
  29562. vertexData.positions = positions;
  29563. vertexData.normals = normals;
  29564. vertexData.uvs = uvs;
  29565. return vertexData;
  29566. };
  29567. /**
  29568. * Creates the VertexData of the Disc or regular Polygon.
  29569. */
  29570. VertexData.CreateDisc = function (options) {
  29571. var positions = new Array();
  29572. var indices = new Array();
  29573. var normals = new Array();
  29574. var uvs = new Array();
  29575. var radius = options.radius || 0.5;
  29576. var tessellation = options.tessellation || 64;
  29577. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29578. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29579. // positions and uvs
  29580. positions.push(0, 0, 0); // disc center first
  29581. uvs.push(0.5, 0.5);
  29582. var theta = Math.PI * 2 * arc;
  29583. var step = theta / tessellation;
  29584. for (var a = 0; a < theta; a += step) {
  29585. var x = Math.cos(a);
  29586. var y = Math.sin(a);
  29587. var u = (x + 1) / 2;
  29588. var v = (1 - y) / 2;
  29589. positions.push(radius * x, radius * y, 0);
  29590. uvs.push(u, v);
  29591. }
  29592. if (arc === 1) {
  29593. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29594. uvs.push(uvs[2], uvs[3]);
  29595. }
  29596. //indices
  29597. var vertexNb = positions.length / 3;
  29598. for (var i = 1; i < vertexNb - 1; i++) {
  29599. indices.push(i + 1, 0, i);
  29600. }
  29601. // result
  29602. VertexData.ComputeNormals(positions, indices, normals);
  29603. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29604. var vertexData = new VertexData();
  29605. vertexData.indices = indices;
  29606. vertexData.positions = positions;
  29607. vertexData.normals = normals;
  29608. vertexData.uvs = uvs;
  29609. return vertexData;
  29610. };
  29611. /**
  29612. * Re-creates the VertexData of the Polygon for sideOrientation.
  29613. */
  29614. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29615. var faceUV = fUV || new Array(3);
  29616. var faceColors = fColors;
  29617. var colors = [];
  29618. // default face colors and UV if undefined
  29619. for (var f = 0; f < 3; f++) {
  29620. if (faceUV[f] === undefined) {
  29621. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29622. }
  29623. if (faceColors && faceColors[f] === undefined) {
  29624. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29625. }
  29626. }
  29627. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29628. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29629. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29630. var indices = polygon.getIndices();
  29631. // set face colours and textures
  29632. var idx = 0;
  29633. var face = 0;
  29634. for (var index = 0; index < normals.length; index += 3) {
  29635. //Edge Face no. 1
  29636. if (Math.abs(normals[index + 1]) < 0.001) {
  29637. face = 1;
  29638. }
  29639. //Top Face no. 0
  29640. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29641. face = 0;
  29642. }
  29643. //Bottom Face no. 2
  29644. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29645. face = 2;
  29646. }
  29647. idx = index / 3;
  29648. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29649. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29650. if (faceColors) {
  29651. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29652. }
  29653. }
  29654. // sides
  29655. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29656. // Result
  29657. var vertexData = new VertexData();
  29658. vertexData.indices = indices;
  29659. vertexData.positions = positions;
  29660. vertexData.normals = normals;
  29661. vertexData.uvs = uvs;
  29662. if (faceColors) {
  29663. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29664. vertexData.colors = totalColors;
  29665. }
  29666. return vertexData;
  29667. };
  29668. /**
  29669. * Creates the VertexData of the IcoSphere.
  29670. */
  29671. VertexData.CreateIcoSphere = function (options) {
  29672. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29673. var radius = options.radius || 1;
  29674. var flat = (options.flat === undefined) ? true : options.flat;
  29675. var subdivisions = options.subdivisions || 4;
  29676. var radiusX = options.radiusX || radius;
  29677. var radiusY = options.radiusY || radius;
  29678. var radiusZ = options.radiusZ || radius;
  29679. var t = (1 + Math.sqrt(5)) / 2;
  29680. // 12 vertex x,y,z
  29681. var ico_vertices = [
  29682. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29683. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29684. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29685. ];
  29686. // index of 3 vertex makes a face of icopshere
  29687. var ico_indices = [
  29688. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29689. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29690. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29691. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29692. ];
  29693. // vertex for uv have aliased position, not for UV
  29694. var vertices_unalias_id = [
  29695. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29696. // vertex alias
  29697. 0,
  29698. 2,
  29699. 3,
  29700. 3,
  29701. 3,
  29702. 4,
  29703. 7,
  29704. 8,
  29705. 9,
  29706. 9,
  29707. 10,
  29708. 11 // 23: B + 12
  29709. ];
  29710. // uv as integer step (not pixels !)
  29711. var ico_vertexuv = [
  29712. 5, 1, 3, 1, 6, 4, 0, 0,
  29713. 5, 3, 4, 2, 2, 2, 4, 0,
  29714. 2, 0, 1, 1, 6, 0, 6, 2,
  29715. // vertex alias (for same vertex on different faces)
  29716. 0, 4,
  29717. 3, 3,
  29718. 4, 4,
  29719. 3, 1,
  29720. 4, 2,
  29721. 4, 4,
  29722. 0, 2,
  29723. 1, 1,
  29724. 2, 2,
  29725. 3, 3,
  29726. 1, 3,
  29727. 2, 4 // 23: B + 12
  29728. ];
  29729. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29730. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29731. // First island of uv mapping
  29732. // v = 4h 3+ 2
  29733. // v = 3h 9+ 4
  29734. // v = 2h 9+ 5 B
  29735. // v = 1h 9 1 0
  29736. // v = 0h 3 8 7 A
  29737. // u = 0 1 2 3 4 5 6 *a
  29738. // Second island of uv mapping
  29739. // v = 4h 0+ B+ 4+
  29740. // v = 3h A+ 2+
  29741. // v = 2h 7+ 6 3+
  29742. // v = 1h 8+ 3+
  29743. // v = 0h
  29744. // u = 0 1 2 3 4 5 6 *a
  29745. // Face layout on texture UV mapping
  29746. // ============
  29747. // \ 4 /\ 16 / ======
  29748. // \ / \ / /\ 11 /
  29749. // \/ 7 \/ / \ /
  29750. // ======= / 10 \/
  29751. // /\ 17 /\ =======
  29752. // / \ / \ \ 15 /\
  29753. // / 8 \/ 12 \ \ / \
  29754. // ============ \/ 6 \
  29755. // \ 18 /\ ============
  29756. // \ / \ \ 5 /\ 0 /
  29757. // \/ 13 \ \ / \ /
  29758. // ======= \/ 1 \/
  29759. // =============
  29760. // /\ 19 /\ 2 /\
  29761. // / \ / \ / \
  29762. // / 14 \/ 9 \/ 3 \
  29763. // ===================
  29764. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29765. var ustep = 138 / 1024;
  29766. var vstep = 239 / 1024;
  29767. var uoffset = 60 / 1024;
  29768. var voffset = 26 / 1024;
  29769. // Second island should have margin, not to touch the first island
  29770. // avoid any borderline artefact in pixel rounding
  29771. var island_u_offset = -40 / 1024;
  29772. var island_v_offset = +20 / 1024;
  29773. // face is either island 0 or 1 :
  29774. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29775. var island = [
  29776. 0, 0, 0, 0, 1,
  29777. 0, 0, 1, 1, 0,
  29778. 0, 0, 1, 1, 0,
  29779. 0, 1, 1, 1, 0 // 15 - 19
  29780. ];
  29781. var indices = new Array();
  29782. var positions = new Array();
  29783. var normals = new Array();
  29784. var uvs = new Array();
  29785. var current_indice = 0;
  29786. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29787. var face_vertex_pos = new Array(3);
  29788. var face_vertex_uv = new Array(3);
  29789. var v012;
  29790. for (v012 = 0; v012 < 3; v012++) {
  29791. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29792. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29793. }
  29794. // create all with normals
  29795. for (var face = 0; face < 20; face++) {
  29796. // 3 vertex per face
  29797. for (v012 = 0; v012 < 3; v012++) {
  29798. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29799. var v_id = ico_indices[3 * face + v012];
  29800. // vertex have 3D position (x,y,z)
  29801. 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]);
  29802. // Normalize to get normal, then scale to radius
  29803. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29804. // uv Coordinates from vertex ID
  29805. 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);
  29806. }
  29807. // Subdivide the face (interpolate pos, norm, uv)
  29808. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29809. // - norm is linear interpolation of vertex corner normal
  29810. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29811. // - uv is linear interpolation
  29812. //
  29813. // Topology is as below for sub-divide by 2
  29814. // vertex shown as v0,v1,v2
  29815. // interp index is i1 to progress in range [v0,v1[
  29816. // interp index is i2 to progress in range [v0,v2[
  29817. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29818. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29819. //
  29820. //
  29821. // i2 v2
  29822. // ^ ^
  29823. // / / \
  29824. // / / \
  29825. // / / \
  29826. // / / (0,1) \
  29827. // / #---------\
  29828. // / / \ (0,0)'/ \
  29829. // / / \ / \
  29830. // / / \ / \
  29831. // / / (0,0) \ / (1,0) \
  29832. // / #---------#---------\
  29833. // v0 v1
  29834. //
  29835. // --------------------> i1
  29836. //
  29837. // interp of (i1,i2):
  29838. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29839. // along i1 : lerp(x0,x1, i1/(S-i2))
  29840. //
  29841. // centroid of triangle is needed to get help normal computation
  29842. // (c1,c2) are used for centroid location
  29843. var interp_vertex = function (i1, i2, c1, c2) {
  29844. // vertex is interpolated from
  29845. // - face_vertex_pos[0..2]
  29846. // - face_vertex_uv[0..2]
  29847. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29848. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29849. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29850. pos_interp.normalize();
  29851. var vertex_normal;
  29852. if (flat) {
  29853. // in flat mode, recalculate normal as face centroid normal
  29854. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29855. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29856. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29857. }
  29858. else {
  29859. // in smooth mode, recalculate normal from each single vertex position
  29860. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29861. }
  29862. // Vertex normal need correction due to X,Y,Z radius scaling
  29863. vertex_normal.x /= radiusX;
  29864. vertex_normal.y /= radiusY;
  29865. vertex_normal.z /= radiusZ;
  29866. vertex_normal.normalize();
  29867. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29868. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29869. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29870. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29871. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29872. uvs.push(uv_interp.x, uv_interp.y);
  29873. // push each vertex has member of a face
  29874. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29875. indices.push(current_indice);
  29876. current_indice++;
  29877. };
  29878. for (var i2 = 0; i2 < subdivisions; i2++) {
  29879. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29880. // face : (i1,i2) for /\ :
  29881. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29882. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29883. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29884. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29885. if (i1 + i2 + 1 < subdivisions) {
  29886. // face : (i1,i2)' for \/ :
  29887. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29888. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29889. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29890. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29891. }
  29892. }
  29893. }
  29894. }
  29895. // Sides
  29896. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29897. // Result
  29898. var vertexData = new VertexData();
  29899. vertexData.indices = indices;
  29900. vertexData.positions = positions;
  29901. vertexData.normals = normals;
  29902. vertexData.uvs = uvs;
  29903. return vertexData;
  29904. };
  29905. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29906. /**
  29907. * Creates the VertexData of the Polyhedron.
  29908. */
  29909. VertexData.CreatePolyhedron = function (options) {
  29910. // provided polyhedron types :
  29911. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29912. // 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)
  29913. var polyhedra = [];
  29914. 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]] };
  29915. 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]] };
  29916. polyhedra[2] = {
  29917. 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]],
  29918. 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]]
  29919. };
  29920. polyhedra[3] = {
  29921. 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]],
  29922. 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]]
  29923. };
  29924. polyhedra[4] = {
  29925. 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]],
  29926. 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]]
  29927. };
  29928. 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]] };
  29929. 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]] };
  29930. 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]] };
  29931. 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]] };
  29932. 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]] };
  29933. 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]] };
  29934. 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]] };
  29935. 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]] };
  29936. 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]] };
  29937. polyhedra[14] = {
  29938. 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]],
  29939. 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]]
  29940. };
  29941. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29942. var size = options.size;
  29943. var sizeX = options.sizeX || size || 1;
  29944. var sizeY = options.sizeY || size || 1;
  29945. var sizeZ = options.sizeZ || size || 1;
  29946. var data = options.custom || polyhedra[type];
  29947. var nbfaces = data.face.length;
  29948. var faceUV = options.faceUV || new Array(nbfaces);
  29949. var faceColors = options.faceColors;
  29950. var flat = (options.flat === undefined) ? true : options.flat;
  29951. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29952. var positions = new Array();
  29953. var indices = new Array();
  29954. var normals = new Array();
  29955. var uvs = new Array();
  29956. var colors = new Array();
  29957. var index = 0;
  29958. var faceIdx = 0; // face cursor in the array "indexes"
  29959. var indexes = new Array();
  29960. var i = 0;
  29961. var f = 0;
  29962. var u, v, ang, x, y, tmp;
  29963. // default face colors and UV if undefined
  29964. if (flat) {
  29965. for (f = 0; f < nbfaces; f++) {
  29966. if (faceColors && faceColors[f] === undefined) {
  29967. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29968. }
  29969. if (faceUV && faceUV[f] === undefined) {
  29970. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29971. }
  29972. }
  29973. }
  29974. if (!flat) {
  29975. for (i = 0; i < data.vertex.length; i++) {
  29976. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29977. uvs.push(0, 0);
  29978. }
  29979. for (f = 0; f < nbfaces; f++) {
  29980. for (i = 0; i < data.face[f].length - 2; i++) {
  29981. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29982. }
  29983. }
  29984. }
  29985. else {
  29986. for (f = 0; f < nbfaces; f++) {
  29987. var fl = data.face[f].length; // number of vertices of the current face
  29988. ang = 2 * Math.PI / fl;
  29989. x = 0.5 * Math.tan(ang / 2);
  29990. y = 0.5;
  29991. // positions, uvs, colors
  29992. for (i = 0; i < fl; i++) {
  29993. // positions
  29994. 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);
  29995. indexes.push(index);
  29996. index++;
  29997. // uvs
  29998. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29999. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30000. uvs.push(u, v);
  30001. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30002. y = x * Math.sin(ang) + y * Math.cos(ang);
  30003. x = tmp;
  30004. // colors
  30005. if (faceColors) {
  30006. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30007. }
  30008. }
  30009. // indices from indexes
  30010. for (i = 0; i < fl - 2; i++) {
  30011. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30012. }
  30013. faceIdx += fl;
  30014. }
  30015. }
  30016. VertexData.ComputeNormals(positions, indices, normals);
  30017. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30018. var vertexData = new VertexData();
  30019. vertexData.positions = positions;
  30020. vertexData.indices = indices;
  30021. vertexData.normals = normals;
  30022. vertexData.uvs = uvs;
  30023. if (faceColors && flat) {
  30024. vertexData.colors = colors;
  30025. }
  30026. return vertexData;
  30027. };
  30028. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30029. /**
  30030. * Creates the VertexData of the Torus Knot.
  30031. */
  30032. VertexData.CreateTorusKnot = function (options) {
  30033. var indices = new Array();
  30034. var positions = new Array();
  30035. var normals = new Array();
  30036. var uvs = new Array();
  30037. var radius = options.radius || 2;
  30038. var tube = options.tube || 0.5;
  30039. var radialSegments = options.radialSegments || 32;
  30040. var tubularSegments = options.tubularSegments || 32;
  30041. var p = options.p || 2;
  30042. var q = options.q || 3;
  30043. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30044. // Helper
  30045. var getPos = function (angle) {
  30046. var cu = Math.cos(angle);
  30047. var su = Math.sin(angle);
  30048. var quOverP = q / p * angle;
  30049. var cs = Math.cos(quOverP);
  30050. var tx = radius * (2 + cs) * 0.5 * cu;
  30051. var ty = radius * (2 + cs) * su * 0.5;
  30052. var tz = radius * Math.sin(quOverP) * 0.5;
  30053. return new BABYLON.Vector3(tx, ty, tz);
  30054. };
  30055. // Vertices
  30056. var i;
  30057. var j;
  30058. for (i = 0; i <= radialSegments; i++) {
  30059. var modI = i % radialSegments;
  30060. var u = modI / radialSegments * 2 * p * Math.PI;
  30061. var p1 = getPos(u);
  30062. var p2 = getPos(u + 0.01);
  30063. var tang = p2.subtract(p1);
  30064. var n = p2.add(p1);
  30065. var bitan = BABYLON.Vector3.Cross(tang, n);
  30066. n = BABYLON.Vector3.Cross(bitan, tang);
  30067. bitan.normalize();
  30068. n.normalize();
  30069. for (j = 0; j < tubularSegments; j++) {
  30070. var modJ = j % tubularSegments;
  30071. var v = modJ / tubularSegments * 2 * Math.PI;
  30072. var cx = -tube * Math.cos(v);
  30073. var cy = tube * Math.sin(v);
  30074. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30075. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30076. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30077. uvs.push(i / radialSegments);
  30078. uvs.push(j / tubularSegments);
  30079. }
  30080. }
  30081. for (i = 0; i < radialSegments; i++) {
  30082. for (j = 0; j < tubularSegments; j++) {
  30083. var jNext = (j + 1) % tubularSegments;
  30084. var a = i * tubularSegments + j;
  30085. var b = (i + 1) * tubularSegments + j;
  30086. var c = (i + 1) * tubularSegments + jNext;
  30087. var d = i * tubularSegments + jNext;
  30088. indices.push(d);
  30089. indices.push(b);
  30090. indices.push(a);
  30091. indices.push(d);
  30092. indices.push(c);
  30093. indices.push(b);
  30094. }
  30095. }
  30096. // Normals
  30097. VertexData.ComputeNormals(positions, indices, normals);
  30098. // Sides
  30099. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30100. // Result
  30101. var vertexData = new VertexData();
  30102. vertexData.indices = indices;
  30103. vertexData.positions = positions;
  30104. vertexData.normals = normals;
  30105. vertexData.uvs = uvs;
  30106. return vertexData;
  30107. };
  30108. // Tools
  30109. /**
  30110. * @param {any} - positions (number[] or Float32Array)
  30111. * @param {any} - indices (number[] or Uint16Array)
  30112. * @param {any} - normals (number[] or Float32Array)
  30113. * options (optional) :
  30114. * facetPositions : optional array of facet positions (vector3)
  30115. * facetNormals : optional array of facet normals (vector3)
  30116. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30117. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30118. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30119. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30120. * bInfo : optional bounding info, required for facetPartitioning computation
  30121. */
  30122. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30123. // temporary scalar variables
  30124. var index = 0; // facet index
  30125. var p1p2x = 0.0; // p1p2 vector x coordinate
  30126. var p1p2y = 0.0; // p1p2 vector y coordinate
  30127. var p1p2z = 0.0; // p1p2 vector z coordinate
  30128. var p3p2x = 0.0; // p3p2 vector x coordinate
  30129. var p3p2y = 0.0; // p3p2 vector y coordinate
  30130. var p3p2z = 0.0; // p3p2 vector z coordinate
  30131. var faceNormalx = 0.0; // facet normal x coordinate
  30132. var faceNormaly = 0.0; // facet normal y coordinate
  30133. var faceNormalz = 0.0; // facet normal z coordinate
  30134. var length = 0.0; // facet normal length before normalization
  30135. var v1x = 0; // vector1 x index in the positions array
  30136. var v1y = 0; // vector1 y index in the positions array
  30137. var v1z = 0; // vector1 z index in the positions array
  30138. var v2x = 0; // vector2 x index in the positions array
  30139. var v2y = 0; // vector2 y index in the positions array
  30140. var v2z = 0; // vector2 z index in the positions array
  30141. var v3x = 0; // vector3 x index in the positions array
  30142. var v3y = 0; // vector3 y index in the positions array
  30143. var v3z = 0; // vector3 z index in the positions array
  30144. var computeFacetNormals = false;
  30145. var computeFacetPositions = false;
  30146. var computeFacetPartitioning = false;
  30147. var faceNormalSign = 1;
  30148. var ratio = 0;
  30149. if (options) {
  30150. computeFacetNormals = (options.facetNormals) ? true : false;
  30151. computeFacetPositions = (options.facetPositions) ? true : false;
  30152. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30153. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30154. ratio = options.ratio || 0;
  30155. }
  30156. // facetPartitioning reinit if needed
  30157. var xSubRatio = 0;
  30158. var ySubRatio = 0;
  30159. var zSubRatio = 0;
  30160. var subSq = 0;
  30161. if (computeFacetPartitioning && options && options.bbSize) {
  30162. var ox = 0; // X partitioning index for facet position
  30163. var oy = 0; // Y partinioning index for facet position
  30164. var oz = 0; // Z partinioning index for facet position
  30165. var b1x = 0; // X partitioning index for facet v1 vertex
  30166. var b1y = 0; // Y partitioning index for facet v1 vertex
  30167. var b1z = 0; // z partitioning index for facet v1 vertex
  30168. var b2x = 0; // X partitioning index for facet v2 vertex
  30169. var b2y = 0; // Y partitioning index for facet v2 vertex
  30170. var b2z = 0; // Z partitioning index for facet v2 vertex
  30171. var b3x = 0; // X partitioning index for facet v3 vertex
  30172. var b3y = 0; // Y partitioning index for facet v3 vertex
  30173. var b3z = 0; // Z partitioning index for facet v3 vertex
  30174. var block_idx_o = 0; // facet barycenter block index
  30175. var block_idx_v1 = 0; // v1 vertex block index
  30176. var block_idx_v2 = 0; // v2 vertex block index
  30177. var block_idx_v3 = 0; // v3 vertex block index
  30178. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30179. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30180. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30181. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30182. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30183. subSq = options.subDiv.max * options.subDiv.max;
  30184. options.facetPartitioning.length = 0;
  30185. }
  30186. // reset the normals
  30187. for (index = 0; index < positions.length; index++) {
  30188. normals[index] = 0.0;
  30189. }
  30190. // Loop : 1 indice triplet = 1 facet
  30191. var nbFaces = indices.length / 3;
  30192. for (index = 0; index < nbFaces; index++) {
  30193. // get the indexes of the coordinates of each vertex of the facet
  30194. v1x = indices[index * 3] * 3;
  30195. v1y = v1x + 1;
  30196. v1z = v1x + 2;
  30197. v2x = indices[index * 3 + 1] * 3;
  30198. v2y = v2x + 1;
  30199. v2z = v2x + 2;
  30200. v3x = indices[index * 3 + 2] * 3;
  30201. v3y = v3x + 1;
  30202. v3z = v3x + 2;
  30203. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30204. p1p2y = positions[v1y] - positions[v2y];
  30205. p1p2z = positions[v1z] - positions[v2z];
  30206. p3p2x = positions[v3x] - positions[v2x];
  30207. p3p2y = positions[v3y] - positions[v2y];
  30208. p3p2z = positions[v3z] - positions[v2z];
  30209. // compute the face normal with the cross product
  30210. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30211. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30212. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30213. // normalize this normal and store it in the array facetData
  30214. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30215. length = (length === 0) ? 1.0 : length;
  30216. faceNormalx /= length;
  30217. faceNormaly /= length;
  30218. faceNormalz /= length;
  30219. if (computeFacetNormals && options) {
  30220. options.facetNormals[index].x = faceNormalx;
  30221. options.facetNormals[index].y = faceNormaly;
  30222. options.facetNormals[index].z = faceNormalz;
  30223. }
  30224. if (computeFacetPositions && options) {
  30225. // compute and the facet barycenter coordinates in the array facetPositions
  30226. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30227. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30228. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30229. }
  30230. if (computeFacetPartitioning && options) {
  30231. // store the facet indexes in arrays in the main facetPartitioning array :
  30232. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30233. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30234. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30235. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30236. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30237. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30238. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30239. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30240. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30241. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30242. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30243. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30244. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30245. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30246. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30247. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30248. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30249. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30250. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30251. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30252. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30253. // push each facet index in each block containing the vertex
  30254. options.facetPartitioning[block_idx_v1].push(index);
  30255. if (block_idx_v2 != block_idx_v1) {
  30256. options.facetPartitioning[block_idx_v2].push(index);
  30257. }
  30258. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30259. options.facetPartitioning[block_idx_v3].push(index);
  30260. }
  30261. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30262. options.facetPartitioning[block_idx_o].push(index);
  30263. }
  30264. }
  30265. // compute the normals anyway
  30266. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30267. normals[v1y] += faceNormaly;
  30268. normals[v1z] += faceNormalz;
  30269. normals[v2x] += faceNormalx;
  30270. normals[v2y] += faceNormaly;
  30271. normals[v2z] += faceNormalz;
  30272. normals[v3x] += faceNormalx;
  30273. normals[v3y] += faceNormaly;
  30274. normals[v3z] += faceNormalz;
  30275. }
  30276. // last normalization of each normal
  30277. for (index = 0; index < normals.length / 3; index++) {
  30278. faceNormalx = normals[index * 3];
  30279. faceNormaly = normals[index * 3 + 1];
  30280. faceNormalz = normals[index * 3 + 2];
  30281. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30282. length = (length === 0) ? 1.0 : length;
  30283. faceNormalx /= length;
  30284. faceNormaly /= length;
  30285. faceNormalz /= length;
  30286. normals[index * 3] = faceNormalx;
  30287. normals[index * 3 + 1] = faceNormaly;
  30288. normals[index * 3 + 2] = faceNormalz;
  30289. }
  30290. };
  30291. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30292. var li = indices.length;
  30293. var ln = normals.length;
  30294. var i;
  30295. var n;
  30296. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30297. switch (sideOrientation) {
  30298. case BABYLON.Mesh.FRONTSIDE:
  30299. // nothing changed
  30300. break;
  30301. case BABYLON.Mesh.BACKSIDE:
  30302. var tmp;
  30303. // indices
  30304. for (i = 0; i < li; i += 3) {
  30305. tmp = indices[i];
  30306. indices[i] = indices[i + 2];
  30307. indices[i + 2] = tmp;
  30308. }
  30309. // normals
  30310. for (n = 0; n < ln; n++) {
  30311. normals[n] = -normals[n];
  30312. }
  30313. break;
  30314. case BABYLON.Mesh.DOUBLESIDE:
  30315. // positions
  30316. var lp = positions.length;
  30317. var l = lp / 3;
  30318. for (var p = 0; p < lp; p++) {
  30319. positions[lp + p] = positions[p];
  30320. }
  30321. // indices
  30322. for (i = 0; i < li; i += 3) {
  30323. indices[i + li] = indices[i + 2] + l;
  30324. indices[i + 1 + li] = indices[i + 1] + l;
  30325. indices[i + 2 + li] = indices[i] + l;
  30326. }
  30327. // normals
  30328. for (n = 0; n < ln; n++) {
  30329. normals[ln + n] = -normals[n];
  30330. }
  30331. // uvs
  30332. var lu = uvs.length;
  30333. var u = 0;
  30334. for (u = 0; u < lu; u++) {
  30335. uvs[u + lu] = uvs[u];
  30336. }
  30337. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30338. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30339. u = 0;
  30340. for (i = 0; i < lu / 2; i++) {
  30341. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30342. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30343. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30344. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30345. u += 2;
  30346. }
  30347. break;
  30348. }
  30349. };
  30350. /**
  30351. * Creates a new VertexData from the imported parameters.
  30352. */
  30353. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30354. var vertexData = new VertexData();
  30355. // positions
  30356. var positions = parsedVertexData.positions;
  30357. if (positions) {
  30358. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30359. }
  30360. // normals
  30361. var normals = parsedVertexData.normals;
  30362. if (normals) {
  30363. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30364. }
  30365. // tangents
  30366. var tangents = parsedVertexData.tangents;
  30367. if (tangents) {
  30368. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30369. }
  30370. // uvs
  30371. var uvs = parsedVertexData.uvs;
  30372. if (uvs) {
  30373. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30374. }
  30375. // uv2s
  30376. var uv2s = parsedVertexData.uv2s;
  30377. if (uv2s) {
  30378. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30379. }
  30380. // uv3s
  30381. var uv3s = parsedVertexData.uv3s;
  30382. if (uv3s) {
  30383. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30384. }
  30385. // uv4s
  30386. var uv4s = parsedVertexData.uv4s;
  30387. if (uv4s) {
  30388. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30389. }
  30390. // uv5s
  30391. var uv5s = parsedVertexData.uv5s;
  30392. if (uv5s) {
  30393. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30394. }
  30395. // uv6s
  30396. var uv6s = parsedVertexData.uv6s;
  30397. if (uv6s) {
  30398. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30399. }
  30400. // colors
  30401. var colors = parsedVertexData.colors;
  30402. if (colors) {
  30403. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30404. }
  30405. // matricesIndices
  30406. var matricesIndices = parsedVertexData.matricesIndices;
  30407. if (matricesIndices) {
  30408. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30409. }
  30410. // matricesWeights
  30411. var matricesWeights = parsedVertexData.matricesWeights;
  30412. if (matricesWeights) {
  30413. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30414. }
  30415. // indices
  30416. var indices = parsedVertexData.indices;
  30417. if (indices) {
  30418. vertexData.indices = indices;
  30419. }
  30420. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30421. };
  30422. return VertexData;
  30423. }());
  30424. BABYLON.VertexData = VertexData;
  30425. })(BABYLON || (BABYLON = {}));
  30426. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30427. var BABYLON;
  30428. (function (BABYLON) {
  30429. var Geometry = /** @class */ (function () {
  30430. function Geometry(id, scene, vertexData, updatable, mesh) {
  30431. if (updatable === void 0) { updatable = false; }
  30432. if (mesh === void 0) { mesh = null; }
  30433. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30434. this._totalVertices = 0;
  30435. this._isDisposed = false;
  30436. this._indexBufferIsUpdatable = false;
  30437. this.id = id;
  30438. this._engine = scene.getEngine();
  30439. this._meshes = [];
  30440. this._scene = scene;
  30441. //Init vertex buffer cache
  30442. this._vertexBuffers = {};
  30443. this._indices = [];
  30444. this._updatable = updatable;
  30445. // vertexData
  30446. if (vertexData) {
  30447. this.setAllVerticesData(vertexData, updatable);
  30448. }
  30449. else {
  30450. this._totalVertices = 0;
  30451. this._indices = [];
  30452. }
  30453. if (this._engine.getCaps().vertexArrayObject) {
  30454. this._vertexArrayObjects = {};
  30455. }
  30456. // applyToMesh
  30457. if (mesh) {
  30458. if (mesh.getClassName() === "LinesMesh") {
  30459. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30460. this.updateExtend();
  30461. }
  30462. this.applyToMesh(mesh);
  30463. mesh.computeWorldMatrix(true);
  30464. }
  30465. }
  30466. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30467. /**
  30468. * 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
  30469. * @returns The Bias Vector
  30470. */
  30471. get: function () {
  30472. return this._boundingBias;
  30473. },
  30474. set: function (value) {
  30475. if (this._boundingBias && this._boundingBias.equals(value)) {
  30476. return;
  30477. }
  30478. this._boundingBias = value.clone();
  30479. this.updateBoundingInfo(true, null);
  30480. },
  30481. enumerable: true,
  30482. configurable: true
  30483. });
  30484. Geometry.CreateGeometryForMesh = function (mesh) {
  30485. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30486. geometry.applyToMesh(mesh);
  30487. return geometry;
  30488. };
  30489. Object.defineProperty(Geometry.prototype, "extend", {
  30490. get: function () {
  30491. return this._extend;
  30492. },
  30493. enumerable: true,
  30494. configurable: true
  30495. });
  30496. Geometry.prototype.getScene = function () {
  30497. return this._scene;
  30498. };
  30499. Geometry.prototype.getEngine = function () {
  30500. return this._engine;
  30501. };
  30502. Geometry.prototype.isReady = function () {
  30503. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30504. };
  30505. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30506. get: function () {
  30507. for (var index = 0; index < this._meshes.length; index++) {
  30508. if (!this._meshes[index].doNotSerialize) {
  30509. return false;
  30510. }
  30511. }
  30512. return true;
  30513. },
  30514. enumerable: true,
  30515. configurable: true
  30516. });
  30517. Geometry.prototype._rebuild = function () {
  30518. if (this._vertexArrayObjects) {
  30519. this._vertexArrayObjects = {};
  30520. }
  30521. // Index buffer
  30522. if (this._meshes.length !== 0 && this._indices) {
  30523. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30524. }
  30525. // Vertex buffers
  30526. for (var key in this._vertexBuffers) {
  30527. var vertexBuffer = this._vertexBuffers[key];
  30528. vertexBuffer._rebuild();
  30529. }
  30530. };
  30531. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30532. vertexData.applyToGeometry(this, updatable);
  30533. this.notifyUpdate();
  30534. };
  30535. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30536. if (updatable === void 0) { updatable = false; }
  30537. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30538. this.setVerticesBuffer(buffer);
  30539. };
  30540. Geometry.prototype.removeVerticesData = function (kind) {
  30541. if (this._vertexBuffers[kind]) {
  30542. this._vertexBuffers[kind].dispose();
  30543. delete this._vertexBuffers[kind];
  30544. }
  30545. };
  30546. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30547. var kind = buffer.getKind();
  30548. if (this._vertexBuffers[kind]) {
  30549. this._vertexBuffers[kind].dispose();
  30550. }
  30551. this._vertexBuffers[kind] = buffer;
  30552. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30553. var data = buffer.getData();
  30554. var stride = buffer.getStrideSize();
  30555. this._totalVertices = data.length / stride;
  30556. this.updateExtend(data, stride);
  30557. this._resetPointsArrayCache();
  30558. var meshes = this._meshes;
  30559. var numOfMeshes = meshes.length;
  30560. for (var index = 0; index < numOfMeshes; index++) {
  30561. var mesh = meshes[index];
  30562. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30563. mesh._createGlobalSubMesh(false);
  30564. mesh.computeWorldMatrix(true);
  30565. }
  30566. }
  30567. this.notifyUpdate(kind);
  30568. if (this._vertexArrayObjects) {
  30569. this._disposeVertexArrayObjects();
  30570. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30571. }
  30572. };
  30573. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30574. var vertexBuffer = this.getVertexBuffer(kind);
  30575. if (!vertexBuffer) {
  30576. return;
  30577. }
  30578. vertexBuffer.updateDirectly(data, offset);
  30579. this.notifyUpdate(kind);
  30580. };
  30581. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30582. if (updateExtends === void 0) { updateExtends = false; }
  30583. var vertexBuffer = this.getVertexBuffer(kind);
  30584. if (!vertexBuffer) {
  30585. return;
  30586. }
  30587. vertexBuffer.update(data);
  30588. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30589. var stride = vertexBuffer.getStrideSize();
  30590. this._totalVertices = data.length / stride;
  30591. this.updateBoundingInfo(updateExtends, data);
  30592. }
  30593. this.notifyUpdate(kind);
  30594. };
  30595. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30596. if (updateExtends) {
  30597. this.updateExtend(data);
  30598. }
  30599. var meshes = this._meshes;
  30600. var numOfMeshes = meshes.length;
  30601. this._resetPointsArrayCache();
  30602. for (var index = 0; index < numOfMeshes; index++) {
  30603. var mesh = meshes[index];
  30604. if (updateExtends) {
  30605. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30606. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30607. var subMesh = mesh.subMeshes[subIndex];
  30608. subMesh.refreshBoundingInfo();
  30609. }
  30610. }
  30611. }
  30612. };
  30613. Geometry.prototype._bind = function (effect, indexToBind) {
  30614. if (!effect) {
  30615. return;
  30616. }
  30617. if (indexToBind === undefined) {
  30618. indexToBind = this._indexBuffer;
  30619. }
  30620. var vbs = this.getVertexBuffers();
  30621. if (!vbs) {
  30622. return;
  30623. }
  30624. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30625. this._engine.bindBuffers(vbs, indexToBind, effect);
  30626. return;
  30627. }
  30628. // Using VAO
  30629. if (!this._vertexArrayObjects[effect.key]) {
  30630. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30631. }
  30632. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30633. };
  30634. Geometry.prototype.getTotalVertices = function () {
  30635. if (!this.isReady()) {
  30636. return 0;
  30637. }
  30638. return this._totalVertices;
  30639. };
  30640. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30641. var vertexBuffer = this.getVertexBuffer(kind);
  30642. if (!vertexBuffer) {
  30643. return null;
  30644. }
  30645. var orig = vertexBuffer.getData();
  30646. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30647. return orig;
  30648. }
  30649. else {
  30650. var len = orig.length;
  30651. var copy = [];
  30652. for (var i = 0; i < len; i++) {
  30653. copy.push(orig[i]);
  30654. }
  30655. return copy;
  30656. }
  30657. };
  30658. /**
  30659. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30660. * Possible `kind` values :
  30661. * - BABYLON.VertexBuffer.PositionKind
  30662. * - BABYLON.VertexBuffer.UVKind
  30663. * - BABYLON.VertexBuffer.UV2Kind
  30664. * - BABYLON.VertexBuffer.UV3Kind
  30665. * - BABYLON.VertexBuffer.UV4Kind
  30666. * - BABYLON.VertexBuffer.UV5Kind
  30667. * - BABYLON.VertexBuffer.UV6Kind
  30668. * - BABYLON.VertexBuffer.ColorKind
  30669. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30670. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30671. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30672. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30673. */
  30674. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30675. var vb = this._vertexBuffers[kind];
  30676. if (!vb) {
  30677. return false;
  30678. }
  30679. return vb.isUpdatable();
  30680. };
  30681. Geometry.prototype.getVertexBuffer = function (kind) {
  30682. if (!this.isReady()) {
  30683. return null;
  30684. }
  30685. return this._vertexBuffers[kind];
  30686. };
  30687. Geometry.prototype.getVertexBuffers = function () {
  30688. if (!this.isReady()) {
  30689. return null;
  30690. }
  30691. return this._vertexBuffers;
  30692. };
  30693. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30694. if (!this._vertexBuffers) {
  30695. if (this._delayInfo) {
  30696. return this._delayInfo.indexOf(kind) !== -1;
  30697. }
  30698. return false;
  30699. }
  30700. return this._vertexBuffers[kind] !== undefined;
  30701. };
  30702. Geometry.prototype.getVerticesDataKinds = function () {
  30703. var result = [];
  30704. var kind;
  30705. if (!this._vertexBuffers && this._delayInfo) {
  30706. for (kind in this._delayInfo) {
  30707. result.push(kind);
  30708. }
  30709. }
  30710. else {
  30711. for (kind in this._vertexBuffers) {
  30712. result.push(kind);
  30713. }
  30714. }
  30715. return result;
  30716. };
  30717. Geometry.prototype.updateIndices = function (indices, offset) {
  30718. if (!this._indexBuffer) {
  30719. return;
  30720. }
  30721. if (!this._indexBufferIsUpdatable) {
  30722. this.setIndices(indices, null, true);
  30723. }
  30724. else {
  30725. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30726. }
  30727. };
  30728. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30729. if (totalVertices === void 0) { totalVertices = null; }
  30730. if (updatable === void 0) { updatable = false; }
  30731. if (this._indexBuffer) {
  30732. this._engine._releaseBuffer(this._indexBuffer);
  30733. }
  30734. this._disposeVertexArrayObjects();
  30735. this._indices = indices;
  30736. this._indexBufferIsUpdatable = updatable;
  30737. if (this._meshes.length !== 0 && this._indices) {
  30738. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30739. }
  30740. if (totalVertices != undefined) {
  30741. this._totalVertices = totalVertices;
  30742. }
  30743. var meshes = this._meshes;
  30744. var numOfMeshes = meshes.length;
  30745. for (var index = 0; index < numOfMeshes; index++) {
  30746. meshes[index]._createGlobalSubMesh(true);
  30747. }
  30748. this.notifyUpdate();
  30749. };
  30750. Geometry.prototype.getTotalIndices = function () {
  30751. if (!this.isReady()) {
  30752. return 0;
  30753. }
  30754. return this._indices.length;
  30755. };
  30756. Geometry.prototype.getIndices = function (copyWhenShared) {
  30757. if (!this.isReady()) {
  30758. return null;
  30759. }
  30760. var orig = this._indices;
  30761. if (!copyWhenShared || this._meshes.length === 1) {
  30762. return orig;
  30763. }
  30764. else {
  30765. var len = orig.length;
  30766. var copy = [];
  30767. for (var i = 0; i < len; i++) {
  30768. copy.push(orig[i]);
  30769. }
  30770. return copy;
  30771. }
  30772. };
  30773. Geometry.prototype.getIndexBuffer = function () {
  30774. if (!this.isReady()) {
  30775. return null;
  30776. }
  30777. return this._indexBuffer;
  30778. };
  30779. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30780. if (effect === void 0) { effect = null; }
  30781. if (!effect || !this._vertexArrayObjects) {
  30782. return;
  30783. }
  30784. if (this._vertexArrayObjects[effect.key]) {
  30785. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30786. delete this._vertexArrayObjects[effect.key];
  30787. }
  30788. };
  30789. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30790. var meshes = this._meshes;
  30791. var index = meshes.indexOf(mesh);
  30792. if (index === -1) {
  30793. return;
  30794. }
  30795. meshes.splice(index, 1);
  30796. mesh._geometry = null;
  30797. if (meshes.length === 0 && shouldDispose) {
  30798. this.dispose();
  30799. }
  30800. };
  30801. Geometry.prototype.applyToMesh = function (mesh) {
  30802. if (mesh._geometry === this) {
  30803. return;
  30804. }
  30805. var previousGeometry = mesh._geometry;
  30806. if (previousGeometry) {
  30807. previousGeometry.releaseForMesh(mesh);
  30808. }
  30809. var meshes = this._meshes;
  30810. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30811. mesh._geometry = this;
  30812. this._scene.pushGeometry(this);
  30813. meshes.push(mesh);
  30814. if (this.isReady()) {
  30815. this._applyToMesh(mesh);
  30816. }
  30817. else {
  30818. mesh._boundingInfo = this._boundingInfo;
  30819. }
  30820. };
  30821. Geometry.prototype.updateExtend = function (data, stride) {
  30822. if (data === void 0) { data = null; }
  30823. if (!data) {
  30824. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30825. }
  30826. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30827. };
  30828. Geometry.prototype._applyToMesh = function (mesh) {
  30829. var numOfMeshes = this._meshes.length;
  30830. // vertexBuffers
  30831. for (var kind in this._vertexBuffers) {
  30832. if (numOfMeshes === 1) {
  30833. this._vertexBuffers[kind].create();
  30834. }
  30835. var buffer = this._vertexBuffers[kind].getBuffer();
  30836. if (buffer)
  30837. buffer.references = numOfMeshes;
  30838. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30839. if (!this._extend) {
  30840. this.updateExtend(this._vertexBuffers[kind].getData());
  30841. }
  30842. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30843. mesh._createGlobalSubMesh(false);
  30844. //bounding info was just created again, world matrix should be applied again.
  30845. mesh._updateBoundingInfo();
  30846. }
  30847. }
  30848. // indexBuffer
  30849. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30850. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30851. }
  30852. if (this._indexBuffer) {
  30853. this._indexBuffer.references = numOfMeshes;
  30854. }
  30855. };
  30856. Geometry.prototype.notifyUpdate = function (kind) {
  30857. if (this.onGeometryUpdated) {
  30858. this.onGeometryUpdated(this, kind);
  30859. }
  30860. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30861. var mesh = _a[_i];
  30862. mesh._markSubMeshesAsAttributesDirty();
  30863. }
  30864. };
  30865. Geometry.prototype.load = function (scene, onLoaded) {
  30866. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30867. return;
  30868. }
  30869. if (this.isReady()) {
  30870. if (onLoaded) {
  30871. onLoaded();
  30872. }
  30873. return;
  30874. }
  30875. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30876. this._queueLoad(scene, onLoaded);
  30877. };
  30878. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30879. var _this = this;
  30880. if (!this.delayLoadingFile) {
  30881. return;
  30882. }
  30883. scene._addPendingData(this);
  30884. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30885. if (!_this._delayLoadingFunction) {
  30886. return;
  30887. }
  30888. _this._delayLoadingFunction(JSON.parse(data), _this);
  30889. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30890. _this._delayInfo = [];
  30891. scene._removePendingData(_this);
  30892. var meshes = _this._meshes;
  30893. var numOfMeshes = meshes.length;
  30894. for (var index = 0; index < numOfMeshes; index++) {
  30895. _this._applyToMesh(meshes[index]);
  30896. }
  30897. if (onLoaded) {
  30898. onLoaded();
  30899. }
  30900. }, function () { }, scene.database);
  30901. };
  30902. /**
  30903. * Invert the geometry to move from a right handed system to a left handed one.
  30904. */
  30905. Geometry.prototype.toLeftHanded = function () {
  30906. // Flip faces
  30907. var tIndices = this.getIndices(false);
  30908. if (tIndices != null && tIndices.length > 0) {
  30909. for (var i = 0; i < tIndices.length; i += 3) {
  30910. var tTemp = tIndices[i + 0];
  30911. tIndices[i + 0] = tIndices[i + 2];
  30912. tIndices[i + 2] = tTemp;
  30913. }
  30914. this.setIndices(tIndices);
  30915. }
  30916. // Negate position.z
  30917. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30918. if (tPositions != null && tPositions.length > 0) {
  30919. for (var i = 0; i < tPositions.length; i += 3) {
  30920. tPositions[i + 2] = -tPositions[i + 2];
  30921. }
  30922. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30923. }
  30924. // Negate normal.z
  30925. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30926. if (tNormals != null && tNormals.length > 0) {
  30927. for (var i = 0; i < tNormals.length; i += 3) {
  30928. tNormals[i + 2] = -tNormals[i + 2];
  30929. }
  30930. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30931. }
  30932. };
  30933. // Cache
  30934. Geometry.prototype._resetPointsArrayCache = function () {
  30935. this._positions = null;
  30936. };
  30937. Geometry.prototype._generatePointsArray = function () {
  30938. if (this._positions)
  30939. return true;
  30940. this._positions = [];
  30941. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30942. if (!data) {
  30943. return false;
  30944. }
  30945. for (var index = 0; index < data.length; index += 3) {
  30946. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30947. }
  30948. return true;
  30949. };
  30950. Geometry.prototype.isDisposed = function () {
  30951. return this._isDisposed;
  30952. };
  30953. Geometry.prototype._disposeVertexArrayObjects = function () {
  30954. if (this._vertexArrayObjects) {
  30955. for (var kind in this._vertexArrayObjects) {
  30956. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30957. }
  30958. this._vertexArrayObjects = {};
  30959. }
  30960. };
  30961. Geometry.prototype.dispose = function () {
  30962. var meshes = this._meshes;
  30963. var numOfMeshes = meshes.length;
  30964. var index;
  30965. for (index = 0; index < numOfMeshes; index++) {
  30966. this.releaseForMesh(meshes[index]);
  30967. }
  30968. this._meshes = [];
  30969. this._disposeVertexArrayObjects();
  30970. for (var kind in this._vertexBuffers) {
  30971. this._vertexBuffers[kind].dispose();
  30972. }
  30973. this._vertexBuffers = {};
  30974. this._totalVertices = 0;
  30975. if (this._indexBuffer) {
  30976. this._engine._releaseBuffer(this._indexBuffer);
  30977. }
  30978. this._indexBuffer = null;
  30979. this._indices = [];
  30980. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30981. this.delayLoadingFile = null;
  30982. this._delayLoadingFunction = null;
  30983. this._delayInfo = [];
  30984. this._boundingInfo = null;
  30985. this._scene.removeGeometry(this);
  30986. this._isDisposed = true;
  30987. };
  30988. Geometry.prototype.copy = function (id) {
  30989. var vertexData = new BABYLON.VertexData();
  30990. vertexData.indices = [];
  30991. var indices = this.getIndices();
  30992. if (indices) {
  30993. for (var index = 0; index < indices.length; index++) {
  30994. vertexData.indices.push(indices[index]);
  30995. }
  30996. }
  30997. var updatable = false;
  30998. var stopChecking = false;
  30999. var kind;
  31000. for (kind in this._vertexBuffers) {
  31001. // using slice() to make a copy of the array and not just reference it
  31002. var data = this.getVerticesData(kind);
  31003. if (data instanceof Float32Array) {
  31004. vertexData.set(new Float32Array(data), kind);
  31005. }
  31006. else {
  31007. vertexData.set(data.slice(0), kind);
  31008. }
  31009. if (!stopChecking) {
  31010. var vb = this.getVertexBuffer(kind);
  31011. if (vb) {
  31012. updatable = vb.isUpdatable();
  31013. stopChecking = !updatable;
  31014. }
  31015. }
  31016. }
  31017. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31018. geometry.delayLoadState = this.delayLoadState;
  31019. geometry.delayLoadingFile = this.delayLoadingFile;
  31020. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31021. for (kind in this._delayInfo) {
  31022. geometry._delayInfo = geometry._delayInfo || [];
  31023. geometry._delayInfo.push(kind);
  31024. }
  31025. // Bounding info
  31026. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31027. return geometry;
  31028. };
  31029. Geometry.prototype.serialize = function () {
  31030. var serializationObject = {};
  31031. serializationObject.id = this.id;
  31032. serializationObject.updatable = this._updatable;
  31033. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31034. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31035. }
  31036. return serializationObject;
  31037. };
  31038. Geometry.prototype.toNumberArray = function (origin) {
  31039. if (Array.isArray(origin)) {
  31040. return origin;
  31041. }
  31042. else {
  31043. return Array.prototype.slice.call(origin);
  31044. }
  31045. };
  31046. Geometry.prototype.serializeVerticeData = function () {
  31047. var serializationObject = this.serialize();
  31048. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31049. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31050. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31051. serializationObject.positions._updatable = true;
  31052. }
  31053. }
  31054. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31055. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31056. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31057. serializationObject.normals._updatable = true;
  31058. }
  31059. }
  31060. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31061. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31062. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31063. serializationObject.uvs._updatable = true;
  31064. }
  31065. }
  31066. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31067. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31068. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31069. serializationObject.uv2s._updatable = true;
  31070. }
  31071. }
  31072. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31073. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31074. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31075. serializationObject.uv3s._updatable = true;
  31076. }
  31077. }
  31078. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31079. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31080. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31081. serializationObject.uv4s._updatable = true;
  31082. }
  31083. }
  31084. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31085. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31086. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31087. serializationObject.uv5s._updatable = true;
  31088. }
  31089. }
  31090. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31091. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31092. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31093. serializationObject.uv6s._updatable = true;
  31094. }
  31095. }
  31096. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31097. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31098. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31099. serializationObject.colors._updatable = true;
  31100. }
  31101. }
  31102. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31103. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31104. serializationObject.matricesIndices._isExpanded = true;
  31105. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31106. serializationObject.matricesIndices._updatable = true;
  31107. }
  31108. }
  31109. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31110. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31111. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31112. serializationObject.matricesWeights._updatable = true;
  31113. }
  31114. }
  31115. serializationObject.indices = this.toNumberArray(this.getIndices());
  31116. return serializationObject;
  31117. };
  31118. // Statics
  31119. Geometry.ExtractFromMesh = function (mesh, id) {
  31120. var geometry = mesh._geometry;
  31121. if (!geometry) {
  31122. return null;
  31123. }
  31124. return geometry.copy(id);
  31125. };
  31126. /**
  31127. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31128. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31129. * Be aware Math.random() could cause collisions, but:
  31130. * "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"
  31131. */
  31132. Geometry.RandomId = function () {
  31133. return BABYLON.Tools.RandomId();
  31134. };
  31135. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31136. var scene = mesh.getScene();
  31137. // Geometry
  31138. var geometryId = parsedGeometry.geometryId;
  31139. if (geometryId) {
  31140. var geometry = scene.getGeometryByID(geometryId);
  31141. if (geometry) {
  31142. geometry.applyToMesh(mesh);
  31143. }
  31144. }
  31145. else if (parsedGeometry instanceof ArrayBuffer) {
  31146. var binaryInfo = mesh._binaryInfo;
  31147. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31148. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31149. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31150. }
  31151. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31152. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31153. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31154. }
  31155. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31156. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31157. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31158. }
  31159. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31160. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31161. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31162. }
  31163. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31164. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31165. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31166. }
  31167. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31168. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31169. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31170. }
  31171. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31172. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31173. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31174. }
  31175. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31176. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31177. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31178. }
  31179. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31180. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31181. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31182. }
  31183. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31184. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31185. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31186. }
  31187. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31188. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31189. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31190. }
  31191. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31192. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31193. mesh.setIndices(indicesData, null);
  31194. }
  31195. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31196. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31197. mesh.subMeshes = [];
  31198. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31199. var materialIndex = subMeshesData[(i * 5) + 0];
  31200. var verticesStart = subMeshesData[(i * 5) + 1];
  31201. var verticesCount = subMeshesData[(i * 5) + 2];
  31202. var indexStart = subMeshesData[(i * 5) + 3];
  31203. var indexCount = subMeshesData[(i * 5) + 4];
  31204. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31205. }
  31206. }
  31207. }
  31208. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31209. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31210. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31211. if (parsedGeometry.uvs) {
  31212. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31213. }
  31214. if (parsedGeometry.uvs2) {
  31215. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31216. }
  31217. if (parsedGeometry.uvs3) {
  31218. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31219. }
  31220. if (parsedGeometry.uvs4) {
  31221. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31222. }
  31223. if (parsedGeometry.uvs5) {
  31224. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31225. }
  31226. if (parsedGeometry.uvs6) {
  31227. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31228. }
  31229. if (parsedGeometry.colors) {
  31230. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31231. }
  31232. if (parsedGeometry.matricesIndices) {
  31233. if (!parsedGeometry.matricesIndices._isExpanded) {
  31234. var floatIndices = [];
  31235. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31236. var matricesIndex = parsedGeometry.matricesIndices[i];
  31237. floatIndices.push(matricesIndex & 0x000000FF);
  31238. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31239. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31240. floatIndices.push(matricesIndex >> 24);
  31241. }
  31242. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31243. }
  31244. else {
  31245. delete parsedGeometry.matricesIndices._isExpanded;
  31246. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31247. }
  31248. }
  31249. if (parsedGeometry.matricesIndicesExtra) {
  31250. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31251. var floatIndices = [];
  31252. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31253. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31254. floatIndices.push(matricesIndex & 0x000000FF);
  31255. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31256. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31257. floatIndices.push(matricesIndex >> 24);
  31258. }
  31259. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31260. }
  31261. else {
  31262. delete parsedGeometry.matricesIndices._isExpanded;
  31263. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31264. }
  31265. }
  31266. if (parsedGeometry.matricesWeights) {
  31267. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31268. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31269. }
  31270. if (parsedGeometry.matricesWeightsExtra) {
  31271. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31272. }
  31273. mesh.setIndices(parsedGeometry.indices, null);
  31274. }
  31275. // SubMeshes
  31276. if (parsedGeometry.subMeshes) {
  31277. mesh.subMeshes = [];
  31278. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31279. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31280. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31281. }
  31282. }
  31283. // Flat shading
  31284. if (mesh._shouldGenerateFlatShading) {
  31285. mesh.convertToFlatShadedMesh();
  31286. delete mesh._shouldGenerateFlatShading;
  31287. }
  31288. // Update
  31289. mesh.computeWorldMatrix(true);
  31290. // Octree
  31291. if (scene['_selectionOctree']) {
  31292. scene['_selectionOctree'].addMesh(mesh);
  31293. }
  31294. };
  31295. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31296. var epsilon = 1e-3;
  31297. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31298. return;
  31299. }
  31300. var noInfluenceBoneIndex = 0.0;
  31301. if (parsedGeometry.skeletonId > -1) {
  31302. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31303. if (!skeleton) {
  31304. return;
  31305. }
  31306. noInfluenceBoneIndex = skeleton.bones.length;
  31307. }
  31308. else {
  31309. return;
  31310. }
  31311. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31312. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31313. var matricesWeights = parsedGeometry.matricesWeights;
  31314. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31315. var influencers = parsedGeometry.numBoneInfluencer;
  31316. var size = matricesWeights.length;
  31317. for (var i = 0; i < size; i += 4) {
  31318. var weight = 0.0;
  31319. var firstZeroWeight = -1;
  31320. for (var j = 0; j < 4; j++) {
  31321. var w = matricesWeights[i + j];
  31322. weight += w;
  31323. if (w < epsilon && firstZeroWeight < 0) {
  31324. firstZeroWeight = j;
  31325. }
  31326. }
  31327. if (matricesWeightsExtra) {
  31328. for (var j = 0; j < 4; j++) {
  31329. var w = matricesWeightsExtra[i + j];
  31330. weight += w;
  31331. if (w < epsilon && firstZeroWeight < 0) {
  31332. firstZeroWeight = j + 4;
  31333. }
  31334. }
  31335. }
  31336. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31337. firstZeroWeight = influencers - 1;
  31338. }
  31339. if (weight > epsilon) {
  31340. var mweight = 1.0 / weight;
  31341. for (var j = 0; j < 4; j++) {
  31342. matricesWeights[i + j] *= mweight;
  31343. }
  31344. if (matricesWeightsExtra) {
  31345. for (var j = 0; j < 4; j++) {
  31346. matricesWeightsExtra[i + j] *= mweight;
  31347. }
  31348. }
  31349. }
  31350. else {
  31351. if (firstZeroWeight >= 4) {
  31352. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31353. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31354. }
  31355. else {
  31356. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31357. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31358. }
  31359. }
  31360. }
  31361. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31362. if (parsedGeometry.matricesWeightsExtra) {
  31363. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31364. }
  31365. };
  31366. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31367. if (scene.getGeometryByID(parsedVertexData.id)) {
  31368. return null; // null since geometry could be something else than a box...
  31369. }
  31370. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31371. if (BABYLON.Tags) {
  31372. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31373. }
  31374. if (parsedVertexData.delayLoadingFile) {
  31375. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31376. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31377. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31378. geometry._delayInfo = [];
  31379. if (parsedVertexData.hasUVs) {
  31380. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31381. }
  31382. if (parsedVertexData.hasUVs2) {
  31383. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31384. }
  31385. if (parsedVertexData.hasUVs3) {
  31386. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31387. }
  31388. if (parsedVertexData.hasUVs4) {
  31389. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31390. }
  31391. if (parsedVertexData.hasUVs5) {
  31392. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31393. }
  31394. if (parsedVertexData.hasUVs6) {
  31395. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31396. }
  31397. if (parsedVertexData.hasColors) {
  31398. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31399. }
  31400. if (parsedVertexData.hasMatricesIndices) {
  31401. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31402. }
  31403. if (parsedVertexData.hasMatricesWeights) {
  31404. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31405. }
  31406. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31407. }
  31408. else {
  31409. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31410. }
  31411. scene.pushGeometry(geometry, true);
  31412. return geometry;
  31413. };
  31414. return Geometry;
  31415. }());
  31416. BABYLON.Geometry = Geometry;
  31417. /////// Primitives //////////////////////////////////////////////
  31418. (function (Geometry) {
  31419. var Primitives;
  31420. (function (Primitives) {
  31421. /// Abstract class
  31422. var _Primitive = /** @class */ (function (_super) {
  31423. __extends(_Primitive, _super);
  31424. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31425. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31426. if (mesh === void 0) { mesh = null; }
  31427. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31428. _this._canBeRegenerated = _canBeRegenerated;
  31429. _this._beingRegenerated = true;
  31430. _this.regenerate();
  31431. _this._beingRegenerated = false;
  31432. return _this;
  31433. }
  31434. _Primitive.prototype.canBeRegenerated = function () {
  31435. return this._canBeRegenerated;
  31436. };
  31437. _Primitive.prototype.regenerate = function () {
  31438. if (!this._canBeRegenerated) {
  31439. return;
  31440. }
  31441. this._beingRegenerated = true;
  31442. this.setAllVerticesData(this._regenerateVertexData(), false);
  31443. this._beingRegenerated = false;
  31444. };
  31445. _Primitive.prototype.asNewGeometry = function (id) {
  31446. return _super.prototype.copy.call(this, id);
  31447. };
  31448. // overrides
  31449. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31450. if (!this._beingRegenerated) {
  31451. return;
  31452. }
  31453. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31454. };
  31455. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31456. if (!this._beingRegenerated) {
  31457. return;
  31458. }
  31459. _super.prototype.setVerticesData.call(this, kind, data, false);
  31460. };
  31461. // to override
  31462. // protected
  31463. _Primitive.prototype._regenerateVertexData = function () {
  31464. throw new Error("Abstract method");
  31465. };
  31466. _Primitive.prototype.copy = function (id) {
  31467. throw new Error("Must be overriden in sub-classes.");
  31468. };
  31469. _Primitive.prototype.serialize = function () {
  31470. var serializationObject = _super.prototype.serialize.call(this);
  31471. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31472. return serializationObject;
  31473. };
  31474. return _Primitive;
  31475. }(Geometry));
  31476. Primitives._Primitive = _Primitive;
  31477. var Ribbon = /** @class */ (function (_super) {
  31478. __extends(Ribbon, _super);
  31479. // Members
  31480. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31481. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31482. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31483. _this.pathArray = pathArray;
  31484. _this.closeArray = closeArray;
  31485. _this.closePath = closePath;
  31486. _this.offset = offset;
  31487. _this.side = side;
  31488. return _this;
  31489. }
  31490. Ribbon.prototype._regenerateVertexData = function () {
  31491. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31492. };
  31493. Ribbon.prototype.copy = function (id) {
  31494. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31495. };
  31496. return Ribbon;
  31497. }(_Primitive));
  31498. Primitives.Ribbon = Ribbon;
  31499. var Box = /** @class */ (function (_super) {
  31500. __extends(Box, _super);
  31501. // Members
  31502. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31503. if (mesh === void 0) { mesh = null; }
  31504. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31505. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31506. _this.size = size;
  31507. _this.side = side;
  31508. return _this;
  31509. }
  31510. Box.prototype._regenerateVertexData = function () {
  31511. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31512. };
  31513. Box.prototype.copy = function (id) {
  31514. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31515. };
  31516. Box.prototype.serialize = function () {
  31517. var serializationObject = _super.prototype.serialize.call(this);
  31518. serializationObject.size = this.size;
  31519. return serializationObject;
  31520. };
  31521. Box.Parse = function (parsedBox, scene) {
  31522. if (scene.getGeometryByID(parsedBox.id)) {
  31523. return null; // null since geometry could be something else than a box...
  31524. }
  31525. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31526. if (BABYLON.Tags) {
  31527. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31528. }
  31529. scene.pushGeometry(box, true);
  31530. return box;
  31531. };
  31532. return Box;
  31533. }(_Primitive));
  31534. Primitives.Box = Box;
  31535. var Sphere = /** @class */ (function (_super) {
  31536. __extends(Sphere, _super);
  31537. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31538. if (mesh === void 0) { mesh = null; }
  31539. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31540. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31541. _this.segments = segments;
  31542. _this.diameter = diameter;
  31543. _this.side = side;
  31544. return _this;
  31545. }
  31546. Sphere.prototype._regenerateVertexData = function () {
  31547. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31548. };
  31549. Sphere.prototype.copy = function (id) {
  31550. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31551. };
  31552. Sphere.prototype.serialize = function () {
  31553. var serializationObject = _super.prototype.serialize.call(this);
  31554. serializationObject.segments = this.segments;
  31555. serializationObject.diameter = this.diameter;
  31556. return serializationObject;
  31557. };
  31558. Sphere.Parse = function (parsedSphere, scene) {
  31559. if (scene.getGeometryByID(parsedSphere.id)) {
  31560. return null; // null since geometry could be something else than a sphere...
  31561. }
  31562. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31563. if (BABYLON.Tags) {
  31564. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31565. }
  31566. scene.pushGeometry(sphere, true);
  31567. return sphere;
  31568. };
  31569. return Sphere;
  31570. }(_Primitive));
  31571. Primitives.Sphere = Sphere;
  31572. var Disc = /** @class */ (function (_super) {
  31573. __extends(Disc, _super);
  31574. // Members
  31575. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31576. if (mesh === void 0) { mesh = null; }
  31577. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31578. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31579. _this.radius = radius;
  31580. _this.tessellation = tessellation;
  31581. _this.side = side;
  31582. return _this;
  31583. }
  31584. Disc.prototype._regenerateVertexData = function () {
  31585. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31586. };
  31587. Disc.prototype.copy = function (id) {
  31588. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31589. };
  31590. return Disc;
  31591. }(_Primitive));
  31592. Primitives.Disc = Disc;
  31593. var Cylinder = /** @class */ (function (_super) {
  31594. __extends(Cylinder, _super);
  31595. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31596. if (subdivisions === void 0) { subdivisions = 1; }
  31597. if (mesh === void 0) { mesh = null; }
  31598. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31599. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31600. _this.height = height;
  31601. _this.diameterTop = diameterTop;
  31602. _this.diameterBottom = diameterBottom;
  31603. _this.tessellation = tessellation;
  31604. _this.subdivisions = subdivisions;
  31605. _this.side = side;
  31606. return _this;
  31607. }
  31608. Cylinder.prototype._regenerateVertexData = function () {
  31609. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31610. };
  31611. Cylinder.prototype.copy = function (id) {
  31612. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31613. };
  31614. Cylinder.prototype.serialize = function () {
  31615. var serializationObject = _super.prototype.serialize.call(this);
  31616. serializationObject.height = this.height;
  31617. serializationObject.diameterTop = this.diameterTop;
  31618. serializationObject.diameterBottom = this.diameterBottom;
  31619. serializationObject.tessellation = this.tessellation;
  31620. return serializationObject;
  31621. };
  31622. Cylinder.Parse = function (parsedCylinder, scene) {
  31623. if (scene.getGeometryByID(parsedCylinder.id)) {
  31624. return null; // null since geometry could be something else than a cylinder...
  31625. }
  31626. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31627. if (BABYLON.Tags) {
  31628. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31629. }
  31630. scene.pushGeometry(cylinder, true);
  31631. return cylinder;
  31632. };
  31633. return Cylinder;
  31634. }(_Primitive));
  31635. Primitives.Cylinder = Cylinder;
  31636. var Torus = /** @class */ (function (_super) {
  31637. __extends(Torus, _super);
  31638. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31639. if (mesh === void 0) { mesh = null; }
  31640. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31641. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31642. _this.diameter = diameter;
  31643. _this.thickness = thickness;
  31644. _this.tessellation = tessellation;
  31645. _this.side = side;
  31646. return _this;
  31647. }
  31648. Torus.prototype._regenerateVertexData = function () {
  31649. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31650. };
  31651. Torus.prototype.copy = function (id) {
  31652. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31653. };
  31654. Torus.prototype.serialize = function () {
  31655. var serializationObject = _super.prototype.serialize.call(this);
  31656. serializationObject.diameter = this.diameter;
  31657. serializationObject.thickness = this.thickness;
  31658. serializationObject.tessellation = this.tessellation;
  31659. return serializationObject;
  31660. };
  31661. Torus.Parse = function (parsedTorus, scene) {
  31662. if (scene.getGeometryByID(parsedTorus.id)) {
  31663. return null; // null since geometry could be something else than a torus...
  31664. }
  31665. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31666. if (BABYLON.Tags) {
  31667. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31668. }
  31669. scene.pushGeometry(torus, true);
  31670. return torus;
  31671. };
  31672. return Torus;
  31673. }(_Primitive));
  31674. Primitives.Torus = Torus;
  31675. var Ground = /** @class */ (function (_super) {
  31676. __extends(Ground, _super);
  31677. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31678. if (mesh === void 0) { mesh = null; }
  31679. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31680. _this.width = width;
  31681. _this.height = height;
  31682. _this.subdivisions = subdivisions;
  31683. return _this;
  31684. }
  31685. Ground.prototype._regenerateVertexData = function () {
  31686. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31687. };
  31688. Ground.prototype.copy = function (id) {
  31689. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31690. };
  31691. Ground.prototype.serialize = function () {
  31692. var serializationObject = _super.prototype.serialize.call(this);
  31693. serializationObject.width = this.width;
  31694. serializationObject.height = this.height;
  31695. serializationObject.subdivisions = this.subdivisions;
  31696. return serializationObject;
  31697. };
  31698. Ground.Parse = function (parsedGround, scene) {
  31699. if (scene.getGeometryByID(parsedGround.id)) {
  31700. return null; // null since geometry could be something else than a ground...
  31701. }
  31702. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31703. if (BABYLON.Tags) {
  31704. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31705. }
  31706. scene.pushGeometry(ground, true);
  31707. return ground;
  31708. };
  31709. return Ground;
  31710. }(_Primitive));
  31711. Primitives.Ground = Ground;
  31712. var TiledGround = /** @class */ (function (_super) {
  31713. __extends(TiledGround, _super);
  31714. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31715. if (mesh === void 0) { mesh = null; }
  31716. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31717. _this.xmin = xmin;
  31718. _this.zmin = zmin;
  31719. _this.xmax = xmax;
  31720. _this.zmax = zmax;
  31721. _this.subdivisions = subdivisions;
  31722. _this.precision = precision;
  31723. return _this;
  31724. }
  31725. TiledGround.prototype._regenerateVertexData = function () {
  31726. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31727. };
  31728. TiledGround.prototype.copy = function (id) {
  31729. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31730. };
  31731. return TiledGround;
  31732. }(_Primitive));
  31733. Primitives.TiledGround = TiledGround;
  31734. var Plane = /** @class */ (function (_super) {
  31735. __extends(Plane, _super);
  31736. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31737. if (mesh === void 0) { mesh = null; }
  31738. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31739. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31740. _this.size = size;
  31741. _this.side = side;
  31742. return _this;
  31743. }
  31744. Plane.prototype._regenerateVertexData = function () {
  31745. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31746. };
  31747. Plane.prototype.copy = function (id) {
  31748. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31749. };
  31750. Plane.prototype.serialize = function () {
  31751. var serializationObject = _super.prototype.serialize.call(this);
  31752. serializationObject.size = this.size;
  31753. return serializationObject;
  31754. };
  31755. Plane.Parse = function (parsedPlane, scene) {
  31756. if (scene.getGeometryByID(parsedPlane.id)) {
  31757. return null; // null since geometry could be something else than a ground...
  31758. }
  31759. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31760. if (BABYLON.Tags) {
  31761. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31762. }
  31763. scene.pushGeometry(plane, true);
  31764. return plane;
  31765. };
  31766. return Plane;
  31767. }(_Primitive));
  31768. Primitives.Plane = Plane;
  31769. var TorusKnot = /** @class */ (function (_super) {
  31770. __extends(TorusKnot, _super);
  31771. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31772. if (mesh === void 0) { mesh = null; }
  31773. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31774. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31775. _this.radius = radius;
  31776. _this.tube = tube;
  31777. _this.radialSegments = radialSegments;
  31778. _this.tubularSegments = tubularSegments;
  31779. _this.p = p;
  31780. _this.q = q;
  31781. _this.side = side;
  31782. return _this;
  31783. }
  31784. TorusKnot.prototype._regenerateVertexData = function () {
  31785. 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 });
  31786. };
  31787. TorusKnot.prototype.copy = function (id) {
  31788. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31789. };
  31790. TorusKnot.prototype.serialize = function () {
  31791. var serializationObject = _super.prototype.serialize.call(this);
  31792. serializationObject.radius = this.radius;
  31793. serializationObject.tube = this.tube;
  31794. serializationObject.radialSegments = this.radialSegments;
  31795. serializationObject.tubularSegments = this.tubularSegments;
  31796. serializationObject.p = this.p;
  31797. serializationObject.q = this.q;
  31798. return serializationObject;
  31799. };
  31800. ;
  31801. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31802. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31803. return null; // null since geometry could be something else than a ground...
  31804. }
  31805. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31806. if (BABYLON.Tags) {
  31807. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31808. }
  31809. scene.pushGeometry(torusKnot, true);
  31810. return torusKnot;
  31811. };
  31812. return TorusKnot;
  31813. }(_Primitive));
  31814. Primitives.TorusKnot = TorusKnot;
  31815. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31816. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31817. })(BABYLON || (BABYLON = {}));
  31818. //# sourceMappingURL=babylon.geometry.js.map
  31819. var BABYLON;
  31820. (function (BABYLON) {
  31821. var PostProcessManager = /** @class */ (function () {
  31822. function PostProcessManager(scene) {
  31823. this._vertexBuffers = {};
  31824. this._scene = scene;
  31825. }
  31826. PostProcessManager.prototype._prepareBuffers = function () {
  31827. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31828. return;
  31829. }
  31830. // VBO
  31831. var vertices = [];
  31832. vertices.push(1, 1);
  31833. vertices.push(-1, 1);
  31834. vertices.push(-1, -1);
  31835. vertices.push(1, -1);
  31836. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31837. this._buildIndexBuffer();
  31838. };
  31839. PostProcessManager.prototype._buildIndexBuffer = function () {
  31840. // Indices
  31841. var indices = [];
  31842. indices.push(0);
  31843. indices.push(1);
  31844. indices.push(2);
  31845. indices.push(0);
  31846. indices.push(2);
  31847. indices.push(3);
  31848. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31849. };
  31850. PostProcessManager.prototype._rebuild = function () {
  31851. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31852. if (!vb) {
  31853. return;
  31854. }
  31855. vb._rebuild();
  31856. this._buildIndexBuffer();
  31857. };
  31858. // Methods
  31859. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31860. if (sourceTexture === void 0) { sourceTexture = null; }
  31861. if (postProcesses === void 0) { postProcesses = null; }
  31862. var camera = this._scene.activeCamera;
  31863. if (!camera) {
  31864. return false;
  31865. }
  31866. var postProcesses = postProcesses || camera._postProcesses;
  31867. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31868. return false;
  31869. }
  31870. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31871. return true;
  31872. };
  31873. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31874. if (targetTexture === void 0) { targetTexture = null; }
  31875. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31876. if (!this._scene.activeCamera) {
  31877. return;
  31878. }
  31879. var engine = this._scene.getEngine();
  31880. for (var index = 0; index < postProcesses.length; index++) {
  31881. if (index < postProcesses.length - 1) {
  31882. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31883. }
  31884. else {
  31885. if (targetTexture) {
  31886. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31887. }
  31888. else {
  31889. engine.restoreDefaultFramebuffer();
  31890. }
  31891. }
  31892. var pp = postProcesses[index];
  31893. var effect = pp.apply();
  31894. if (effect) {
  31895. pp.onBeforeRenderObservable.notifyObservers(effect);
  31896. // VBOs
  31897. this._prepareBuffers();
  31898. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31899. // Draw order
  31900. engine.draw(true, 0, 6);
  31901. pp.onAfterRenderObservable.notifyObservers(effect);
  31902. }
  31903. }
  31904. // Restore depth buffer
  31905. engine.setDepthBuffer(true);
  31906. engine.setDepthWrite(true);
  31907. };
  31908. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31909. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31910. var camera = this._scene.activeCamera;
  31911. if (!camera) {
  31912. return;
  31913. }
  31914. postProcesses = postProcesses || camera._postProcesses;
  31915. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31916. return;
  31917. }
  31918. var engine = this._scene.getEngine();
  31919. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31920. if (index < len - 1) {
  31921. postProcesses[index + 1].activate(camera, targetTexture);
  31922. }
  31923. else {
  31924. if (targetTexture) {
  31925. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31926. }
  31927. else {
  31928. engine.restoreDefaultFramebuffer();
  31929. }
  31930. }
  31931. if (doNotPresent) {
  31932. break;
  31933. }
  31934. var pp = postProcesses[index];
  31935. var effect = pp.apply();
  31936. if (effect) {
  31937. pp.onBeforeRenderObservable.notifyObservers(effect);
  31938. // VBOs
  31939. this._prepareBuffers();
  31940. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31941. // Draw order
  31942. engine.draw(true, 0, 6);
  31943. pp.onAfterRenderObservable.notifyObservers(effect);
  31944. }
  31945. }
  31946. // Restore states
  31947. engine.setDepthBuffer(true);
  31948. engine.setDepthWrite(true);
  31949. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31950. };
  31951. PostProcessManager.prototype.dispose = function () {
  31952. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31953. if (buffer) {
  31954. buffer.dispose();
  31955. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31956. }
  31957. if (this._indexBuffer) {
  31958. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31959. this._indexBuffer = null;
  31960. }
  31961. };
  31962. return PostProcessManager;
  31963. }());
  31964. BABYLON.PostProcessManager = PostProcessManager;
  31965. })(BABYLON || (BABYLON = {}));
  31966. //# sourceMappingURL=babylon.postProcessManager.js.map
  31967. var BABYLON;
  31968. (function (BABYLON) {
  31969. /**
  31970. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31971. */
  31972. var PerformanceMonitor = /** @class */ (function () {
  31973. /**
  31974. * constructor
  31975. * @param frameSampleSize The number of samples required to saturate the sliding window
  31976. */
  31977. function PerformanceMonitor(frameSampleSize) {
  31978. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31979. this._enabled = true;
  31980. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31981. }
  31982. /**
  31983. * Samples current frame
  31984. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31985. */
  31986. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31987. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31988. if (!this._enabled)
  31989. return;
  31990. if (this._lastFrameTimeMs != null) {
  31991. var dt = timeMs - this._lastFrameTimeMs;
  31992. this._rollingFrameTime.add(dt);
  31993. }
  31994. this._lastFrameTimeMs = timeMs;
  31995. };
  31996. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31997. /**
  31998. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31999. * @return Average frame time in milliseconds
  32000. */
  32001. get: function () {
  32002. return this._rollingFrameTime.average;
  32003. },
  32004. enumerable: true,
  32005. configurable: true
  32006. });
  32007. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32008. /**
  32009. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32010. * @return Frame time variance in milliseconds squared
  32011. */
  32012. get: function () {
  32013. return this._rollingFrameTime.variance;
  32014. },
  32015. enumerable: true,
  32016. configurable: true
  32017. });
  32018. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32019. /**
  32020. * Returns the frame time of the most recent frame
  32021. * @return Frame time in milliseconds
  32022. */
  32023. get: function () {
  32024. return this._rollingFrameTime.history(0);
  32025. },
  32026. enumerable: true,
  32027. configurable: true
  32028. });
  32029. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32030. /**
  32031. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32032. * @return Framerate in frames per second
  32033. */
  32034. get: function () {
  32035. return 1000.0 / this._rollingFrameTime.average;
  32036. },
  32037. enumerable: true,
  32038. configurable: true
  32039. });
  32040. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32041. /**
  32042. * Returns the average framerate in frames per second using the most recent frame time
  32043. * @return Framerate in frames per second
  32044. */
  32045. get: function () {
  32046. var history = this._rollingFrameTime.history(0);
  32047. if (history === 0) {
  32048. return 0;
  32049. }
  32050. return 1000.0 / history;
  32051. },
  32052. enumerable: true,
  32053. configurable: true
  32054. });
  32055. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32056. /**
  32057. * Returns true if enough samples have been taken to completely fill the sliding window
  32058. * @return true if saturated
  32059. */
  32060. get: function () {
  32061. return this._rollingFrameTime.isSaturated();
  32062. },
  32063. enumerable: true,
  32064. configurable: true
  32065. });
  32066. /**
  32067. * Enables contributions to the sliding window sample set
  32068. */
  32069. PerformanceMonitor.prototype.enable = function () {
  32070. this._enabled = true;
  32071. };
  32072. /**
  32073. * Disables contributions to the sliding window sample set
  32074. * Samples will not be interpolated over the disabled period
  32075. */
  32076. PerformanceMonitor.prototype.disable = function () {
  32077. this._enabled = false;
  32078. //clear last sample to avoid interpolating over the disabled period when next enabled
  32079. this._lastFrameTimeMs = null;
  32080. this._lastChangeTimeMs = null;
  32081. };
  32082. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32083. /**
  32084. * Returns true if sampling is enabled
  32085. * @return true if enabled
  32086. */
  32087. get: function () {
  32088. return this._enabled;
  32089. },
  32090. enumerable: true,
  32091. configurable: true
  32092. });
  32093. /**
  32094. * Resets performance monitor
  32095. */
  32096. PerformanceMonitor.prototype.reset = function () {
  32097. //clear last sample to avoid interpolating over the disabled period when next enabled
  32098. this._lastFrameTimeMs = null;
  32099. this._lastChangeTimeMs = null;
  32100. //wipe record
  32101. this._rollingFrameTime.reset();
  32102. };
  32103. return PerformanceMonitor;
  32104. }());
  32105. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32106. /**
  32107. * RollingAverage
  32108. *
  32109. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32110. */
  32111. var RollingAverage = /** @class */ (function () {
  32112. /**
  32113. * constructor
  32114. * @param length The number of samples required to saturate the sliding window
  32115. */
  32116. function RollingAverage(length) {
  32117. this._samples = new Array(length);
  32118. this.reset();
  32119. }
  32120. /**
  32121. * Adds a sample to the sample set
  32122. * @param v The sample value
  32123. */
  32124. RollingAverage.prototype.add = function (v) {
  32125. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32126. var delta;
  32127. //we need to check if we've already wrapped round
  32128. if (this.isSaturated()) {
  32129. //remove bottom of stack from mean
  32130. var bottomValue = this._samples[this._pos];
  32131. delta = bottomValue - this.average;
  32132. this.average -= delta / (this._sampleCount - 1);
  32133. this._m2 -= delta * (bottomValue - this.average);
  32134. }
  32135. else {
  32136. this._sampleCount++;
  32137. }
  32138. //add new value to mean
  32139. delta = v - this.average;
  32140. this.average += delta / (this._sampleCount);
  32141. this._m2 += delta * (v - this.average);
  32142. //set the new variance
  32143. this.variance = this._m2 / (this._sampleCount - 1);
  32144. this._samples[this._pos] = v;
  32145. this._pos++;
  32146. this._pos %= this._samples.length; //positive wrap around
  32147. };
  32148. /**
  32149. * Returns previously added values or null if outside of history or outside the sliding window domain
  32150. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32151. * @return Value previously recorded with add() or null if outside of range
  32152. */
  32153. RollingAverage.prototype.history = function (i) {
  32154. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32155. return 0;
  32156. }
  32157. var i0 = this._wrapPosition(this._pos - 1.0);
  32158. return this._samples[this._wrapPosition(i0 - i)];
  32159. };
  32160. /**
  32161. * Returns true if enough samples have been taken to completely fill the sliding window
  32162. * @return true if sample-set saturated
  32163. */
  32164. RollingAverage.prototype.isSaturated = function () {
  32165. return this._sampleCount >= this._samples.length;
  32166. };
  32167. /**
  32168. * Resets the rolling average (equivalent to 0 samples taken so far)
  32169. */
  32170. RollingAverage.prototype.reset = function () {
  32171. this.average = 0;
  32172. this.variance = 0;
  32173. this._sampleCount = 0;
  32174. this._pos = 0;
  32175. this._m2 = 0;
  32176. };
  32177. /**
  32178. * Wraps a value around the sample range boundaries
  32179. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32180. * @return Wrapped position in sample range
  32181. */
  32182. RollingAverage.prototype._wrapPosition = function (i) {
  32183. var max = this._samples.length;
  32184. return ((i % max) + max) % max;
  32185. };
  32186. return RollingAverage;
  32187. }());
  32188. BABYLON.RollingAverage = RollingAverage;
  32189. })(BABYLON || (BABYLON = {}));
  32190. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32191. var BABYLON;
  32192. (function (BABYLON) {
  32193. /**
  32194. * This groups together the common properties used for image processing either in direct forward pass
  32195. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32196. * or not.
  32197. */
  32198. var ImageProcessingConfiguration = /** @class */ (function () {
  32199. function ImageProcessingConfiguration() {
  32200. /**
  32201. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32202. */
  32203. this.colorCurves = new BABYLON.ColorCurves();
  32204. this._colorCurvesEnabled = false;
  32205. this._colorGradingEnabled = false;
  32206. this._colorGradingWithGreenDepth = true;
  32207. this._colorGradingBGR = true;
  32208. this._exposure = 1.0;
  32209. this._toneMappingEnabled = false;
  32210. this._contrast = 1.0;
  32211. /**
  32212. * Vignette stretch size.
  32213. */
  32214. this.vignetteStretch = 0;
  32215. /**
  32216. * Vignette centre X Offset.
  32217. */
  32218. this.vignetteCentreX = 0;
  32219. /**
  32220. * Vignette centre Y Offset.
  32221. */
  32222. this.vignetteCentreY = 0;
  32223. /**
  32224. * Vignette weight or intensity of the vignette effect.
  32225. */
  32226. this.vignetteWeight = 1.5;
  32227. /**
  32228. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32229. * if vignetteEnabled is set to true.
  32230. */
  32231. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32232. /**
  32233. * Camera field of view used by the Vignette effect.
  32234. */
  32235. this.vignetteCameraFov = 0.5;
  32236. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32237. this._vignetteEnabled = false;
  32238. this._applyByPostProcess = false;
  32239. /**
  32240. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32241. * @type {BABYLON.Observable}
  32242. */
  32243. this.onUpdateParameters = new BABYLON.Observable();
  32244. }
  32245. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32246. /**
  32247. * Gets wether the color curves effect is enabled.
  32248. */
  32249. get: function () {
  32250. return this._colorCurvesEnabled;
  32251. },
  32252. /**
  32253. * Sets wether the color curves effect is enabled.
  32254. */
  32255. set: function (value) {
  32256. if (this._colorCurvesEnabled === value) {
  32257. return;
  32258. }
  32259. this._colorCurvesEnabled = value;
  32260. this._updateParameters();
  32261. },
  32262. enumerable: true,
  32263. configurable: true
  32264. });
  32265. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32266. /**
  32267. * Gets wether the color grading effect is enabled.
  32268. */
  32269. get: function () {
  32270. return this._colorGradingEnabled;
  32271. },
  32272. /**
  32273. * Sets wether the color grading effect is enabled.
  32274. */
  32275. set: function (value) {
  32276. if (this._colorGradingEnabled === value) {
  32277. return;
  32278. }
  32279. this._colorGradingEnabled = value;
  32280. this._updateParameters();
  32281. },
  32282. enumerable: true,
  32283. configurable: true
  32284. });
  32285. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32286. /**
  32287. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32288. */
  32289. get: function () {
  32290. return this._colorGradingWithGreenDepth;
  32291. },
  32292. /**
  32293. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32294. */
  32295. set: function (value) {
  32296. if (this._colorGradingWithGreenDepth === value) {
  32297. return;
  32298. }
  32299. this._colorGradingWithGreenDepth = value;
  32300. this._updateParameters();
  32301. },
  32302. enumerable: true,
  32303. configurable: true
  32304. });
  32305. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32306. /**
  32307. * Gets wether the color grading texture contains BGR values.
  32308. */
  32309. get: function () {
  32310. return this._colorGradingBGR;
  32311. },
  32312. /**
  32313. * Sets wether the color grading texture contains BGR values.
  32314. */
  32315. set: function (value) {
  32316. if (this._colorGradingBGR === value) {
  32317. return;
  32318. }
  32319. this._colorGradingBGR = value;
  32320. this._updateParameters();
  32321. },
  32322. enumerable: true,
  32323. configurable: true
  32324. });
  32325. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32326. /**
  32327. * Gets the Exposure used in the effect.
  32328. */
  32329. get: function () {
  32330. return this._exposure;
  32331. },
  32332. /**
  32333. * Sets the Exposure used in the effect.
  32334. */
  32335. set: function (value) {
  32336. if (this._exposure === value) {
  32337. return;
  32338. }
  32339. this._exposure = value;
  32340. this._updateParameters();
  32341. },
  32342. enumerable: true,
  32343. configurable: true
  32344. });
  32345. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32346. /**
  32347. * Gets wether the tone mapping effect is enabled.
  32348. */
  32349. get: function () {
  32350. return this._toneMappingEnabled;
  32351. },
  32352. /**
  32353. * Sets wether the tone mapping effect is enabled.
  32354. */
  32355. set: function (value) {
  32356. if (this._toneMappingEnabled === value) {
  32357. return;
  32358. }
  32359. this._toneMappingEnabled = value;
  32360. this._updateParameters();
  32361. },
  32362. enumerable: true,
  32363. configurable: true
  32364. });
  32365. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32366. /**
  32367. * Gets the contrast used in the effect.
  32368. */
  32369. get: function () {
  32370. return this._contrast;
  32371. },
  32372. /**
  32373. * Sets the contrast used in the effect.
  32374. */
  32375. set: function (value) {
  32376. if (this._contrast === value) {
  32377. return;
  32378. }
  32379. this._contrast = value;
  32380. this._updateParameters();
  32381. },
  32382. enumerable: true,
  32383. configurable: true
  32384. });
  32385. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32386. /**
  32387. * Gets the vignette blend mode allowing different kind of effect.
  32388. */
  32389. get: function () {
  32390. return this._vignetteBlendMode;
  32391. },
  32392. /**
  32393. * Sets the vignette blend mode allowing different kind of effect.
  32394. */
  32395. set: function (value) {
  32396. if (this._vignetteBlendMode === value) {
  32397. return;
  32398. }
  32399. this._vignetteBlendMode = value;
  32400. this._updateParameters();
  32401. },
  32402. enumerable: true,
  32403. configurable: true
  32404. });
  32405. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32406. /**
  32407. * Gets wether the vignette effect is enabled.
  32408. */
  32409. get: function () {
  32410. return this._vignetteEnabled;
  32411. },
  32412. /**
  32413. * Sets wether the vignette effect is enabled.
  32414. */
  32415. set: function (value) {
  32416. if (this._vignetteEnabled === value) {
  32417. return;
  32418. }
  32419. this._vignetteEnabled = value;
  32420. this._updateParameters();
  32421. },
  32422. enumerable: true,
  32423. configurable: true
  32424. });
  32425. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32426. /**
  32427. * Gets wether the image processing is applied through a post process or not.
  32428. */
  32429. get: function () {
  32430. return this._applyByPostProcess;
  32431. },
  32432. /**
  32433. * Sets wether the image processing is applied through a post process or not.
  32434. */
  32435. set: function (value) {
  32436. if (this._applyByPostProcess === value) {
  32437. return;
  32438. }
  32439. this._applyByPostProcess = value;
  32440. this._updateParameters();
  32441. },
  32442. enumerable: true,
  32443. configurable: true
  32444. });
  32445. /**
  32446. * Method called each time the image processing information changes requires to recompile the effect.
  32447. */
  32448. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32449. this.onUpdateParameters.notifyObservers(this);
  32450. };
  32451. ImageProcessingConfiguration.prototype.getClassName = function () {
  32452. return "ImageProcessingConfiguration";
  32453. };
  32454. /**
  32455. * Prepare the list of uniforms associated with the Image Processing effects.
  32456. * @param uniformsList The list of uniforms used in the effect
  32457. * @param defines the list of defines currently in use
  32458. */
  32459. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32460. if (defines.EXPOSURE) {
  32461. uniforms.push("exposureLinear");
  32462. }
  32463. if (defines.CONTRAST) {
  32464. uniforms.push("contrast");
  32465. }
  32466. if (defines.COLORGRADING) {
  32467. uniforms.push("colorTransformSettings");
  32468. }
  32469. if (defines.VIGNETTE) {
  32470. uniforms.push("vInverseScreenSize");
  32471. uniforms.push("vignetteSettings1");
  32472. uniforms.push("vignetteSettings2");
  32473. }
  32474. if (defines.COLORCURVES) {
  32475. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32476. }
  32477. };
  32478. /**
  32479. * Prepare the list of samplers associated with the Image Processing effects.
  32480. * @param uniformsList The list of uniforms used in the effect
  32481. * @param defines the list of defines currently in use
  32482. */
  32483. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32484. if (defines.COLORGRADING) {
  32485. samplersList.push("txColorTransform");
  32486. }
  32487. };
  32488. /**
  32489. * Prepare the list of defines associated to the shader.
  32490. * @param defines the list of defines to complete
  32491. */
  32492. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32493. if (forPostProcess === void 0) { forPostProcess = false; }
  32494. if (forPostProcess !== this.applyByPostProcess) {
  32495. defines.VIGNETTE = false;
  32496. defines.TONEMAPPING = false;
  32497. defines.CONTRAST = false;
  32498. defines.EXPOSURE = false;
  32499. defines.COLORCURVES = false;
  32500. defines.COLORGRADING = false;
  32501. defines.COLORGRADING3D = false;
  32502. defines.IMAGEPROCESSING = false;
  32503. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32504. return;
  32505. }
  32506. defines.VIGNETTE = this.vignetteEnabled;
  32507. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32508. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32509. defines.TONEMAPPING = this.toneMappingEnabled;
  32510. defines.CONTRAST = (this.contrast !== 1.0);
  32511. defines.EXPOSURE = (this.exposure !== 1.0);
  32512. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32513. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32514. if (defines.COLORGRADING) {
  32515. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32516. }
  32517. else {
  32518. defines.COLORGRADING3D = false;
  32519. }
  32520. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32521. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32522. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32523. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32524. };
  32525. /**
  32526. * Returns true if all the image processing information are ready.
  32527. */
  32528. ImageProcessingConfiguration.prototype.isReady = function () {
  32529. // Color Grading texure can not be none blocking.
  32530. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32531. };
  32532. /**
  32533. * Binds the image processing to the shader.
  32534. * @param effect The effect to bind to
  32535. */
  32536. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32537. if (aspectRatio === void 0) { aspectRatio = 1; }
  32538. // Color Curves
  32539. if (this._colorCurvesEnabled && this.colorCurves) {
  32540. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32541. }
  32542. // Vignette
  32543. if (this._vignetteEnabled) {
  32544. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32545. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32546. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32547. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32548. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32549. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32550. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32551. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32552. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32553. var vignettePower = -2.0 * this.vignetteWeight;
  32554. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32555. }
  32556. // Exposure
  32557. effect.setFloat("exposureLinear", this.exposure);
  32558. // Contrast
  32559. effect.setFloat("contrast", this.contrast);
  32560. // Color transform settings
  32561. if (this.colorGradingTexture) {
  32562. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32563. var textureSize = this.colorGradingTexture.getSize().height;
  32564. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32565. 0.5 / textureSize, // textureOffset
  32566. textureSize, // textureSize
  32567. this.colorGradingTexture.level // weight
  32568. );
  32569. }
  32570. };
  32571. /**
  32572. * Clones the current image processing instance.
  32573. * @return The cloned image processing
  32574. */
  32575. ImageProcessingConfiguration.prototype.clone = function () {
  32576. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32577. };
  32578. /**
  32579. * Serializes the current image processing instance to a json representation.
  32580. * @return a JSON representation
  32581. */
  32582. ImageProcessingConfiguration.prototype.serialize = function () {
  32583. return BABYLON.SerializationHelper.Serialize(this);
  32584. };
  32585. /**
  32586. * Parses the image processing from a json representation.
  32587. * @param source the JSON source to parse
  32588. * @return The parsed image processing
  32589. */
  32590. ImageProcessingConfiguration.Parse = function (source) {
  32591. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32592. };
  32593. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32594. /**
  32595. * Used to apply the vignette as a mix with the pixel color.
  32596. */
  32597. get: function () {
  32598. return this._VIGNETTEMODE_MULTIPLY;
  32599. },
  32600. enumerable: true,
  32601. configurable: true
  32602. });
  32603. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32604. /**
  32605. * Used to apply the vignette as a replacement of the pixel color.
  32606. */
  32607. get: function () {
  32608. return this._VIGNETTEMODE_OPAQUE;
  32609. },
  32610. enumerable: true,
  32611. configurable: true
  32612. });
  32613. // Static constants associated to the image processing.
  32614. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32615. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32616. __decorate([
  32617. BABYLON.serializeAsColorCurves()
  32618. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32619. __decorate([
  32620. BABYLON.serialize()
  32621. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32622. __decorate([
  32623. BABYLON.serializeAsTexture()
  32624. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32625. __decorate([
  32626. BABYLON.serialize()
  32627. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32628. __decorate([
  32629. BABYLON.serialize()
  32630. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32631. __decorate([
  32632. BABYLON.serialize()
  32633. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32634. __decorate([
  32635. BABYLON.serialize()
  32636. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32637. __decorate([
  32638. BABYLON.serialize()
  32639. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32640. __decorate([
  32641. BABYLON.serialize()
  32642. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32643. __decorate([
  32644. BABYLON.serialize()
  32645. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32646. __decorate([
  32647. BABYLON.serialize()
  32648. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32649. __decorate([
  32650. BABYLON.serialize()
  32651. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32652. __decorate([
  32653. BABYLON.serialize()
  32654. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32655. __decorate([
  32656. BABYLON.serializeAsColor4()
  32657. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32658. __decorate([
  32659. BABYLON.serialize()
  32660. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32661. __decorate([
  32662. BABYLON.serialize()
  32663. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32664. __decorate([
  32665. BABYLON.serialize()
  32666. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32667. __decorate([
  32668. BABYLON.serialize()
  32669. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32670. return ImageProcessingConfiguration;
  32671. }());
  32672. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32673. })(BABYLON || (BABYLON = {}));
  32674. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32675. var BABYLON;
  32676. (function (BABYLON) {
  32677. /**
  32678. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32679. * It can help converting any input color in a desired output one. This can then be used to create effects
  32680. * from sepia, black and white to sixties or futuristic rendering...
  32681. *
  32682. * The only supported format is currently 3dl.
  32683. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32684. */
  32685. var ColorGradingTexture = /** @class */ (function (_super) {
  32686. __extends(ColorGradingTexture, _super);
  32687. /**
  32688. * Instantiates a ColorGradingTexture from the following parameters.
  32689. *
  32690. * @param url The location of the color gradind data (currently only supporting 3dl)
  32691. * @param scene The scene the texture will be used in
  32692. */
  32693. function ColorGradingTexture(url, scene) {
  32694. var _this = _super.call(this, scene) || this;
  32695. if (!url) {
  32696. return _this;
  32697. }
  32698. _this._engine = scene.getEngine();
  32699. _this._textureMatrix = BABYLON.Matrix.Identity();
  32700. _this.name = url;
  32701. _this.url = url;
  32702. _this.hasAlpha = false;
  32703. _this.isCube = false;
  32704. _this.is3D = _this._engine.webGLVersion > 1;
  32705. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32706. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32707. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32708. _this.anisotropicFilteringLevel = 1;
  32709. _this._texture = _this._getFromCache(url, true);
  32710. if (!_this._texture) {
  32711. if (!scene.useDelayedTextureLoading) {
  32712. _this.loadTexture();
  32713. }
  32714. else {
  32715. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32716. }
  32717. }
  32718. return _this;
  32719. }
  32720. /**
  32721. * Returns the texture matrix used in most of the material.
  32722. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32723. */
  32724. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32725. return this._textureMatrix;
  32726. };
  32727. /**
  32728. * Occurs when the file being loaded is a .3dl LUT file.
  32729. */
  32730. ColorGradingTexture.prototype.load3dlTexture = function () {
  32731. var engine = this._engine;
  32732. var texture;
  32733. if (engine.webGLVersion === 1) {
  32734. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32735. }
  32736. else {
  32737. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32738. }
  32739. this._texture = texture;
  32740. var callback = function (text) {
  32741. var data = null;
  32742. var tempData = null;
  32743. var line;
  32744. var lines = text.split('\n');
  32745. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32746. var maxColor = 0;
  32747. for (var i = 0; i < lines.length; i++) {
  32748. line = lines[i];
  32749. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32750. continue;
  32751. if (line.indexOf('#') === 0)
  32752. continue;
  32753. var words = line.split(" ");
  32754. if (size === 0) {
  32755. // Number of space + one
  32756. size = words.length;
  32757. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32758. tempData = new Float32Array(size * size * size * 4);
  32759. continue;
  32760. }
  32761. if (size != 0) {
  32762. var r = Math.max(parseInt(words[0]), 0);
  32763. var g = Math.max(parseInt(words[1]), 0);
  32764. var b = Math.max(parseInt(words[2]), 0);
  32765. maxColor = Math.max(r, maxColor);
  32766. maxColor = Math.max(g, maxColor);
  32767. maxColor = Math.max(b, maxColor);
  32768. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32769. if (tempData) {
  32770. tempData[pixelStorageIndex + 0] = r;
  32771. tempData[pixelStorageIndex + 1] = g;
  32772. tempData[pixelStorageIndex + 2] = b;
  32773. }
  32774. pixelIndexSlice++;
  32775. if (pixelIndexSlice % size == 0) {
  32776. pixelIndexH++;
  32777. pixelIndexSlice = 0;
  32778. if (pixelIndexH % size == 0) {
  32779. pixelIndexW++;
  32780. pixelIndexH = 0;
  32781. }
  32782. }
  32783. }
  32784. }
  32785. if (tempData && data) {
  32786. for (var i = 0; i < tempData.length; i++) {
  32787. if (i > 0 && (i + 1) % 4 === 0) {
  32788. data[i] = 255;
  32789. }
  32790. else {
  32791. var value = tempData[i];
  32792. data[i] = (value / maxColor * 255);
  32793. }
  32794. }
  32795. }
  32796. if (texture.is3D) {
  32797. texture.updateSize(size, size, size);
  32798. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32799. }
  32800. else {
  32801. texture.updateSize(size * size, size);
  32802. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32803. }
  32804. };
  32805. BABYLON.Tools.LoadFile(this.url, callback);
  32806. return this._texture;
  32807. };
  32808. /**
  32809. * Starts the loading process of the texture.
  32810. */
  32811. ColorGradingTexture.prototype.loadTexture = function () {
  32812. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32813. this.load3dlTexture();
  32814. }
  32815. };
  32816. /**
  32817. * Clones the color gradind texture.
  32818. */
  32819. ColorGradingTexture.prototype.clone = function () {
  32820. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32821. // Base texture
  32822. newTexture.level = this.level;
  32823. return newTexture;
  32824. };
  32825. /**
  32826. * Called during delayed load for textures.
  32827. */
  32828. ColorGradingTexture.prototype.delayLoad = function () {
  32829. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32830. return;
  32831. }
  32832. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32833. this._texture = this._getFromCache(this.url, true);
  32834. if (!this._texture) {
  32835. this.loadTexture();
  32836. }
  32837. };
  32838. /**
  32839. * Parses a color grading texture serialized by Babylon.
  32840. * @param parsedTexture The texture information being parsedTexture
  32841. * @param scene The scene to load the texture in
  32842. * @param rootUrl The root url of the data assets to load
  32843. * @return A color gradind texture
  32844. */
  32845. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32846. var texture = null;
  32847. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32848. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32849. texture.name = parsedTexture.name;
  32850. texture.level = parsedTexture.level;
  32851. }
  32852. return texture;
  32853. };
  32854. /**
  32855. * Serializes the LUT texture to json format.
  32856. */
  32857. ColorGradingTexture.prototype.serialize = function () {
  32858. if (!this.name) {
  32859. return null;
  32860. }
  32861. var serializationObject = {};
  32862. serializationObject.name = this.name;
  32863. serializationObject.level = this.level;
  32864. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32865. return serializationObject;
  32866. };
  32867. /**
  32868. * Empty line regex stored for GC.
  32869. */
  32870. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32871. return ColorGradingTexture;
  32872. }(BABYLON.BaseTexture));
  32873. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32874. })(BABYLON || (BABYLON = {}));
  32875. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32876. var BABYLON;
  32877. (function (BABYLON) {
  32878. /**
  32879. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32880. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32881. * 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;
  32882. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32883. */
  32884. var ColorCurves = /** @class */ (function () {
  32885. function ColorCurves() {
  32886. this._dirty = true;
  32887. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32888. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32889. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32890. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32891. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32892. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32893. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32894. this._globalHue = 30;
  32895. this._globalDensity = 0;
  32896. this._globalSaturation = 0;
  32897. this._globalExposure = 0;
  32898. this._highlightsHue = 30;
  32899. this._highlightsDensity = 0;
  32900. this._highlightsSaturation = 0;
  32901. this._highlightsExposure = 0;
  32902. this._midtonesHue = 30;
  32903. this._midtonesDensity = 0;
  32904. this._midtonesSaturation = 0;
  32905. this._midtonesExposure = 0;
  32906. this._shadowsHue = 30;
  32907. this._shadowsDensity = 0;
  32908. this._shadowsSaturation = 0;
  32909. this._shadowsExposure = 0;
  32910. }
  32911. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32912. /**
  32913. * Gets the global Hue value.
  32914. * 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).
  32915. */
  32916. get: function () {
  32917. return this._globalHue;
  32918. },
  32919. /**
  32920. * Sets the global Hue value.
  32921. * 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).
  32922. */
  32923. set: function (value) {
  32924. this._globalHue = value;
  32925. this._dirty = true;
  32926. },
  32927. enumerable: true,
  32928. configurable: true
  32929. });
  32930. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32931. /**
  32932. * Gets the global Density value.
  32933. * 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.
  32934. * Values less than zero provide a filter of opposite hue.
  32935. */
  32936. get: function () {
  32937. return this._globalDensity;
  32938. },
  32939. /**
  32940. * Sets the global Density value.
  32941. * 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.
  32942. * Values less than zero provide a filter of opposite hue.
  32943. */
  32944. set: function (value) {
  32945. this._globalDensity = value;
  32946. this._dirty = true;
  32947. },
  32948. enumerable: true,
  32949. configurable: true
  32950. });
  32951. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32952. /**
  32953. * Gets the global Saturation value.
  32954. * 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.
  32955. */
  32956. get: function () {
  32957. return this._globalSaturation;
  32958. },
  32959. /**
  32960. * Sets the global Saturation value.
  32961. * 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.
  32962. */
  32963. set: function (value) {
  32964. this._globalSaturation = value;
  32965. this._dirty = true;
  32966. },
  32967. enumerable: true,
  32968. configurable: true
  32969. });
  32970. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32971. /**
  32972. * Gets the highlights Hue value.
  32973. * 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).
  32974. */
  32975. get: function () {
  32976. return this._highlightsHue;
  32977. },
  32978. /**
  32979. * Sets the highlights Hue value.
  32980. * 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).
  32981. */
  32982. set: function (value) {
  32983. this._highlightsHue = value;
  32984. this._dirty = true;
  32985. },
  32986. enumerable: true,
  32987. configurable: true
  32988. });
  32989. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32990. /**
  32991. * Gets the highlights Density value.
  32992. * 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.
  32993. * Values less than zero provide a filter of opposite hue.
  32994. */
  32995. get: function () {
  32996. return this._highlightsDensity;
  32997. },
  32998. /**
  32999. * Sets the highlights Density value.
  33000. * 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.
  33001. * Values less than zero provide a filter of opposite hue.
  33002. */
  33003. set: function (value) {
  33004. this._highlightsDensity = value;
  33005. this._dirty = true;
  33006. },
  33007. enumerable: true,
  33008. configurable: true
  33009. });
  33010. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33011. /**
  33012. * Gets the highlights Saturation value.
  33013. * 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.
  33014. */
  33015. get: function () {
  33016. return this._highlightsSaturation;
  33017. },
  33018. /**
  33019. * Sets the highlights Saturation value.
  33020. * 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.
  33021. */
  33022. set: function (value) {
  33023. this._highlightsSaturation = value;
  33024. this._dirty = true;
  33025. },
  33026. enumerable: true,
  33027. configurable: true
  33028. });
  33029. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33030. /**
  33031. * Gets the highlights Exposure value.
  33032. * 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.
  33033. */
  33034. get: function () {
  33035. return this._highlightsExposure;
  33036. },
  33037. /**
  33038. * Sets the highlights Exposure value.
  33039. * 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.
  33040. */
  33041. set: function (value) {
  33042. this._highlightsExposure = value;
  33043. this._dirty = true;
  33044. },
  33045. enumerable: true,
  33046. configurable: true
  33047. });
  33048. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33049. /**
  33050. * Gets the midtones Hue value.
  33051. * 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).
  33052. */
  33053. get: function () {
  33054. return this._midtonesHue;
  33055. },
  33056. /**
  33057. * Sets the midtones Hue value.
  33058. * 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).
  33059. */
  33060. set: function (value) {
  33061. this._midtonesHue = value;
  33062. this._dirty = true;
  33063. },
  33064. enumerable: true,
  33065. configurable: true
  33066. });
  33067. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33068. /**
  33069. * Gets the midtones Density value.
  33070. * 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.
  33071. * Values less than zero provide a filter of opposite hue.
  33072. */
  33073. get: function () {
  33074. return this._midtonesDensity;
  33075. },
  33076. /**
  33077. * Sets the midtones Density value.
  33078. * 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.
  33079. * Values less than zero provide a filter of opposite hue.
  33080. */
  33081. set: function (value) {
  33082. this._midtonesDensity = value;
  33083. this._dirty = true;
  33084. },
  33085. enumerable: true,
  33086. configurable: true
  33087. });
  33088. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33089. /**
  33090. * Gets the midtones Saturation value.
  33091. * 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.
  33092. */
  33093. get: function () {
  33094. return this._midtonesSaturation;
  33095. },
  33096. /**
  33097. * Sets the midtones Saturation value.
  33098. * 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.
  33099. */
  33100. set: function (value) {
  33101. this._midtonesSaturation = value;
  33102. this._dirty = true;
  33103. },
  33104. enumerable: true,
  33105. configurable: true
  33106. });
  33107. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33108. /**
  33109. * Gets the midtones Exposure value.
  33110. * 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.
  33111. */
  33112. get: function () {
  33113. return this._midtonesExposure;
  33114. },
  33115. /**
  33116. * Sets the midtones Exposure value.
  33117. * 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.
  33118. */
  33119. set: function (value) {
  33120. this._midtonesExposure = value;
  33121. this._dirty = true;
  33122. },
  33123. enumerable: true,
  33124. configurable: true
  33125. });
  33126. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33127. /**
  33128. * Gets the shadows Hue value.
  33129. * 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).
  33130. */
  33131. get: function () {
  33132. return this._shadowsHue;
  33133. },
  33134. /**
  33135. * Sets the shadows Hue value.
  33136. * 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).
  33137. */
  33138. set: function (value) {
  33139. this._shadowsHue = value;
  33140. this._dirty = true;
  33141. },
  33142. enumerable: true,
  33143. configurable: true
  33144. });
  33145. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33146. /**
  33147. * Gets the shadows Density value.
  33148. * 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.
  33149. * Values less than zero provide a filter of opposite hue.
  33150. */
  33151. get: function () {
  33152. return this._shadowsDensity;
  33153. },
  33154. /**
  33155. * Sets the shadows Density value.
  33156. * 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.
  33157. * Values less than zero provide a filter of opposite hue.
  33158. */
  33159. set: function (value) {
  33160. this._shadowsDensity = value;
  33161. this._dirty = true;
  33162. },
  33163. enumerable: true,
  33164. configurable: true
  33165. });
  33166. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33167. /**
  33168. * Gets the shadows Saturation value.
  33169. * 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.
  33170. */
  33171. get: function () {
  33172. return this._shadowsSaturation;
  33173. },
  33174. /**
  33175. * Sets the shadows Saturation value.
  33176. * 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.
  33177. */
  33178. set: function (value) {
  33179. this._shadowsSaturation = value;
  33180. this._dirty = true;
  33181. },
  33182. enumerable: true,
  33183. configurable: true
  33184. });
  33185. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33186. /**
  33187. * Gets the shadows Exposure value.
  33188. * 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.
  33189. */
  33190. get: function () {
  33191. return this._shadowsExposure;
  33192. },
  33193. /**
  33194. * Sets the shadows Exposure value.
  33195. * 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.
  33196. */
  33197. set: function (value) {
  33198. this._shadowsExposure = value;
  33199. this._dirty = true;
  33200. },
  33201. enumerable: true,
  33202. configurable: true
  33203. });
  33204. ColorCurves.prototype.getClassName = function () {
  33205. return "ColorCurves";
  33206. };
  33207. /**
  33208. * Binds the color curves to the shader.
  33209. * @param colorCurves The color curve to bind
  33210. * @param effect The effect to bind to
  33211. */
  33212. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33213. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33214. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33215. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33216. if (colorCurves._dirty) {
  33217. colorCurves._dirty = false;
  33218. // Fill in global info.
  33219. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33220. // Compute highlights info.
  33221. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33222. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33223. // Compute midtones info.
  33224. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33225. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33226. // Compute shadows info.
  33227. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33228. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33229. // Compute deltas (neutral is midtones).
  33230. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33231. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33232. }
  33233. if (effect) {
  33234. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33235. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33236. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33237. }
  33238. };
  33239. /**
  33240. * Prepare the list of uniforms associated with the ColorCurves effects.
  33241. * @param uniformsList The list of uniforms used in the effect
  33242. */
  33243. ColorCurves.PrepareUniforms = function (uniformsList) {
  33244. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33245. };
  33246. /**
  33247. * Returns color grading data based on a hue, density, saturation and exposure value.
  33248. * @param filterHue The hue of the color filter.
  33249. * @param filterDensity The density of the color filter.
  33250. * @param saturation The saturation.
  33251. * @param exposure The exposure.
  33252. * @param result The result data container.
  33253. */
  33254. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33255. if (hue == null) {
  33256. return;
  33257. }
  33258. hue = ColorCurves.clamp(hue, 0, 360);
  33259. density = ColorCurves.clamp(density, -100, 100);
  33260. saturation = ColorCurves.clamp(saturation, -100, 100);
  33261. exposure = ColorCurves.clamp(exposure, -100, 100);
  33262. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33263. // so that the maximum filter density is only 50% control. This provides fine control
  33264. // for small values and reasonable range.
  33265. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33266. density *= 0.5;
  33267. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33268. if (density < 0) {
  33269. density *= -1;
  33270. hue = (hue + 180) % 360;
  33271. }
  33272. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33273. result.scaleToRef(2, result);
  33274. result.a = 1 + 0.01 * saturation;
  33275. };
  33276. /**
  33277. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33278. * @param value The input slider value in range [-100,100].
  33279. * @returns Adjusted value.
  33280. */
  33281. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33282. value /= 100;
  33283. var x = Math.abs(value);
  33284. x = Math.pow(x, 2);
  33285. if (value < 0) {
  33286. x *= -1;
  33287. }
  33288. x *= 100;
  33289. return x;
  33290. };
  33291. /**
  33292. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33293. * @param hue The hue (H) input.
  33294. * @param saturation The saturation (S) input.
  33295. * @param brightness The brightness (B) input.
  33296. * @result An RGBA color represented as Vector4.
  33297. */
  33298. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33299. var h = ColorCurves.clamp(hue, 0, 360);
  33300. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33301. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33302. if (s === 0) {
  33303. result.r = v;
  33304. result.g = v;
  33305. result.b = v;
  33306. }
  33307. else {
  33308. // sector 0 to 5
  33309. h /= 60;
  33310. var i = Math.floor(h);
  33311. // fractional part of h
  33312. var f = h - i;
  33313. var p = v * (1 - s);
  33314. var q = v * (1 - s * f);
  33315. var t = v * (1 - s * (1 - f));
  33316. switch (i) {
  33317. case 0:
  33318. result.r = v;
  33319. result.g = t;
  33320. result.b = p;
  33321. break;
  33322. case 1:
  33323. result.r = q;
  33324. result.g = v;
  33325. result.b = p;
  33326. break;
  33327. case 2:
  33328. result.r = p;
  33329. result.g = v;
  33330. result.b = t;
  33331. break;
  33332. case 3:
  33333. result.r = p;
  33334. result.g = q;
  33335. result.b = v;
  33336. break;
  33337. case 4:
  33338. result.r = t;
  33339. result.g = p;
  33340. result.b = v;
  33341. break;
  33342. default:// case 5:
  33343. result.r = v;
  33344. result.g = p;
  33345. result.b = q;
  33346. break;
  33347. }
  33348. }
  33349. result.a = 1;
  33350. };
  33351. /**
  33352. * Returns a value clamped between min and max
  33353. * @param value The value to clamp
  33354. * @param min The minimum of value
  33355. * @param max The maximum of value
  33356. * @returns The clamped value.
  33357. */
  33358. ColorCurves.clamp = function (value, min, max) {
  33359. return Math.min(Math.max(value, min), max);
  33360. };
  33361. /**
  33362. * Clones the current color curve instance.
  33363. * @return The cloned curves
  33364. */
  33365. ColorCurves.prototype.clone = function () {
  33366. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33367. };
  33368. /**
  33369. * Serializes the current color curve instance to a json representation.
  33370. * @return a JSON representation
  33371. */
  33372. ColorCurves.prototype.serialize = function () {
  33373. return BABYLON.SerializationHelper.Serialize(this);
  33374. };
  33375. /**
  33376. * Parses the color curve from a json representation.
  33377. * @param source the JSON source to parse
  33378. * @return The parsed curves
  33379. */
  33380. ColorCurves.Parse = function (source) {
  33381. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33382. };
  33383. __decorate([
  33384. BABYLON.serialize()
  33385. ], ColorCurves.prototype, "_globalHue", void 0);
  33386. __decorate([
  33387. BABYLON.serialize()
  33388. ], ColorCurves.prototype, "_globalDensity", void 0);
  33389. __decorate([
  33390. BABYLON.serialize()
  33391. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33392. __decorate([
  33393. BABYLON.serialize()
  33394. ], ColorCurves.prototype, "_globalExposure", void 0);
  33395. __decorate([
  33396. BABYLON.serialize()
  33397. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33398. __decorate([
  33399. BABYLON.serialize()
  33400. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33401. __decorate([
  33402. BABYLON.serialize()
  33403. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33404. __decorate([
  33405. BABYLON.serialize()
  33406. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33407. __decorate([
  33408. BABYLON.serialize()
  33409. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33410. __decorate([
  33411. BABYLON.serialize()
  33412. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33413. __decorate([
  33414. BABYLON.serialize()
  33415. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33416. __decorate([
  33417. BABYLON.serialize()
  33418. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33419. return ColorCurves;
  33420. }());
  33421. BABYLON.ColorCurves = ColorCurves;
  33422. })(BABYLON || (BABYLON = {}));
  33423. //# sourceMappingURL=babylon.colorCurves.js.map
  33424. var BABYLON;
  33425. (function (BABYLON) {
  33426. var StandardMaterialDefines = /** @class */ (function (_super) {
  33427. __extends(StandardMaterialDefines, _super);
  33428. function StandardMaterialDefines() {
  33429. var _this = _super.call(this) || this;
  33430. _this.MAINUV1 = false;
  33431. _this.MAINUV2 = false;
  33432. _this.DIFFUSE = false;
  33433. _this.DIFFUSEDIRECTUV = 0;
  33434. _this.AMBIENT = false;
  33435. _this.AMBIENTDIRECTUV = 0;
  33436. _this.OPACITY = false;
  33437. _this.OPACITYDIRECTUV = 0;
  33438. _this.OPACITYRGB = false;
  33439. _this.REFLECTION = false;
  33440. _this.EMISSIVE = false;
  33441. _this.EMISSIVEDIRECTUV = 0;
  33442. _this.SPECULAR = false;
  33443. _this.SPECULARDIRECTUV = 0;
  33444. _this.BUMP = false;
  33445. _this.BUMPDIRECTUV = 0;
  33446. _this.PARALLAX = false;
  33447. _this.PARALLAXOCCLUSION = false;
  33448. _this.SPECULAROVERALPHA = false;
  33449. _this.CLIPPLANE = false;
  33450. _this.ALPHATEST = false;
  33451. _this.DEPTHPREPASS = false;
  33452. _this.ALPHAFROMDIFFUSE = false;
  33453. _this.POINTSIZE = false;
  33454. _this.FOG = false;
  33455. _this.SPECULARTERM = false;
  33456. _this.DIFFUSEFRESNEL = false;
  33457. _this.OPACITYFRESNEL = false;
  33458. _this.REFLECTIONFRESNEL = false;
  33459. _this.REFRACTIONFRESNEL = false;
  33460. _this.EMISSIVEFRESNEL = false;
  33461. _this.FRESNEL = false;
  33462. _this.NORMAL = false;
  33463. _this.UV1 = false;
  33464. _this.UV2 = false;
  33465. _this.VERTEXCOLOR = false;
  33466. _this.VERTEXALPHA = false;
  33467. _this.NUM_BONE_INFLUENCERS = 0;
  33468. _this.BonesPerMesh = 0;
  33469. _this.INSTANCES = false;
  33470. _this.GLOSSINESS = false;
  33471. _this.ROUGHNESS = false;
  33472. _this.EMISSIVEASILLUMINATION = false;
  33473. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33474. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33475. _this.LIGHTMAP = false;
  33476. _this.LIGHTMAPDIRECTUV = 0;
  33477. _this.USELIGHTMAPASSHADOWMAP = false;
  33478. _this.REFLECTIONMAP_3D = false;
  33479. _this.REFLECTIONMAP_SPHERICAL = false;
  33480. _this.REFLECTIONMAP_PLANAR = false;
  33481. _this.REFLECTIONMAP_CUBIC = false;
  33482. _this.REFLECTIONMAP_PROJECTION = false;
  33483. _this.REFLECTIONMAP_SKYBOX = false;
  33484. _this.REFLECTIONMAP_EXPLICIT = false;
  33485. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33486. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33487. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33488. _this.INVERTCUBICMAP = false;
  33489. _this.LOGARITHMICDEPTH = false;
  33490. _this.REFRACTION = false;
  33491. _this.REFRACTIONMAP_3D = false;
  33492. _this.REFLECTIONOVERALPHA = false;
  33493. _this.TWOSIDEDLIGHTING = false;
  33494. _this.SHADOWFLOAT = false;
  33495. _this.MORPHTARGETS = false;
  33496. _this.MORPHTARGETS_NORMAL = false;
  33497. _this.MORPHTARGETS_TANGENT = false;
  33498. _this.NUM_MORPH_INFLUENCERS = 0;
  33499. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33500. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33501. _this.IMAGEPROCESSING = false;
  33502. _this.VIGNETTE = false;
  33503. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33504. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33505. _this.TONEMAPPING = false;
  33506. _this.CONTRAST = false;
  33507. _this.COLORCURVES = false;
  33508. _this.COLORGRADING = false;
  33509. _this.COLORGRADING3D = false;
  33510. _this.SAMPLER3DGREENDEPTH = false;
  33511. _this.SAMPLER3DBGRMAP = false;
  33512. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33513. _this.EXPOSURE = false;
  33514. _this.rebuild();
  33515. return _this;
  33516. }
  33517. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33518. var modes = [
  33519. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33520. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33521. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33522. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33523. ];
  33524. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33525. var mode = modes_1[_i];
  33526. this[mode] = (mode === modeToEnable);
  33527. }
  33528. };
  33529. return StandardMaterialDefines;
  33530. }(BABYLON.MaterialDefines));
  33531. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33532. var StandardMaterial = /** @class */ (function (_super) {
  33533. __extends(StandardMaterial, _super);
  33534. function StandardMaterial(name, scene) {
  33535. var _this = _super.call(this, name, scene) || this;
  33536. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33537. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33538. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33539. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33540. _this.specularPower = 64;
  33541. _this._useAlphaFromDiffuseTexture = false;
  33542. _this._useEmissiveAsIllumination = false;
  33543. _this._linkEmissiveWithDiffuse = false;
  33544. _this._useSpecularOverAlpha = false;
  33545. _this._useReflectionOverAlpha = false;
  33546. _this._disableLighting = false;
  33547. _this._useParallax = false;
  33548. _this._useParallaxOcclusion = false;
  33549. _this.parallaxScaleBias = 0.05;
  33550. _this._roughness = 0;
  33551. _this.indexOfRefraction = 0.98;
  33552. _this.invertRefractionY = true;
  33553. _this._useLightmapAsShadowmap = false;
  33554. _this._useReflectionFresnelFromSpecular = false;
  33555. _this._useGlossinessFromSpecularMapAlpha = false;
  33556. _this._maxSimultaneousLights = 4;
  33557. /**
  33558. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33559. */
  33560. _this._invertNormalMapX = false;
  33561. /**
  33562. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33563. */
  33564. _this._invertNormalMapY = false;
  33565. /**
  33566. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33567. */
  33568. _this._twoSidedLighting = false;
  33569. _this._renderTargets = new BABYLON.SmartArray(16);
  33570. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33571. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33572. // Setup the default processing configuration to the scene.
  33573. _this._attachImageProcessingConfiguration(null);
  33574. _this.getRenderTargetTextures = function () {
  33575. _this._renderTargets.reset();
  33576. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33577. _this._renderTargets.push(_this._reflectionTexture);
  33578. }
  33579. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33580. _this._renderTargets.push(_this._refractionTexture);
  33581. }
  33582. return _this._renderTargets;
  33583. };
  33584. return _this;
  33585. }
  33586. ;
  33587. ;
  33588. ;
  33589. ;
  33590. ;
  33591. ;
  33592. ;
  33593. ;
  33594. ;
  33595. ;
  33596. ;
  33597. ;
  33598. ;
  33599. ;
  33600. ;
  33601. ;
  33602. ;
  33603. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33604. /**
  33605. * Gets the image processing configuration used either in this material.
  33606. */
  33607. get: function () {
  33608. return this._imageProcessingConfiguration;
  33609. },
  33610. /**
  33611. * Sets the Default image processing configuration used either in the this material.
  33612. *
  33613. * If sets to null, the scene one is in use.
  33614. */
  33615. set: function (value) {
  33616. this._attachImageProcessingConfiguration(value);
  33617. // Ensure the effect will be rebuilt.
  33618. this._markAllSubMeshesAsTexturesDirty();
  33619. },
  33620. enumerable: true,
  33621. configurable: true
  33622. });
  33623. /**
  33624. * Attaches a new image processing configuration to the Standard Material.
  33625. * @param configuration
  33626. */
  33627. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33628. var _this = this;
  33629. if (configuration === this._imageProcessingConfiguration) {
  33630. return;
  33631. }
  33632. // Detaches observer.
  33633. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33634. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33635. }
  33636. // Pick the scene configuration if needed.
  33637. if (!configuration) {
  33638. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33639. }
  33640. else {
  33641. this._imageProcessingConfiguration = configuration;
  33642. }
  33643. // Attaches observer.
  33644. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33645. _this._markAllSubMeshesAsImageProcessingDirty();
  33646. });
  33647. };
  33648. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33649. /**
  33650. * Gets wether the color curves effect is enabled.
  33651. */
  33652. get: function () {
  33653. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33654. },
  33655. /**
  33656. * Sets wether the color curves effect is enabled.
  33657. */
  33658. set: function (value) {
  33659. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33660. },
  33661. enumerable: true,
  33662. configurable: true
  33663. });
  33664. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33665. /**
  33666. * Gets wether the color grading effect is enabled.
  33667. */
  33668. get: function () {
  33669. return this.imageProcessingConfiguration.colorGradingEnabled;
  33670. },
  33671. /**
  33672. * Gets wether the color grading effect is enabled.
  33673. */
  33674. set: function (value) {
  33675. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33676. },
  33677. enumerable: true,
  33678. configurable: true
  33679. });
  33680. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33681. /**
  33682. * Gets wether tonemapping is enabled or not.
  33683. */
  33684. get: function () {
  33685. return this._imageProcessingConfiguration.toneMappingEnabled;
  33686. },
  33687. /**
  33688. * Sets wether tonemapping is enabled or not
  33689. */
  33690. set: function (value) {
  33691. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33692. },
  33693. enumerable: true,
  33694. configurable: true
  33695. });
  33696. ;
  33697. ;
  33698. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33699. /**
  33700. * The camera exposure used on this material.
  33701. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33702. * This corresponds to a photographic exposure.
  33703. */
  33704. get: function () {
  33705. return this._imageProcessingConfiguration.exposure;
  33706. },
  33707. /**
  33708. * The camera exposure used on this material.
  33709. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33710. * This corresponds to a photographic exposure.
  33711. */
  33712. set: function (value) {
  33713. this._imageProcessingConfiguration.exposure = value;
  33714. },
  33715. enumerable: true,
  33716. configurable: true
  33717. });
  33718. ;
  33719. ;
  33720. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33721. /**
  33722. * Gets The camera contrast used on this material.
  33723. */
  33724. get: function () {
  33725. return this._imageProcessingConfiguration.contrast;
  33726. },
  33727. /**
  33728. * Sets The camera contrast used on this material.
  33729. */
  33730. set: function (value) {
  33731. this._imageProcessingConfiguration.contrast = value;
  33732. },
  33733. enumerable: true,
  33734. configurable: true
  33735. });
  33736. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33737. /**
  33738. * Gets the Color Grading 2D Lookup Texture.
  33739. */
  33740. get: function () {
  33741. return this._imageProcessingConfiguration.colorGradingTexture;
  33742. },
  33743. /**
  33744. * Sets the Color Grading 2D Lookup Texture.
  33745. */
  33746. set: function (value) {
  33747. this._imageProcessingConfiguration.colorGradingTexture = value;
  33748. },
  33749. enumerable: true,
  33750. configurable: true
  33751. });
  33752. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33753. /**
  33754. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33755. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33756. * 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;
  33757. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33758. */
  33759. get: function () {
  33760. return this._imageProcessingConfiguration.colorCurves;
  33761. },
  33762. /**
  33763. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33764. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33765. * 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;
  33766. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33767. */
  33768. set: function (value) {
  33769. this._imageProcessingConfiguration.colorCurves = value;
  33770. },
  33771. enumerable: true,
  33772. configurable: true
  33773. });
  33774. StandardMaterial.prototype.getClassName = function () {
  33775. return "StandardMaterial";
  33776. };
  33777. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33778. get: function () {
  33779. return this._useLogarithmicDepth;
  33780. },
  33781. set: function (value) {
  33782. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33783. this._markAllSubMeshesAsMiscDirty();
  33784. },
  33785. enumerable: true,
  33786. configurable: true
  33787. });
  33788. StandardMaterial.prototype.needAlphaBlending = function () {
  33789. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33790. };
  33791. StandardMaterial.prototype.needAlphaTesting = function () {
  33792. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33793. };
  33794. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33795. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33796. };
  33797. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33798. return this._diffuseTexture;
  33799. };
  33800. /**
  33801. * Child classes can use it to update shaders
  33802. */
  33803. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33804. if (useInstances === void 0) { useInstances = false; }
  33805. if (subMesh.effect && this.isFrozen) {
  33806. if (this._wasPreviouslyReady && subMesh.effect) {
  33807. return true;
  33808. }
  33809. }
  33810. if (!subMesh._materialDefines) {
  33811. subMesh._materialDefines = new StandardMaterialDefines();
  33812. }
  33813. var scene = this.getScene();
  33814. var defines = subMesh._materialDefines;
  33815. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33816. if (defines._renderId === scene.getRenderId()) {
  33817. return true;
  33818. }
  33819. }
  33820. var engine = scene.getEngine();
  33821. // Lights
  33822. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33823. // Textures
  33824. if (defines._areTexturesDirty) {
  33825. defines._needUVs = false;
  33826. defines.MAINUV1 = false;
  33827. defines.MAINUV2 = false;
  33828. if (scene.texturesEnabled) {
  33829. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33830. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33831. return false;
  33832. }
  33833. else {
  33834. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33835. }
  33836. }
  33837. else {
  33838. defines.DIFFUSE = false;
  33839. }
  33840. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33841. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33842. return false;
  33843. }
  33844. else {
  33845. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33846. }
  33847. }
  33848. else {
  33849. defines.AMBIENT = false;
  33850. }
  33851. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33852. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33853. return false;
  33854. }
  33855. else {
  33856. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33857. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33858. }
  33859. }
  33860. else {
  33861. defines.OPACITY = false;
  33862. }
  33863. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33864. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33865. return false;
  33866. }
  33867. else {
  33868. defines._needNormals = true;
  33869. defines.REFLECTION = true;
  33870. defines.ROUGHNESS = (this._roughness > 0);
  33871. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33872. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33873. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33874. switch (this._reflectionTexture.coordinatesMode) {
  33875. case BABYLON.Texture.CUBIC_MODE:
  33876. case BABYLON.Texture.INVCUBIC_MODE:
  33877. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33878. break;
  33879. case BABYLON.Texture.EXPLICIT_MODE:
  33880. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33881. break;
  33882. case BABYLON.Texture.PLANAR_MODE:
  33883. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33884. break;
  33885. case BABYLON.Texture.PROJECTION_MODE:
  33886. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33887. break;
  33888. case BABYLON.Texture.SKYBOX_MODE:
  33889. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33890. break;
  33891. case BABYLON.Texture.SPHERICAL_MODE:
  33892. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33893. break;
  33894. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33895. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33896. break;
  33897. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33898. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33899. break;
  33900. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33901. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33902. break;
  33903. }
  33904. }
  33905. }
  33906. else {
  33907. defines.REFLECTION = false;
  33908. }
  33909. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33910. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33911. return false;
  33912. }
  33913. else {
  33914. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33915. }
  33916. }
  33917. else {
  33918. defines.EMISSIVE = false;
  33919. }
  33920. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33921. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33922. return false;
  33923. }
  33924. else {
  33925. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33926. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33927. }
  33928. }
  33929. else {
  33930. defines.LIGHTMAP = false;
  33931. }
  33932. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33933. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33934. return false;
  33935. }
  33936. else {
  33937. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33938. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33939. }
  33940. }
  33941. else {
  33942. defines.SPECULAR = false;
  33943. }
  33944. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33945. // Bump texure can not be not blocking.
  33946. if (!this._bumpTexture.isReady()) {
  33947. return false;
  33948. }
  33949. else {
  33950. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33951. defines.PARALLAX = this._useParallax;
  33952. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33953. }
  33954. }
  33955. else {
  33956. defines.BUMP = false;
  33957. }
  33958. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33959. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33960. return false;
  33961. }
  33962. else {
  33963. defines._needUVs = true;
  33964. defines.REFRACTION = true;
  33965. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33966. }
  33967. }
  33968. else {
  33969. defines.REFRACTION = false;
  33970. }
  33971. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33972. }
  33973. else {
  33974. defines.DIFFUSE = false;
  33975. defines.AMBIENT = false;
  33976. defines.OPACITY = false;
  33977. defines.REFLECTION = false;
  33978. defines.EMISSIVE = false;
  33979. defines.LIGHTMAP = false;
  33980. defines.BUMP = false;
  33981. defines.REFRACTION = false;
  33982. }
  33983. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33984. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33985. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33986. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33987. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33988. }
  33989. if (defines._areImageProcessingDirty) {
  33990. if (!this._imageProcessingConfiguration.isReady()) {
  33991. return false;
  33992. }
  33993. this._imageProcessingConfiguration.prepareDefines(defines);
  33994. }
  33995. if (defines._areFresnelDirty) {
  33996. if (StandardMaterial.FresnelEnabled) {
  33997. // Fresnel
  33998. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33999. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  34000. this._reflectionFresnelParameters) {
  34001. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34002. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34003. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34004. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34005. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34006. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34007. defines._needNormals = true;
  34008. defines.FRESNEL = true;
  34009. }
  34010. }
  34011. else {
  34012. defines.FRESNEL = false;
  34013. }
  34014. }
  34015. // Misc.
  34016. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34017. // Attribs
  34018. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34019. // Values that need to be evaluated on every frame
  34020. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34021. // Get correct effect
  34022. if (defines.isDirty) {
  34023. defines.markAsProcessed();
  34024. scene.resetCachedMaterial();
  34025. // Fallbacks
  34026. var fallbacks = new BABYLON.EffectFallbacks();
  34027. if (defines.REFLECTION) {
  34028. fallbacks.addFallback(0, "REFLECTION");
  34029. }
  34030. if (defines.SPECULAR) {
  34031. fallbacks.addFallback(0, "SPECULAR");
  34032. }
  34033. if (defines.BUMP) {
  34034. fallbacks.addFallback(0, "BUMP");
  34035. }
  34036. if (defines.PARALLAX) {
  34037. fallbacks.addFallback(1, "PARALLAX");
  34038. }
  34039. if (defines.PARALLAXOCCLUSION) {
  34040. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34041. }
  34042. if (defines.SPECULAROVERALPHA) {
  34043. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34044. }
  34045. if (defines.FOG) {
  34046. fallbacks.addFallback(1, "FOG");
  34047. }
  34048. if (defines.POINTSIZE) {
  34049. fallbacks.addFallback(0, "POINTSIZE");
  34050. }
  34051. if (defines.LOGARITHMICDEPTH) {
  34052. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34053. }
  34054. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34055. if (defines.SPECULARTERM) {
  34056. fallbacks.addFallback(0, "SPECULARTERM");
  34057. }
  34058. if (defines.DIFFUSEFRESNEL) {
  34059. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34060. }
  34061. if (defines.OPACITYFRESNEL) {
  34062. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34063. }
  34064. if (defines.REFLECTIONFRESNEL) {
  34065. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34066. }
  34067. if (defines.EMISSIVEFRESNEL) {
  34068. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34069. }
  34070. if (defines.FRESNEL) {
  34071. fallbacks.addFallback(4, "FRESNEL");
  34072. }
  34073. //Attributes
  34074. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34075. if (defines.NORMAL) {
  34076. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34077. }
  34078. if (defines.UV1) {
  34079. attribs.push(BABYLON.VertexBuffer.UVKind);
  34080. }
  34081. if (defines.UV2) {
  34082. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34083. }
  34084. if (defines.VERTEXCOLOR) {
  34085. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34086. }
  34087. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34088. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34089. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34090. var shaderName = "default";
  34091. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34092. "vFogInfos", "vFogColor", "pointSize",
  34093. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34094. "mBones",
  34095. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34096. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  34097. "logarithmicDepthConstant", "vTangentSpaceParams"
  34098. ];
  34099. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34100. var uniformBuffers = ["Material", "Scene"];
  34101. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34102. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34103. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34104. uniformsNames: uniforms,
  34105. uniformBuffersNames: uniformBuffers,
  34106. samplers: samplers,
  34107. defines: defines,
  34108. maxSimultaneousLights: this._maxSimultaneousLights
  34109. });
  34110. if (this.customShaderNameResolve) {
  34111. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  34112. }
  34113. var join = defines.toString();
  34114. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  34115. attributes: attribs,
  34116. uniformsNames: uniforms,
  34117. uniformBuffersNames: uniformBuffers,
  34118. samplers: samplers,
  34119. defines: join,
  34120. fallbacks: fallbacks,
  34121. onCompiled: this.onCompiled,
  34122. onError: this.onError,
  34123. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34124. }, engine), defines);
  34125. this.buildUniformLayout();
  34126. }
  34127. if (!subMesh.effect || !subMesh.effect.isReady()) {
  34128. return false;
  34129. }
  34130. defines._renderId = scene.getRenderId();
  34131. this._wasPreviouslyReady = true;
  34132. return true;
  34133. };
  34134. StandardMaterial.prototype.buildUniformLayout = function () {
  34135. // Order is important !
  34136. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  34137. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  34138. this._uniformBuffer.addUniform("opacityParts", 4);
  34139. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  34140. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34141. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34142. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34143. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34144. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34145. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34146. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34147. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34148. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34149. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34150. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34151. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34152. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34153. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34154. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34155. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34156. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34157. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34158. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34159. this._uniformBuffer.addUniform("specularMatrix", 16);
  34160. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34161. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34162. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34163. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34164. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34165. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34166. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34167. this._uniformBuffer.addUniform("pointSize", 1);
  34168. this._uniformBuffer.create();
  34169. };
  34170. StandardMaterial.prototype.unbind = function () {
  34171. if (this._activeEffect) {
  34172. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34173. this._activeEffect.setTexture("reflection2DSampler", null);
  34174. }
  34175. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34176. this._activeEffect.setTexture("refraction2DSampler", null);
  34177. }
  34178. }
  34179. _super.prototype.unbind.call(this);
  34180. };
  34181. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34182. var scene = this.getScene();
  34183. var defines = subMesh._materialDefines;
  34184. if (!defines) {
  34185. return;
  34186. }
  34187. var effect = subMesh.effect;
  34188. if (!effect) {
  34189. return;
  34190. }
  34191. this._activeEffect = effect;
  34192. // Matrices
  34193. this.bindOnlyWorldMatrix(world);
  34194. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34195. // Bones
  34196. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34197. if (mustRebind) {
  34198. this._uniformBuffer.bindToEffect(effect, "Material");
  34199. this.bindViewProjection(effect);
  34200. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34201. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34202. // Fresnel
  34203. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34204. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34205. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34206. }
  34207. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34208. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34209. }
  34210. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34211. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34212. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34213. }
  34214. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34215. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34216. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34217. }
  34218. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34219. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34220. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34221. }
  34222. }
  34223. // Textures
  34224. if (scene.texturesEnabled) {
  34225. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34226. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34227. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34228. }
  34229. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34230. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34231. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34232. }
  34233. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34234. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34235. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34236. }
  34237. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34238. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34239. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34240. }
  34241. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34242. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34243. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34244. }
  34245. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34246. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34247. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34248. }
  34249. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34250. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34251. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34252. }
  34253. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34254. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34255. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34256. if (scene._mirroredCameraPosition) {
  34257. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34258. }
  34259. else {
  34260. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34261. }
  34262. }
  34263. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34264. var depth = 1.0;
  34265. if (!this._refractionTexture.isCube) {
  34266. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34267. if (this._refractionTexture.depth) {
  34268. depth = this._refractionTexture.depth;
  34269. }
  34270. }
  34271. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34272. }
  34273. }
  34274. // Point size
  34275. if (this.pointsCloud) {
  34276. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34277. }
  34278. if (defines.SPECULARTERM) {
  34279. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34280. }
  34281. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34282. // Diffuse
  34283. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34284. }
  34285. // Textures
  34286. if (scene.texturesEnabled) {
  34287. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34288. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34289. }
  34290. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34291. effect.setTexture("ambientSampler", this._ambientTexture);
  34292. }
  34293. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34294. effect.setTexture("opacitySampler", this._opacityTexture);
  34295. }
  34296. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34297. if (this._reflectionTexture.isCube) {
  34298. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34299. }
  34300. else {
  34301. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34302. }
  34303. }
  34304. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34305. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34306. }
  34307. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34308. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34309. }
  34310. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34311. effect.setTexture("specularSampler", this._specularTexture);
  34312. }
  34313. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34314. effect.setTexture("bumpSampler", this._bumpTexture);
  34315. }
  34316. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34317. var depth = 1.0;
  34318. if (this._refractionTexture.isCube) {
  34319. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34320. }
  34321. else {
  34322. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34323. }
  34324. }
  34325. }
  34326. // Clip plane
  34327. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34328. // Colors
  34329. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34330. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34331. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34332. }
  34333. if (mustRebind || !this.isFrozen) {
  34334. // Lights
  34335. if (scene.lightsEnabled && !this._disableLighting) {
  34336. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34337. }
  34338. // View
  34339. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34340. this.bindView(effect);
  34341. }
  34342. // Fog
  34343. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34344. // Morph targets
  34345. if (defines.NUM_MORPH_INFLUENCERS) {
  34346. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34347. }
  34348. // Log. depth
  34349. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34350. // image processing
  34351. this._imageProcessingConfiguration.bind(this._activeEffect);
  34352. }
  34353. this._uniformBuffer.update();
  34354. this._afterBind(mesh, this._activeEffect);
  34355. };
  34356. StandardMaterial.prototype.getAnimatables = function () {
  34357. var results = [];
  34358. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34359. results.push(this._diffuseTexture);
  34360. }
  34361. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34362. results.push(this._ambientTexture);
  34363. }
  34364. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34365. results.push(this._opacityTexture);
  34366. }
  34367. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34368. results.push(this._reflectionTexture);
  34369. }
  34370. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34371. results.push(this._emissiveTexture);
  34372. }
  34373. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34374. results.push(this._specularTexture);
  34375. }
  34376. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34377. results.push(this._bumpTexture);
  34378. }
  34379. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34380. results.push(this._lightmapTexture);
  34381. }
  34382. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34383. results.push(this._refractionTexture);
  34384. }
  34385. return results;
  34386. };
  34387. StandardMaterial.prototype.getActiveTextures = function () {
  34388. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34389. if (this._diffuseTexture) {
  34390. activeTextures.push(this._diffuseTexture);
  34391. }
  34392. if (this._ambientTexture) {
  34393. activeTextures.push(this._ambientTexture);
  34394. }
  34395. if (this._opacityTexture) {
  34396. activeTextures.push(this._opacityTexture);
  34397. }
  34398. if (this._reflectionTexture) {
  34399. activeTextures.push(this._reflectionTexture);
  34400. }
  34401. if (this._emissiveTexture) {
  34402. activeTextures.push(this._emissiveTexture);
  34403. }
  34404. if (this._specularTexture) {
  34405. activeTextures.push(this._specularTexture);
  34406. }
  34407. if (this._bumpTexture) {
  34408. activeTextures.push(this._bumpTexture);
  34409. }
  34410. if (this._lightmapTexture) {
  34411. activeTextures.push(this._lightmapTexture);
  34412. }
  34413. if (this._refractionTexture) {
  34414. activeTextures.push(this._refractionTexture);
  34415. }
  34416. return activeTextures;
  34417. };
  34418. StandardMaterial.prototype.hasTexture = function (texture) {
  34419. if (_super.prototype.hasTexture.call(this, texture)) {
  34420. return true;
  34421. }
  34422. if (this._diffuseTexture === texture) {
  34423. return true;
  34424. }
  34425. if (this._ambientTexture === texture) {
  34426. return true;
  34427. }
  34428. if (this._opacityTexture === texture) {
  34429. return true;
  34430. }
  34431. if (this._reflectionTexture === texture) {
  34432. return true;
  34433. }
  34434. if (this._emissiveTexture === texture) {
  34435. return true;
  34436. }
  34437. if (this._specularTexture === texture) {
  34438. return true;
  34439. }
  34440. if (this._bumpTexture === texture) {
  34441. return true;
  34442. }
  34443. if (this._lightmapTexture === texture) {
  34444. return true;
  34445. }
  34446. if (this._refractionTexture === texture) {
  34447. return true;
  34448. }
  34449. return false;
  34450. };
  34451. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34452. if (forceDisposeTextures) {
  34453. if (this._diffuseTexture) {
  34454. this._diffuseTexture.dispose();
  34455. }
  34456. if (this._ambientTexture) {
  34457. this._ambientTexture.dispose();
  34458. }
  34459. if (this._opacityTexture) {
  34460. this._opacityTexture.dispose();
  34461. }
  34462. if (this._reflectionTexture) {
  34463. this._reflectionTexture.dispose();
  34464. }
  34465. if (this._emissiveTexture) {
  34466. this._emissiveTexture.dispose();
  34467. }
  34468. if (this._specularTexture) {
  34469. this._specularTexture.dispose();
  34470. }
  34471. if (this._bumpTexture) {
  34472. this._bumpTexture.dispose();
  34473. }
  34474. if (this._lightmapTexture) {
  34475. this._lightmapTexture.dispose();
  34476. }
  34477. if (this._refractionTexture) {
  34478. this._refractionTexture.dispose();
  34479. }
  34480. }
  34481. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34482. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34483. }
  34484. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34485. };
  34486. StandardMaterial.prototype.clone = function (name) {
  34487. var _this = this;
  34488. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34489. result.name = name;
  34490. result.id = name;
  34491. return result;
  34492. };
  34493. StandardMaterial.prototype.serialize = function () {
  34494. return BABYLON.SerializationHelper.Serialize(this);
  34495. };
  34496. // Statics
  34497. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34498. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34499. };
  34500. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34501. get: function () {
  34502. return StandardMaterial._DiffuseTextureEnabled;
  34503. },
  34504. set: function (value) {
  34505. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34506. return;
  34507. }
  34508. StandardMaterial._DiffuseTextureEnabled = value;
  34509. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34510. },
  34511. enumerable: true,
  34512. configurable: true
  34513. });
  34514. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34515. get: function () {
  34516. return StandardMaterial._AmbientTextureEnabled;
  34517. },
  34518. set: function (value) {
  34519. if (StandardMaterial._AmbientTextureEnabled === value) {
  34520. return;
  34521. }
  34522. StandardMaterial._AmbientTextureEnabled = value;
  34523. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34524. },
  34525. enumerable: true,
  34526. configurable: true
  34527. });
  34528. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34529. get: function () {
  34530. return StandardMaterial._OpacityTextureEnabled;
  34531. },
  34532. set: function (value) {
  34533. if (StandardMaterial._OpacityTextureEnabled === value) {
  34534. return;
  34535. }
  34536. StandardMaterial._OpacityTextureEnabled = value;
  34537. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34538. },
  34539. enumerable: true,
  34540. configurable: true
  34541. });
  34542. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34543. get: function () {
  34544. return StandardMaterial._ReflectionTextureEnabled;
  34545. },
  34546. set: function (value) {
  34547. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34548. return;
  34549. }
  34550. StandardMaterial._ReflectionTextureEnabled = value;
  34551. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34552. },
  34553. enumerable: true,
  34554. configurable: true
  34555. });
  34556. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34557. get: function () {
  34558. return StandardMaterial._EmissiveTextureEnabled;
  34559. },
  34560. set: function (value) {
  34561. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34562. return;
  34563. }
  34564. StandardMaterial._EmissiveTextureEnabled = value;
  34565. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34566. },
  34567. enumerable: true,
  34568. configurable: true
  34569. });
  34570. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34571. get: function () {
  34572. return StandardMaterial._SpecularTextureEnabled;
  34573. },
  34574. set: function (value) {
  34575. if (StandardMaterial._SpecularTextureEnabled === value) {
  34576. return;
  34577. }
  34578. StandardMaterial._SpecularTextureEnabled = value;
  34579. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34580. },
  34581. enumerable: true,
  34582. configurable: true
  34583. });
  34584. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34585. get: function () {
  34586. return StandardMaterial._BumpTextureEnabled;
  34587. },
  34588. set: function (value) {
  34589. if (StandardMaterial._BumpTextureEnabled === value) {
  34590. return;
  34591. }
  34592. StandardMaterial._BumpTextureEnabled = value;
  34593. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34594. },
  34595. enumerable: true,
  34596. configurable: true
  34597. });
  34598. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34599. get: function () {
  34600. return StandardMaterial._LightmapTextureEnabled;
  34601. },
  34602. set: function (value) {
  34603. if (StandardMaterial._LightmapTextureEnabled === value) {
  34604. return;
  34605. }
  34606. StandardMaterial._LightmapTextureEnabled = value;
  34607. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34608. },
  34609. enumerable: true,
  34610. configurable: true
  34611. });
  34612. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34613. get: function () {
  34614. return StandardMaterial._RefractionTextureEnabled;
  34615. },
  34616. set: function (value) {
  34617. if (StandardMaterial._RefractionTextureEnabled === value) {
  34618. return;
  34619. }
  34620. StandardMaterial._RefractionTextureEnabled = value;
  34621. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34622. },
  34623. enumerable: true,
  34624. configurable: true
  34625. });
  34626. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34627. get: function () {
  34628. return StandardMaterial._ColorGradingTextureEnabled;
  34629. },
  34630. set: function (value) {
  34631. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34632. return;
  34633. }
  34634. StandardMaterial._ColorGradingTextureEnabled = value;
  34635. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34636. },
  34637. enumerable: true,
  34638. configurable: true
  34639. });
  34640. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34641. get: function () {
  34642. return StandardMaterial._FresnelEnabled;
  34643. },
  34644. set: function (value) {
  34645. if (StandardMaterial._FresnelEnabled === value) {
  34646. return;
  34647. }
  34648. StandardMaterial._FresnelEnabled = value;
  34649. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34650. },
  34651. enumerable: true,
  34652. configurable: true
  34653. });
  34654. // Flags used to enable or disable a type of texture for all Standard Materials
  34655. StandardMaterial._DiffuseTextureEnabled = true;
  34656. StandardMaterial._AmbientTextureEnabled = true;
  34657. StandardMaterial._OpacityTextureEnabled = true;
  34658. StandardMaterial._ReflectionTextureEnabled = true;
  34659. StandardMaterial._EmissiveTextureEnabled = true;
  34660. StandardMaterial._SpecularTextureEnabled = true;
  34661. StandardMaterial._BumpTextureEnabled = true;
  34662. StandardMaterial._LightmapTextureEnabled = true;
  34663. StandardMaterial._RefractionTextureEnabled = true;
  34664. StandardMaterial._ColorGradingTextureEnabled = true;
  34665. StandardMaterial._FresnelEnabled = true;
  34666. __decorate([
  34667. BABYLON.serializeAsTexture("diffuseTexture")
  34668. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34669. __decorate([
  34670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34671. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34672. __decorate([
  34673. BABYLON.serializeAsTexture("ambientTexture")
  34674. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34675. __decorate([
  34676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34677. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34678. __decorate([
  34679. BABYLON.serializeAsTexture("opacityTexture")
  34680. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34681. __decorate([
  34682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34683. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34684. __decorate([
  34685. BABYLON.serializeAsTexture("reflectionTexture")
  34686. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34687. __decorate([
  34688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34689. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34690. __decorate([
  34691. BABYLON.serializeAsTexture("emissiveTexture")
  34692. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34693. __decorate([
  34694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34695. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34696. __decorate([
  34697. BABYLON.serializeAsTexture("specularTexture")
  34698. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34699. __decorate([
  34700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34701. ], StandardMaterial.prototype, "specularTexture", void 0);
  34702. __decorate([
  34703. BABYLON.serializeAsTexture("bumpTexture")
  34704. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34705. __decorate([
  34706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34707. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34708. __decorate([
  34709. BABYLON.serializeAsTexture("lightmapTexture")
  34710. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34711. __decorate([
  34712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34713. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34714. __decorate([
  34715. BABYLON.serializeAsTexture("refractionTexture")
  34716. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34717. __decorate([
  34718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34719. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34720. __decorate([
  34721. BABYLON.serializeAsColor3("ambient")
  34722. ], StandardMaterial.prototype, "ambientColor", void 0);
  34723. __decorate([
  34724. BABYLON.serializeAsColor3("diffuse")
  34725. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34726. __decorate([
  34727. BABYLON.serializeAsColor3("specular")
  34728. ], StandardMaterial.prototype, "specularColor", void 0);
  34729. __decorate([
  34730. BABYLON.serializeAsColor3("emissive")
  34731. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34732. __decorate([
  34733. BABYLON.serialize()
  34734. ], StandardMaterial.prototype, "specularPower", void 0);
  34735. __decorate([
  34736. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34737. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34738. __decorate([
  34739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34740. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34741. __decorate([
  34742. BABYLON.serialize("useEmissiveAsIllumination")
  34743. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34744. __decorate([
  34745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34746. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34747. __decorate([
  34748. BABYLON.serialize("linkEmissiveWithDiffuse")
  34749. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34750. __decorate([
  34751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34752. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34753. __decorate([
  34754. BABYLON.serialize("useSpecularOverAlpha")
  34755. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34756. __decorate([
  34757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34758. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34759. __decorate([
  34760. BABYLON.serialize("useReflectionOverAlpha")
  34761. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34762. __decorate([
  34763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34764. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34765. __decorate([
  34766. BABYLON.serialize("disableLighting")
  34767. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34768. __decorate([
  34769. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34770. ], StandardMaterial.prototype, "disableLighting", void 0);
  34771. __decorate([
  34772. BABYLON.serialize("useParallax")
  34773. ], StandardMaterial.prototype, "_useParallax", void 0);
  34774. __decorate([
  34775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34776. ], StandardMaterial.prototype, "useParallax", void 0);
  34777. __decorate([
  34778. BABYLON.serialize("useParallaxOcclusion")
  34779. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34780. __decorate([
  34781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34782. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34783. __decorate([
  34784. BABYLON.serialize()
  34785. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34786. __decorate([
  34787. BABYLON.serialize("roughness")
  34788. ], StandardMaterial.prototype, "_roughness", void 0);
  34789. __decorate([
  34790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34791. ], StandardMaterial.prototype, "roughness", void 0);
  34792. __decorate([
  34793. BABYLON.serialize()
  34794. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34795. __decorate([
  34796. BABYLON.serialize()
  34797. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34798. __decorate([
  34799. BABYLON.serialize("useLightmapAsShadowmap")
  34800. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34801. __decorate([
  34802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34803. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34804. __decorate([
  34805. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34806. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34807. __decorate([
  34808. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34809. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34810. __decorate([
  34811. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34812. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34813. __decorate([
  34814. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34815. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34816. __decorate([
  34817. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34818. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34819. __decorate([
  34820. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34821. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34822. __decorate([
  34823. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34824. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34825. __decorate([
  34826. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34827. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34828. __decorate([
  34829. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34830. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34831. __decorate([
  34832. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34833. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34834. __decorate([
  34835. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34836. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34837. __decorate([
  34838. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34839. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34840. __decorate([
  34841. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34842. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34843. __decorate([
  34844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34845. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34846. __decorate([
  34847. BABYLON.serialize("maxSimultaneousLights")
  34848. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34849. __decorate([
  34850. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34851. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34852. __decorate([
  34853. BABYLON.serialize("invertNormalMapX")
  34854. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34855. __decorate([
  34856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34857. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34858. __decorate([
  34859. BABYLON.serialize("invertNormalMapY")
  34860. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34861. __decorate([
  34862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34863. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34864. __decorate([
  34865. BABYLON.serialize("twoSidedLighting")
  34866. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34867. __decorate([
  34868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34869. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34870. __decorate([
  34871. BABYLON.serialize()
  34872. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34873. return StandardMaterial;
  34874. }(BABYLON.PushMaterial));
  34875. BABYLON.StandardMaterial = StandardMaterial;
  34876. })(BABYLON || (BABYLON = {}));
  34877. //# sourceMappingURL=babylon.standardMaterial.js.map
  34878. var BABYLON;
  34879. (function (BABYLON) {
  34880. var PBRMaterialDefines = /** @class */ (function (_super) {
  34881. __extends(PBRMaterialDefines, _super);
  34882. function PBRMaterialDefines() {
  34883. var _this = _super.call(this) || this;
  34884. _this.PBR = true;
  34885. _this.MAINUV1 = false;
  34886. _this.MAINUV2 = false;
  34887. _this.UV1 = false;
  34888. _this.UV2 = false;
  34889. _this.ALBEDO = false;
  34890. _this.ALBEDODIRECTUV = 0;
  34891. _this.VERTEXCOLOR = false;
  34892. _this.AMBIENT = false;
  34893. _this.AMBIENTDIRECTUV = 0;
  34894. _this.AMBIENTINGRAYSCALE = false;
  34895. _this.OPACITY = false;
  34896. _this.VERTEXALPHA = false;
  34897. _this.OPACITYDIRECTUV = 0;
  34898. _this.OPACITYRGB = false;
  34899. _this.ALPHATEST = false;
  34900. _this.DEPTHPREPASS = false;
  34901. _this.ALPHABLEND = false;
  34902. _this.ALPHAFROMALBEDO = false;
  34903. _this.ALPHATESTVALUE = 0.5;
  34904. _this.SPECULAROVERALPHA = false;
  34905. _this.RADIANCEOVERALPHA = false;
  34906. _this.ALPHAFRESNEL = false;
  34907. _this.PREMULTIPLYALPHA = false;
  34908. _this.EMISSIVE = false;
  34909. _this.EMISSIVEDIRECTUV = 0;
  34910. _this.REFLECTIVITY = false;
  34911. _this.REFLECTIVITYDIRECTUV = 0;
  34912. _this.SPECULARTERM = false;
  34913. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34914. _this.MICROSURFACEAUTOMATIC = false;
  34915. _this.LODBASEDMICROSFURACE = false;
  34916. _this.MICROSURFACEMAP = false;
  34917. _this.MICROSURFACEMAPDIRECTUV = 0;
  34918. _this.METALLICWORKFLOW = false;
  34919. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34920. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34921. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34922. _this.AOSTOREINMETALMAPRED = false;
  34923. _this.ENVIRONMENTBRDF = false;
  34924. _this.NORMAL = false;
  34925. _this.TANGENT = false;
  34926. _this.BUMP = false;
  34927. _this.BUMPDIRECTUV = 0;
  34928. _this.PARALLAX = false;
  34929. _this.PARALLAXOCCLUSION = false;
  34930. _this.NORMALXYSCALE = true;
  34931. _this.LIGHTMAP = false;
  34932. _this.LIGHTMAPDIRECTUV = 0;
  34933. _this.USELIGHTMAPASSHADOWMAP = false;
  34934. _this.REFLECTION = false;
  34935. _this.REFLECTIONMAP_3D = false;
  34936. _this.REFLECTIONMAP_SPHERICAL = false;
  34937. _this.REFLECTIONMAP_PLANAR = false;
  34938. _this.REFLECTIONMAP_CUBIC = false;
  34939. _this.REFLECTIONMAP_PROJECTION = false;
  34940. _this.REFLECTIONMAP_SKYBOX = false;
  34941. _this.REFLECTIONMAP_EXPLICIT = false;
  34942. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34943. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34944. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34945. _this.INVERTCUBICMAP = false;
  34946. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34947. _this.USESPHERICALINVERTEX = false;
  34948. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34949. _this.LODINREFLECTIONALPHA = false;
  34950. _this.GAMMAREFLECTION = false;
  34951. _this.REFRACTION = false;
  34952. _this.REFRACTIONMAP_3D = false;
  34953. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34954. _this.LODINREFRACTIONALPHA = false;
  34955. _this.GAMMAREFRACTION = false;
  34956. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34957. _this.INSTANCES = false;
  34958. _this.NUM_BONE_INFLUENCERS = 0;
  34959. _this.BonesPerMesh = 0;
  34960. _this.NONUNIFORMSCALING = false;
  34961. _this.MORPHTARGETS = false;
  34962. _this.MORPHTARGETS_NORMAL = false;
  34963. _this.MORPHTARGETS_TANGENT = false;
  34964. _this.NUM_MORPH_INFLUENCERS = 0;
  34965. _this.IMAGEPROCESSING = false;
  34966. _this.VIGNETTE = false;
  34967. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34968. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34969. _this.TONEMAPPING = false;
  34970. _this.CONTRAST = false;
  34971. _this.COLORCURVES = false;
  34972. _this.COLORGRADING = false;
  34973. _this.COLORGRADING3D = false;
  34974. _this.SAMPLER3DGREENDEPTH = false;
  34975. _this.SAMPLER3DBGRMAP = false;
  34976. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34977. _this.EXPOSURE = false;
  34978. _this.USEPHYSICALLIGHTFALLOFF = false;
  34979. _this.TWOSIDEDLIGHTING = false;
  34980. _this.SHADOWFLOAT = false;
  34981. _this.CLIPPLANE = false;
  34982. _this.POINTSIZE = false;
  34983. _this.FOG = false;
  34984. _this.LOGARITHMICDEPTH = false;
  34985. _this.FORCENORMALFORWARD = false;
  34986. _this.rebuild();
  34987. return _this;
  34988. }
  34989. PBRMaterialDefines.prototype.reset = function () {
  34990. _super.prototype.reset.call(this);
  34991. this.ALPHATESTVALUE = 0.5;
  34992. this.PBR = true;
  34993. };
  34994. return PBRMaterialDefines;
  34995. }(BABYLON.MaterialDefines));
  34996. /**
  34997. * The Physically based material base class of BJS.
  34998. *
  34999. * This offers the main features of a standard PBR material.
  35000. * For more information, please refer to the documentation :
  35001. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35002. */
  35003. var PBRBaseMaterial = /** @class */ (function (_super) {
  35004. __extends(PBRBaseMaterial, _super);
  35005. /**
  35006. * Instantiates a new PBRMaterial instance.
  35007. *
  35008. * @param name The material name
  35009. * @param scene The scene the material will be use in.
  35010. */
  35011. function PBRBaseMaterial(name, scene) {
  35012. var _this = _super.call(this, name, scene) || this;
  35013. /**
  35014. * Intensity of the direct lights e.g. the four lights available in your scene.
  35015. * This impacts both the direct diffuse and specular highlights.
  35016. */
  35017. _this._directIntensity = 1.0;
  35018. /**
  35019. * Intensity of the emissive part of the material.
  35020. * This helps controlling the emissive effect without modifying the emissive color.
  35021. */
  35022. _this._emissiveIntensity = 1.0;
  35023. /**
  35024. * Intensity of the environment e.g. how much the environment will light the object
  35025. * either through harmonics for rough material or through the refelction for shiny ones.
  35026. */
  35027. _this._environmentIntensity = 1.0;
  35028. /**
  35029. * This is a special control allowing the reduction of the specular highlights coming from the
  35030. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35031. */
  35032. _this._specularIntensity = 1.0;
  35033. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35034. /**
  35035. * Debug Control allowing disabling the bump map on this material.
  35036. */
  35037. _this._disableBumpMap = false;
  35038. /**
  35039. * AKA Occlusion Texture Intensity in other nomenclature.
  35040. */
  35041. _this._ambientTextureStrength = 1.0;
  35042. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35043. /**
  35044. * AKA Diffuse Color in other nomenclature.
  35045. */
  35046. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35047. /**
  35048. * AKA Specular Color in other nomenclature.
  35049. */
  35050. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35051. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35052. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35053. /**
  35054. * AKA Glossiness in other nomenclature.
  35055. */
  35056. _this._microSurface = 0.9;
  35057. /**
  35058. * source material index of refraction (IOR)' / 'destination material IOR.
  35059. */
  35060. _this._indexOfRefraction = 0.66;
  35061. /**
  35062. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35063. */
  35064. _this._invertRefractionY = false;
  35065. /**
  35066. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35067. * Materials half opaque for instance using refraction could benefit from this control.
  35068. */
  35069. _this._linkRefractionWithTransparency = false;
  35070. _this._useLightmapAsShadowmap = false;
  35071. /**
  35072. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  35073. */
  35074. _this._useAlphaFromAlbedoTexture = false;
  35075. /**
  35076. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35077. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35078. */
  35079. _this._useSpecularOverAlpha = true;
  35080. /**
  35081. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35082. */
  35083. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  35084. /**
  35085. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35086. */
  35087. _this._useRoughnessFromMetallicTextureAlpha = true;
  35088. /**
  35089. * Specifies if the metallic texture contains the roughness information in its green channel.
  35090. */
  35091. _this._useRoughnessFromMetallicTextureGreen = false;
  35092. /**
  35093. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35094. */
  35095. _this._useMetallnessFromMetallicTextureBlue = false;
  35096. /**
  35097. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35098. */
  35099. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  35100. /**
  35101. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35102. */
  35103. _this._useAmbientInGrayScale = false;
  35104. /**
  35105. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35106. * The material will try to infer what glossiness each pixel should be.
  35107. */
  35108. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  35109. /**
  35110. * BJS is using an harcoded light falloff based on a manually sets up range.
  35111. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35112. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35113. */
  35114. _this._usePhysicalLightFalloff = true;
  35115. /**
  35116. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35117. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35118. */
  35119. _this._useRadianceOverAlpha = true;
  35120. /**
  35121. * Allows using the bump map in parallax mode.
  35122. */
  35123. _this._useParallax = false;
  35124. /**
  35125. * Allows using the bump map in parallax occlusion mode.
  35126. */
  35127. _this._useParallaxOcclusion = false;
  35128. /**
  35129. * Controls the scale bias of the parallax mode.
  35130. */
  35131. _this._parallaxScaleBias = 0.05;
  35132. /**
  35133. * If sets to true, disables all the lights affecting the material.
  35134. */
  35135. _this._disableLighting = false;
  35136. /**
  35137. * Number of Simultaneous lights allowed on the material.
  35138. */
  35139. _this._maxSimultaneousLights = 4;
  35140. /**
  35141. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35142. */
  35143. _this._invertNormalMapX = false;
  35144. /**
  35145. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35146. */
  35147. _this._invertNormalMapY = false;
  35148. /**
  35149. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35150. */
  35151. _this._twoSidedLighting = false;
  35152. /**
  35153. * Defines the alpha limits in alpha test mode.
  35154. */
  35155. _this._alphaCutOff = 0.4;
  35156. /**
  35157. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35158. */
  35159. _this._forceAlphaTest = false;
  35160. /**
  35161. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35162. * And/Or occlude the blended part.
  35163. */
  35164. _this._useAlphaFresnel = false;
  35165. /**
  35166. * The transparency mode of the material.
  35167. */
  35168. _this._transparencyMode = null;
  35169. /**
  35170. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  35171. * from cos thetav and roughness:
  35172. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  35173. */
  35174. _this._environmentBRDFTexture = null;
  35175. /**
  35176. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35177. */
  35178. _this._forceIrradianceInFragment = false;
  35179. /**
  35180. * Force normal to face away from face.
  35181. * (Temporary internal fix to remove before 3.1)
  35182. */
  35183. _this._forceNormalForward = false;
  35184. _this._renderTargets = new BABYLON.SmartArray(16);
  35185. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35186. // Setup the default processing configuration to the scene.
  35187. _this._attachImageProcessingConfiguration(null);
  35188. _this.getRenderTargetTextures = function () {
  35189. _this._renderTargets.reset();
  35190. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35191. _this._renderTargets.push(_this._reflectionTexture);
  35192. }
  35193. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35194. _this._renderTargets.push(_this._refractionTexture);
  35195. }
  35196. return _this._renderTargets;
  35197. };
  35198. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35199. return _this;
  35200. }
  35201. /**
  35202. * Attaches a new image processing configuration to the PBR Material.
  35203. * @param configuration
  35204. */
  35205. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35206. var _this = this;
  35207. if (configuration === this._imageProcessingConfiguration) {
  35208. return;
  35209. }
  35210. // Detaches observer.
  35211. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35212. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35213. }
  35214. // Pick the scene configuration if needed.
  35215. if (!configuration) {
  35216. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35217. }
  35218. else {
  35219. this._imageProcessingConfiguration = configuration;
  35220. }
  35221. // Attaches observer.
  35222. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35223. _this._markAllSubMeshesAsImageProcessingDirty();
  35224. });
  35225. };
  35226. PBRBaseMaterial.prototype.getClassName = function () {
  35227. return "PBRBaseMaterial";
  35228. };
  35229. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35230. get: function () {
  35231. return this._useLogarithmicDepth;
  35232. },
  35233. set: function (value) {
  35234. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35235. },
  35236. enumerable: true,
  35237. configurable: true
  35238. });
  35239. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  35240. /**
  35241. * Gets the current transparency mode.
  35242. */
  35243. get: function () {
  35244. return this._transparencyMode;
  35245. },
  35246. /**
  35247. * Sets the transparency mode of the material.
  35248. */
  35249. set: function (value) {
  35250. if (this._transparencyMode === value) {
  35251. return;
  35252. }
  35253. this._transparencyMode = value;
  35254. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  35255. this._markAllSubMeshesAsTexturesDirty();
  35256. },
  35257. enumerable: true,
  35258. configurable: true
  35259. });
  35260. /**
  35261. * Specifies whether or not the meshes using this material should be rendered in alpha blend mode.
  35262. */
  35263. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35264. if (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35265. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST) {
  35266. return false;
  35267. }
  35268. return _super.prototype.needAlphaBlending.call(this);
  35269. };
  35270. /**
  35271. * Specifies whether or not the meshes using this material should be rendered in alpha blend mode.
  35272. */
  35273. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  35274. if (this._linkRefractionWithTransparency) {
  35275. return false;
  35276. }
  35277. if (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35278. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST) {
  35279. return false;
  35280. }
  35281. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35282. };
  35283. /**
  35284. * Specifies whether or not the meshes using this material should be rendered in alpha test mode.
  35285. */
  35286. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35287. if (this._forceAlphaTest) {
  35288. return true;
  35289. }
  35290. if (this._linkRefractionWithTransparency) {
  35291. return false;
  35292. }
  35293. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35294. };
  35295. /**
  35296. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  35297. */
  35298. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35299. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35300. };
  35301. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35302. return this._albedoTexture;
  35303. };
  35304. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35305. var _this = this;
  35306. if (subMesh.effect && this.isFrozen) {
  35307. if (this._wasPreviouslyReady) {
  35308. return true;
  35309. }
  35310. }
  35311. if (!subMesh._materialDefines) {
  35312. subMesh._materialDefines = new PBRMaterialDefines();
  35313. }
  35314. var scene = this.getScene();
  35315. var defines = subMesh._materialDefines;
  35316. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35317. if (defines._renderId === scene.getRenderId()) {
  35318. return true;
  35319. }
  35320. }
  35321. var engine = scene.getEngine();
  35322. // Lights
  35323. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35324. defines._needNormals = true;
  35325. // Textures
  35326. if (defines._areTexturesDirty) {
  35327. defines._needUVs = false;
  35328. if (scene.texturesEnabled) {
  35329. if (scene.getEngine().getCaps().textureLOD) {
  35330. defines.LODBASEDMICROSFURACE = true;
  35331. }
  35332. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35333. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35334. return false;
  35335. }
  35336. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35337. }
  35338. else {
  35339. defines.ALBEDO = false;
  35340. }
  35341. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35342. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35343. return false;
  35344. }
  35345. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35346. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35347. }
  35348. else {
  35349. defines.AMBIENT = false;
  35350. }
  35351. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35352. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35353. return false;
  35354. }
  35355. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35356. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35357. }
  35358. else {
  35359. defines.OPACITY = false;
  35360. }
  35361. var reflectionTexture = this._getReflectionTexture();
  35362. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35363. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35364. return false;
  35365. }
  35366. defines.REFLECTION = true;
  35367. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35368. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35369. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35370. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35371. defines.INVERTCUBICMAP = true;
  35372. }
  35373. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35374. switch (reflectionTexture.coordinatesMode) {
  35375. case BABYLON.Texture.CUBIC_MODE:
  35376. case BABYLON.Texture.INVCUBIC_MODE:
  35377. defines.REFLECTIONMAP_CUBIC = true;
  35378. break;
  35379. case BABYLON.Texture.EXPLICIT_MODE:
  35380. defines.REFLECTIONMAP_EXPLICIT = true;
  35381. break;
  35382. case BABYLON.Texture.PLANAR_MODE:
  35383. defines.REFLECTIONMAP_PLANAR = true;
  35384. break;
  35385. case BABYLON.Texture.PROJECTION_MODE:
  35386. defines.REFLECTIONMAP_PROJECTION = true;
  35387. break;
  35388. case BABYLON.Texture.SKYBOX_MODE:
  35389. defines.REFLECTIONMAP_SKYBOX = true;
  35390. break;
  35391. case BABYLON.Texture.SPHERICAL_MODE:
  35392. defines.REFLECTIONMAP_SPHERICAL = true;
  35393. break;
  35394. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35395. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35396. break;
  35397. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35398. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35399. break;
  35400. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35401. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35402. break;
  35403. }
  35404. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35405. if (reflectionTexture.sphericalPolynomial) {
  35406. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35407. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35408. defines.USESPHERICALINVERTEX = false;
  35409. }
  35410. else {
  35411. defines.USESPHERICALINVERTEX = true;
  35412. }
  35413. }
  35414. }
  35415. }
  35416. else {
  35417. defines.REFLECTION = false;
  35418. defines.REFLECTIONMAP_3D = false;
  35419. defines.REFLECTIONMAP_SPHERICAL = false;
  35420. defines.REFLECTIONMAP_PLANAR = false;
  35421. defines.REFLECTIONMAP_CUBIC = false;
  35422. defines.REFLECTIONMAP_PROJECTION = false;
  35423. defines.REFLECTIONMAP_SKYBOX = false;
  35424. defines.REFLECTIONMAP_EXPLICIT = false;
  35425. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35426. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35427. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35428. defines.INVERTCUBICMAP = false;
  35429. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35430. defines.USESPHERICALINVERTEX = false;
  35431. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35432. defines.LODINREFLECTIONALPHA = false;
  35433. defines.GAMMAREFLECTION = false;
  35434. }
  35435. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35436. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35437. return false;
  35438. }
  35439. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35440. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35441. }
  35442. else {
  35443. defines.LIGHTMAP = false;
  35444. }
  35445. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35446. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35447. return false;
  35448. }
  35449. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35450. }
  35451. else {
  35452. defines.EMISSIVE = false;
  35453. }
  35454. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35455. if (this._metallicTexture) {
  35456. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35457. return false;
  35458. }
  35459. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35460. defines.METALLICWORKFLOW = true;
  35461. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35462. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35463. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35464. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35465. }
  35466. else if (this._reflectivityTexture) {
  35467. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35468. return false;
  35469. }
  35470. defines.METALLICWORKFLOW = false;
  35471. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35472. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35473. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35474. }
  35475. else {
  35476. defines.METALLICWORKFLOW = false;
  35477. defines.REFLECTIVITY = false;
  35478. }
  35479. if (this._microSurfaceTexture) {
  35480. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35481. return false;
  35482. }
  35483. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35484. }
  35485. else {
  35486. defines.MICROSURFACEMAP = false;
  35487. }
  35488. }
  35489. else {
  35490. defines.REFLECTIVITY = false;
  35491. defines.MICROSURFACEMAP = false;
  35492. }
  35493. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35494. // Bump texure can not be none blocking.
  35495. if (!this._bumpTexture.isReady()) {
  35496. return false;
  35497. }
  35498. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35499. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35500. defines.PARALLAX = true;
  35501. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35502. }
  35503. else {
  35504. defines.PARALLAX = false;
  35505. }
  35506. }
  35507. else {
  35508. defines.BUMP = false;
  35509. }
  35510. var refractionTexture = this._getRefractionTexture();
  35511. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35512. if (!refractionTexture.isReadyOrNotBlocking()) {
  35513. return false;
  35514. }
  35515. defines.REFRACTION = true;
  35516. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35517. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35518. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35519. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35520. if (this._linkRefractionWithTransparency) {
  35521. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35522. }
  35523. }
  35524. else {
  35525. defines.REFRACTION = false;
  35526. }
  35527. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35528. // This is blocking.
  35529. if (!this._environmentBRDFTexture.isReady()) {
  35530. return false;
  35531. }
  35532. defines.ENVIRONMENTBRDF = true;
  35533. }
  35534. else {
  35535. defines.ENVIRONMENTBRDF = false;
  35536. }
  35537. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35538. defines.ALPHAFROMALBEDO = true;
  35539. }
  35540. else {
  35541. defines.ALPHAFROMALBEDO = false;
  35542. }
  35543. }
  35544. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35545. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35546. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35547. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35548. defines.METALLICWORKFLOW = true;
  35549. }
  35550. else {
  35551. defines.METALLICWORKFLOW = false;
  35552. }
  35553. if (!this.backFaceCulling && this._twoSidedLighting) {
  35554. defines.TWOSIDEDLIGHTING = true;
  35555. }
  35556. else {
  35557. defines.TWOSIDEDLIGHTING = false;
  35558. }
  35559. defines.ALPHATESTVALUE = this._alphaCutOff;
  35560. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35561. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  35562. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35563. }
  35564. if (defines._areImageProcessingDirty) {
  35565. if (!this._imageProcessingConfiguration.isReady()) {
  35566. return false;
  35567. }
  35568. this._imageProcessingConfiguration.prepareDefines(defines);
  35569. }
  35570. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35571. // Misc.
  35572. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35573. // Values that need to be evaluated on every frame
  35574. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35575. // Attribs
  35576. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE)) {
  35577. if (mesh) {
  35578. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35579. mesh.createNormals(true);
  35580. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35581. }
  35582. }
  35583. }
  35584. // Get correct effect
  35585. if (defines.isDirty) {
  35586. defines.markAsProcessed();
  35587. scene.resetCachedMaterial();
  35588. // Fallbacks
  35589. var fallbacks = new BABYLON.EffectFallbacks();
  35590. var fallbackRank = 0;
  35591. if (defines.USESPHERICALINVERTEX) {
  35592. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  35593. }
  35594. if (defines.FOG) {
  35595. fallbacks.addFallback(fallbackRank, "FOG");
  35596. }
  35597. if (defines.POINTSIZE) {
  35598. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  35599. }
  35600. if (defines.LOGARITHMICDEPTH) {
  35601. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  35602. }
  35603. if (defines.PARALLAX) {
  35604. fallbacks.addFallback(fallbackRank, "PARALLAX");
  35605. }
  35606. if (defines.PARALLAXOCCLUSION) {
  35607. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  35608. }
  35609. if (defines.ENVIRONMENTBRDF) {
  35610. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  35611. }
  35612. if (defines.TANGENT) {
  35613. fallbacks.addFallback(fallbackRank++, "TANGENT");
  35614. }
  35615. if (defines.BUMP) {
  35616. fallbacks.addFallback(fallbackRank++, "BUMP");
  35617. }
  35618. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  35619. if (defines.SPECULARTERM) {
  35620. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  35621. }
  35622. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35623. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  35624. }
  35625. if (defines.LIGHTMAP) {
  35626. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  35627. }
  35628. if (defines.NORMAL) {
  35629. fallbacks.addFallback(fallbackRank++, "NORMAL");
  35630. }
  35631. if (defines.AMBIENT) {
  35632. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  35633. }
  35634. if (defines.EMISSIVE) {
  35635. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  35636. }
  35637. if (defines.VERTEXCOLOR) {
  35638. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  35639. }
  35640. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35641. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  35642. }
  35643. if (defines.MORPHTARGETS) {
  35644. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  35645. }
  35646. //Attributes
  35647. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35648. if (defines.NORMAL) {
  35649. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35650. }
  35651. if (defines.TANGENT) {
  35652. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35653. }
  35654. if (defines.UV1) {
  35655. attribs.push(BABYLON.VertexBuffer.UVKind);
  35656. }
  35657. if (defines.UV2) {
  35658. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35659. }
  35660. if (defines.VERTEXCOLOR) {
  35661. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35662. }
  35663. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35664. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35665. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35666. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35667. "vFogInfos", "vFogColor", "pointSize",
  35668. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35669. "mBones",
  35670. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35671. "vLightingIntensity",
  35672. "logarithmicDepthConstant",
  35673. "vSphericalX", "vSphericalY", "vSphericalZ",
  35674. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35675. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35676. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35677. "vTangentSpaceParams"
  35678. ];
  35679. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35680. "bumpSampler", "lightmapSampler", "opacitySampler",
  35681. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35682. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35683. "microSurfaceSampler", "environmentBrdfSampler"];
  35684. var uniformBuffers = ["Material", "Scene"];
  35685. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35686. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35687. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35688. uniformsNames: uniforms,
  35689. uniformBuffersNames: uniformBuffers,
  35690. samplers: samplers,
  35691. defines: defines,
  35692. maxSimultaneousLights: this._maxSimultaneousLights
  35693. });
  35694. var onCompiled = function (effect) {
  35695. if (_this.onCompiled) {
  35696. _this.onCompiled(effect);
  35697. }
  35698. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35699. };
  35700. var join = defines.toString();
  35701. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35702. attributes: attribs,
  35703. uniformsNames: uniforms,
  35704. uniformBuffersNames: uniformBuffers,
  35705. samplers: samplers,
  35706. defines: join,
  35707. fallbacks: fallbacks,
  35708. onCompiled: onCompiled,
  35709. onError: this.onError,
  35710. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35711. }, engine), defines);
  35712. this.buildUniformLayout();
  35713. }
  35714. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35715. return false;
  35716. }
  35717. defines._renderId = scene.getRenderId();
  35718. this._wasPreviouslyReady = true;
  35719. return true;
  35720. };
  35721. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35722. // Order is important !
  35723. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35724. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35725. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35726. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35727. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35728. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35729. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35730. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35731. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35732. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35733. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35734. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35735. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35736. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35737. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35738. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35739. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35740. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35741. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35742. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35743. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35744. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35745. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35746. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35747. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35748. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35749. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35750. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35751. this._uniformBuffer.addUniform("pointSize", 1);
  35752. this._uniformBuffer.create();
  35753. };
  35754. PBRBaseMaterial.prototype.unbind = function () {
  35755. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35756. this._uniformBuffer.setTexture("reflectionSampler", null);
  35757. }
  35758. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35759. this._uniformBuffer.setTexture("refractionSampler", null);
  35760. }
  35761. _super.prototype.unbind.call(this);
  35762. };
  35763. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35764. this._activeEffect.setMatrix("world", world);
  35765. };
  35766. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35767. var scene = this.getScene();
  35768. var defines = subMesh._materialDefines;
  35769. if (!defines) {
  35770. return;
  35771. }
  35772. var effect = subMesh.effect;
  35773. if (!effect) {
  35774. return;
  35775. }
  35776. this._activeEffect = effect;
  35777. // Matrices
  35778. this.bindOnlyWorldMatrix(world);
  35779. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35780. // Bones
  35781. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35782. var reflectionTexture = null;
  35783. if (mustRebind) {
  35784. this._uniformBuffer.bindToEffect(effect, "Material");
  35785. this.bindViewProjection(effect);
  35786. reflectionTexture = this._getReflectionTexture();
  35787. var refractionTexture = this._getRefractionTexture();
  35788. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35789. // Texture uniforms
  35790. if (scene.texturesEnabled) {
  35791. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35792. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35793. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35794. }
  35795. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35796. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35797. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35798. }
  35799. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35800. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35801. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35802. }
  35803. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35804. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35805. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35806. var polynomials = reflectionTexture.sphericalPolynomial;
  35807. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35808. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35809. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35810. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35811. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35812. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35813. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35814. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35815. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35816. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35817. }
  35818. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35819. }
  35820. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35821. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35822. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35823. }
  35824. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35825. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35826. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35827. }
  35828. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35829. if (this._metallicTexture) {
  35830. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35831. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35832. }
  35833. else if (this._reflectivityTexture) {
  35834. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35835. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35836. }
  35837. if (this._microSurfaceTexture) {
  35838. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35839. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35840. }
  35841. }
  35842. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35843. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35844. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35845. if (scene._mirroredCameraPosition) {
  35846. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35847. }
  35848. else {
  35849. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35850. }
  35851. }
  35852. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35853. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35854. var depth = 1.0;
  35855. if (!refractionTexture.isCube) {
  35856. if (refractionTexture.depth) {
  35857. depth = refractionTexture.depth;
  35858. }
  35859. }
  35860. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35861. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35862. }
  35863. }
  35864. // Point size
  35865. if (this.pointsCloud) {
  35866. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35867. }
  35868. // Colors
  35869. if (defines.METALLICWORKFLOW) {
  35870. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35871. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35872. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35873. }
  35874. else {
  35875. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35876. }
  35877. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35878. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35879. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35880. // Misc
  35881. this._lightingInfos.x = this._directIntensity;
  35882. this._lightingInfos.y = this._emissiveIntensity;
  35883. this._lightingInfos.z = this._environmentIntensity;
  35884. this._lightingInfos.w = this._specularIntensity;
  35885. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35886. }
  35887. // Textures
  35888. if (scene.texturesEnabled) {
  35889. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35890. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35891. }
  35892. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35893. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35894. }
  35895. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35896. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35897. }
  35898. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35899. if (defines.LODBASEDMICROSFURACE) {
  35900. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35901. }
  35902. else {
  35903. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35904. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35905. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35906. }
  35907. }
  35908. if (defines.ENVIRONMENTBRDF) {
  35909. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35910. }
  35911. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35912. if (defines.LODBASEDMICROSFURACE) {
  35913. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35914. }
  35915. else {
  35916. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35917. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35918. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35919. }
  35920. }
  35921. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35922. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35923. }
  35924. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35925. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35926. }
  35927. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35928. if (this._metallicTexture) {
  35929. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35930. }
  35931. else if (this._reflectivityTexture) {
  35932. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35933. }
  35934. if (this._microSurfaceTexture) {
  35935. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35936. }
  35937. }
  35938. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35939. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35940. }
  35941. }
  35942. // Clip plane
  35943. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35944. // Colors
  35945. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35946. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35947. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35948. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35949. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35950. }
  35951. if (mustRebind || !this.isFrozen) {
  35952. // Lights
  35953. if (scene.lightsEnabled && !this._disableLighting) {
  35954. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35955. }
  35956. // View
  35957. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35958. this.bindView(effect);
  35959. }
  35960. // Fog
  35961. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35962. // Morph targets
  35963. if (defines.NUM_MORPH_INFLUENCERS) {
  35964. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35965. }
  35966. // image processing
  35967. this._imageProcessingConfiguration.bind(this._activeEffect);
  35968. // Log. depth
  35969. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35970. }
  35971. this._uniformBuffer.update();
  35972. this._afterBind(mesh);
  35973. };
  35974. PBRBaseMaterial.prototype.getAnimatables = function () {
  35975. var results = [];
  35976. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35977. results.push(this._albedoTexture);
  35978. }
  35979. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35980. results.push(this._ambientTexture);
  35981. }
  35982. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35983. results.push(this._opacityTexture);
  35984. }
  35985. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35986. results.push(this._reflectionTexture);
  35987. }
  35988. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35989. results.push(this._emissiveTexture);
  35990. }
  35991. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35992. results.push(this._metallicTexture);
  35993. }
  35994. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35995. results.push(this._reflectivityTexture);
  35996. }
  35997. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35998. results.push(this._bumpTexture);
  35999. }
  36000. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36001. results.push(this._lightmapTexture);
  36002. }
  36003. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36004. results.push(this._refractionTexture);
  36005. }
  36006. return results;
  36007. };
  36008. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36009. if (this._reflectionTexture) {
  36010. return this._reflectionTexture;
  36011. }
  36012. return this.getScene().environmentTexture;
  36013. };
  36014. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36015. if (this._refractionTexture) {
  36016. return this._refractionTexture;
  36017. }
  36018. if (this._linkRefractionWithTransparency) {
  36019. return this.getScene().environmentTexture;
  36020. }
  36021. return null;
  36022. };
  36023. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36024. if (forceDisposeTextures) {
  36025. if (this._albedoTexture) {
  36026. this._albedoTexture.dispose();
  36027. }
  36028. if (this._ambientTexture) {
  36029. this._ambientTexture.dispose();
  36030. }
  36031. if (this._opacityTexture) {
  36032. this._opacityTexture.dispose();
  36033. }
  36034. if (this._reflectionTexture) {
  36035. this._reflectionTexture.dispose();
  36036. }
  36037. if (this._environmentBRDFTexture) {
  36038. this._environmentBRDFTexture.dispose();
  36039. }
  36040. if (this._emissiveTexture) {
  36041. this._emissiveTexture.dispose();
  36042. }
  36043. if (this._metallicTexture) {
  36044. this._metallicTexture.dispose();
  36045. }
  36046. if (this._reflectivityTexture) {
  36047. this._reflectivityTexture.dispose();
  36048. }
  36049. if (this._bumpTexture) {
  36050. this._bumpTexture.dispose();
  36051. }
  36052. if (this._lightmapTexture) {
  36053. this._lightmapTexture.dispose();
  36054. }
  36055. if (this._refractionTexture) {
  36056. this._refractionTexture.dispose();
  36057. }
  36058. }
  36059. this._renderTargets.dispose();
  36060. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36061. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36062. }
  36063. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36064. };
  36065. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  36066. __decorate([
  36067. BABYLON.serializeAsImageProcessingConfiguration()
  36068. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  36069. __decorate([
  36070. BABYLON.serialize()
  36071. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  36072. __decorate([
  36073. BABYLON.serialize()
  36074. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  36075. return PBRBaseMaterial;
  36076. }(BABYLON.PushMaterial));
  36077. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  36078. })(BABYLON || (BABYLON = {}));
  36079. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  36080. var BABYLON;
  36081. (function (BABYLON) {
  36082. var Internals;
  36083. (function (Internals) {
  36084. /**
  36085. * The Physically based simple base material of BJS.
  36086. *
  36087. * This enables better naming and convention enforcements on top of the pbrMaterial.
  36088. * It is used as the base class for both the specGloss and metalRough conventions.
  36089. */
  36090. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  36091. __extends(PBRBaseSimpleMaterial, _super);
  36092. /**
  36093. * Instantiates a new PBRMaterial instance.
  36094. *
  36095. * @param name The material name
  36096. * @param scene The scene the material will be use in.
  36097. */
  36098. function PBRBaseSimpleMaterial(name, scene) {
  36099. var _this = _super.call(this, name, scene) || this;
  36100. /**
  36101. * Number of Simultaneous lights allowed on the material.
  36102. */
  36103. _this.maxSimultaneousLights = 4;
  36104. /**
  36105. * If sets to true, disables all the lights affecting the material.
  36106. */
  36107. _this.disableLighting = false;
  36108. /**
  36109. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36110. */
  36111. _this.invertNormalMapX = false;
  36112. /**
  36113. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36114. */
  36115. _this.invertNormalMapY = false;
  36116. /**
  36117. * Emissivie color used to self-illuminate the model.
  36118. */
  36119. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36120. /**
  36121. * Occlusion Channel Strenght.
  36122. */
  36123. _this.occlusionStrength = 1.0;
  36124. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36125. _this._useAlphaFromAlbedoTexture = true;
  36126. _this._useAmbientInGrayScale = true;
  36127. return _this;
  36128. }
  36129. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  36130. /**
  36131. * Gets the current double sided mode.
  36132. */
  36133. get: function () {
  36134. return this._twoSidedLighting;
  36135. },
  36136. /**
  36137. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36138. */
  36139. set: function (value) {
  36140. if (this._twoSidedLighting === value) {
  36141. return;
  36142. }
  36143. this._twoSidedLighting = value;
  36144. this.backFaceCulling = !value;
  36145. this._markAllSubMeshesAsTexturesDirty();
  36146. },
  36147. enumerable: true,
  36148. configurable: true
  36149. });
  36150. /**
  36151. * Return the active textures of the material.
  36152. */
  36153. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  36154. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36155. if (this.environmentTexture) {
  36156. activeTextures.push(this.environmentTexture);
  36157. }
  36158. if (this.normalTexture) {
  36159. activeTextures.push(this.normalTexture);
  36160. }
  36161. if (this.emissiveTexture) {
  36162. activeTextures.push(this.emissiveTexture);
  36163. }
  36164. if (this.occlusionTexture) {
  36165. activeTextures.push(this.occlusionTexture);
  36166. }
  36167. return activeTextures;
  36168. };
  36169. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  36170. return "PBRBaseSimpleMaterial";
  36171. };
  36172. __decorate([
  36173. BABYLON.serialize(),
  36174. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36175. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36176. __decorate([
  36177. BABYLON.serialize(),
  36178. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36179. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36180. __decorate([
  36181. BABYLON.serializeAsTexture(),
  36182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36183. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36184. __decorate([
  36185. BABYLON.serialize(),
  36186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36187. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36188. __decorate([
  36189. BABYLON.serialize(),
  36190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36191. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36192. __decorate([
  36193. BABYLON.serializeAsTexture(),
  36194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36195. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36196. __decorate([
  36197. BABYLON.serializeAsColor3("emissive"),
  36198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36199. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36200. __decorate([
  36201. BABYLON.serializeAsTexture(),
  36202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36203. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36204. __decorate([
  36205. BABYLON.serialize(),
  36206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36207. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36208. __decorate([
  36209. BABYLON.serializeAsTexture(),
  36210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36211. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36212. __decorate([
  36213. BABYLON.serialize(),
  36214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36215. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36216. __decorate([
  36217. BABYLON.serialize()
  36218. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36219. return PBRBaseSimpleMaterial;
  36220. }(BABYLON.PBRBaseMaterial));
  36221. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36222. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36223. })(BABYLON || (BABYLON = {}));
  36224. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36225. var BABYLON;
  36226. (function (BABYLON) {
  36227. /**
  36228. * The Physically based material of BJS.
  36229. *
  36230. * This offers the main features of a standard PBR material.
  36231. * For more information, please refer to the documentation :
  36232. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36233. */
  36234. var PBRMaterial = /** @class */ (function (_super) {
  36235. __extends(PBRMaterial, _super);
  36236. /**
  36237. * Instantiates a new PBRMaterial instance.
  36238. *
  36239. * @param name The material name
  36240. * @param scene The scene the material will be use in.
  36241. */
  36242. function PBRMaterial(name, scene) {
  36243. var _this = _super.call(this, name, scene) || this;
  36244. /**
  36245. * Intensity of the direct lights e.g. the four lights available in your scene.
  36246. * This impacts both the direct diffuse and specular highlights.
  36247. */
  36248. _this.directIntensity = 1.0;
  36249. /**
  36250. * Intensity of the emissive part of the material.
  36251. * This helps controlling the emissive effect without modifying the emissive color.
  36252. */
  36253. _this.emissiveIntensity = 1.0;
  36254. /**
  36255. * Intensity of the environment e.g. how much the environment will light the object
  36256. * either through harmonics for rough material or through the refelction for shiny ones.
  36257. */
  36258. _this.environmentIntensity = 1.0;
  36259. /**
  36260. * This is a special control allowing the reduction of the specular highlights coming from the
  36261. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36262. */
  36263. _this.specularIntensity = 1.0;
  36264. /**
  36265. * Debug Control allowing disabling the bump map on this material.
  36266. */
  36267. _this.disableBumpMap = false;
  36268. /**
  36269. * AKA Occlusion Texture Intensity in other nomenclature.
  36270. */
  36271. _this.ambientTextureStrength = 1.0;
  36272. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36273. /**
  36274. * AKA Diffuse Color in other nomenclature.
  36275. */
  36276. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36277. /**
  36278. * AKA Specular Color in other nomenclature.
  36279. */
  36280. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36281. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36282. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36283. /**
  36284. * AKA Glossiness in other nomenclature.
  36285. */
  36286. _this.microSurface = 1.0;
  36287. /**
  36288. * source material index of refraction (IOR)' / 'destination material IOR.
  36289. */
  36290. _this.indexOfRefraction = 0.66;
  36291. /**
  36292. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36293. */
  36294. _this.invertRefractionY = false;
  36295. /**
  36296. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36297. * Materials half opaque for instance using refraction could benefit from this control.
  36298. */
  36299. _this.linkRefractionWithTransparency = false;
  36300. _this.useLightmapAsShadowmap = false;
  36301. /**
  36302. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36303. */
  36304. _this.useAlphaFromAlbedoTexture = false;
  36305. /**
  36306. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36307. */
  36308. _this.forceAlphaTest = false;
  36309. /**
  36310. * Defines the alpha limits in alpha test mode.
  36311. */
  36312. _this.alphaCutOff = 0.4;
  36313. /**
  36314. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36315. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36316. */
  36317. _this.useSpecularOverAlpha = true;
  36318. /**
  36319. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36320. */
  36321. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36322. /**
  36323. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36324. */
  36325. _this.useRoughnessFromMetallicTextureAlpha = true;
  36326. /**
  36327. * Specifies if the metallic texture contains the roughness information in its green channel.
  36328. */
  36329. _this.useRoughnessFromMetallicTextureGreen = false;
  36330. /**
  36331. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36332. */
  36333. _this.useMetallnessFromMetallicTextureBlue = false;
  36334. /**
  36335. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36336. */
  36337. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36338. /**
  36339. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36340. */
  36341. _this.useAmbientInGrayScale = false;
  36342. /**
  36343. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36344. * The material will try to infer what glossiness each pixel should be.
  36345. */
  36346. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36347. /**
  36348. * BJS is using an harcoded light falloff based on a manually sets up range.
  36349. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36350. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36351. */
  36352. _this.usePhysicalLightFalloff = true;
  36353. /**
  36354. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36355. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36356. */
  36357. _this.useRadianceOverAlpha = true;
  36358. /**
  36359. * Allows using the bump map in parallax mode.
  36360. */
  36361. _this.useParallax = false;
  36362. /**
  36363. * Allows using the bump map in parallax occlusion mode.
  36364. */
  36365. _this.useParallaxOcclusion = false;
  36366. /**
  36367. * Controls the scale bias of the parallax mode.
  36368. */
  36369. _this.parallaxScaleBias = 0.05;
  36370. /**
  36371. * If sets to true, disables all the lights affecting the material.
  36372. */
  36373. _this.disableLighting = false;
  36374. /**
  36375. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36376. */
  36377. _this.forceIrradianceInFragment = false;
  36378. /**
  36379. * Number of Simultaneous lights allowed on the material.
  36380. */
  36381. _this.maxSimultaneousLights = 4;
  36382. /**
  36383. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36384. */
  36385. _this.invertNormalMapX = false;
  36386. /**
  36387. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36388. */
  36389. _this.invertNormalMapY = false;
  36390. /**
  36391. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36392. */
  36393. _this.twoSidedLighting = false;
  36394. /**
  36395. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36396. * And/Or occlude the blended part.
  36397. */
  36398. _this.useAlphaFresnel = false;
  36399. /**
  36400. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36401. * And/Or occlude the blended part.
  36402. */
  36403. _this.environmentBRDFTexture = null;
  36404. /**
  36405. * Force normal to face away from face.
  36406. * (Temporary internal fix to remove before 3.1)
  36407. */
  36408. _this.forceNormalForward = false;
  36409. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36410. return _this;
  36411. }
  36412. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36413. /**
  36414. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36415. */
  36416. get: function () {
  36417. return this._PBRMATERIAL_OPAQUE;
  36418. },
  36419. enumerable: true,
  36420. configurable: true
  36421. });
  36422. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36423. /**
  36424. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36425. */
  36426. get: function () {
  36427. return this._PBRMATERIAL_ALPHATEST;
  36428. },
  36429. enumerable: true,
  36430. configurable: true
  36431. });
  36432. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36433. /**
  36434. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36435. */
  36436. get: function () {
  36437. return this._PBRMATERIAL_ALPHABLEND;
  36438. },
  36439. enumerable: true,
  36440. configurable: true
  36441. });
  36442. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36443. /**
  36444. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36445. * They are also discarded below the alpha cutoff threshold to improve performances.
  36446. */
  36447. get: function () {
  36448. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36449. },
  36450. enumerable: true,
  36451. configurable: true
  36452. });
  36453. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36454. /**
  36455. * Gets the image processing configuration used either in this material.
  36456. */
  36457. get: function () {
  36458. return this._imageProcessingConfiguration;
  36459. },
  36460. /**
  36461. * Sets the Default image processing configuration used either in the this material.
  36462. *
  36463. * If sets to null, the scene one is in use.
  36464. */
  36465. set: function (value) {
  36466. this._attachImageProcessingConfiguration(value);
  36467. // Ensure the effect will be rebuilt.
  36468. this._markAllSubMeshesAsTexturesDirty();
  36469. },
  36470. enumerable: true,
  36471. configurable: true
  36472. });
  36473. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36474. /**
  36475. * Gets wether the color curves effect is enabled.
  36476. */
  36477. get: function () {
  36478. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36479. },
  36480. /**
  36481. * Sets wether the color curves effect is enabled.
  36482. */
  36483. set: function (value) {
  36484. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36485. },
  36486. enumerable: true,
  36487. configurable: true
  36488. });
  36489. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36490. /**
  36491. * Gets wether the color grading effect is enabled.
  36492. */
  36493. get: function () {
  36494. return this.imageProcessingConfiguration.colorGradingEnabled;
  36495. },
  36496. /**
  36497. * Gets wether the color grading effect is enabled.
  36498. */
  36499. set: function (value) {
  36500. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36501. },
  36502. enumerable: true,
  36503. configurable: true
  36504. });
  36505. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36506. /**
  36507. * Gets wether tonemapping is enabled or not.
  36508. */
  36509. get: function () {
  36510. return this._imageProcessingConfiguration.toneMappingEnabled;
  36511. },
  36512. /**
  36513. * Sets wether tonemapping is enabled or not
  36514. */
  36515. set: function (value) {
  36516. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36517. },
  36518. enumerable: true,
  36519. configurable: true
  36520. });
  36521. ;
  36522. ;
  36523. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36524. /**
  36525. * The camera exposure used on this material.
  36526. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36527. * This corresponds to a photographic exposure.
  36528. */
  36529. get: function () {
  36530. return this._imageProcessingConfiguration.exposure;
  36531. },
  36532. /**
  36533. * The camera exposure used on this material.
  36534. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36535. * This corresponds to a photographic exposure.
  36536. */
  36537. set: function (value) {
  36538. this._imageProcessingConfiguration.exposure = value;
  36539. },
  36540. enumerable: true,
  36541. configurable: true
  36542. });
  36543. ;
  36544. ;
  36545. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36546. /**
  36547. * Gets The camera contrast used on this material.
  36548. */
  36549. get: function () {
  36550. return this._imageProcessingConfiguration.contrast;
  36551. },
  36552. /**
  36553. * Sets The camera contrast used on this material.
  36554. */
  36555. set: function (value) {
  36556. this._imageProcessingConfiguration.contrast = value;
  36557. },
  36558. enumerable: true,
  36559. configurable: true
  36560. });
  36561. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36562. /**
  36563. * Gets the Color Grading 2D Lookup Texture.
  36564. */
  36565. get: function () {
  36566. return this._imageProcessingConfiguration.colorGradingTexture;
  36567. },
  36568. /**
  36569. * Sets the Color Grading 2D Lookup Texture.
  36570. */
  36571. set: function (value) {
  36572. this._imageProcessingConfiguration.colorGradingTexture = value;
  36573. },
  36574. enumerable: true,
  36575. configurable: true
  36576. });
  36577. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36578. /**
  36579. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36580. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36581. * 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;
  36582. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36583. */
  36584. get: function () {
  36585. return this._imageProcessingConfiguration.colorCurves;
  36586. },
  36587. /**
  36588. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36589. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36590. * 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;
  36591. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36592. */
  36593. set: function (value) {
  36594. this._imageProcessingConfiguration.colorCurves = value;
  36595. },
  36596. enumerable: true,
  36597. configurable: true
  36598. });
  36599. PBRMaterial.prototype.getClassName = function () {
  36600. return "PBRMaterial";
  36601. };
  36602. PBRMaterial.prototype.getActiveTextures = function () {
  36603. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36604. if (this._albedoTexture) {
  36605. activeTextures.push(this._albedoTexture);
  36606. }
  36607. if (this._ambientTexture) {
  36608. activeTextures.push(this._ambientTexture);
  36609. }
  36610. if (this._opacityTexture) {
  36611. activeTextures.push(this._opacityTexture);
  36612. }
  36613. if (this._reflectionTexture) {
  36614. activeTextures.push(this._reflectionTexture);
  36615. }
  36616. if (this._emissiveTexture) {
  36617. activeTextures.push(this._emissiveTexture);
  36618. }
  36619. if (this._reflectivityTexture) {
  36620. activeTextures.push(this._reflectivityTexture);
  36621. }
  36622. if (this._metallicTexture) {
  36623. activeTextures.push(this._metallicTexture);
  36624. }
  36625. if (this._microSurfaceTexture) {
  36626. activeTextures.push(this._microSurfaceTexture);
  36627. }
  36628. if (this._bumpTexture) {
  36629. activeTextures.push(this._bumpTexture);
  36630. }
  36631. if (this._lightmapTexture) {
  36632. activeTextures.push(this._lightmapTexture);
  36633. }
  36634. if (this._refractionTexture) {
  36635. activeTextures.push(this._refractionTexture);
  36636. }
  36637. return activeTextures;
  36638. };
  36639. PBRMaterial.prototype.hasTexture = function (texture) {
  36640. if (_super.prototype.hasTexture.call(this, texture)) {
  36641. return true;
  36642. }
  36643. if (this._albedoTexture === texture) {
  36644. return true;
  36645. }
  36646. if (this._ambientTexture === texture) {
  36647. return true;
  36648. }
  36649. if (this._opacityTexture === texture) {
  36650. return true;
  36651. }
  36652. if (this._reflectionTexture === texture) {
  36653. return true;
  36654. }
  36655. if (this._reflectivityTexture === texture) {
  36656. return true;
  36657. }
  36658. if (this._metallicTexture === texture) {
  36659. return true;
  36660. }
  36661. if (this._microSurfaceTexture === texture) {
  36662. return true;
  36663. }
  36664. if (this._bumpTexture === texture) {
  36665. return true;
  36666. }
  36667. if (this._lightmapTexture === texture) {
  36668. return true;
  36669. }
  36670. if (this._refractionTexture === texture) {
  36671. return true;
  36672. }
  36673. return false;
  36674. };
  36675. PBRMaterial.prototype.clone = function (name) {
  36676. var _this = this;
  36677. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36678. clone.id = name;
  36679. clone.name = name;
  36680. return clone;
  36681. };
  36682. PBRMaterial.prototype.serialize = function () {
  36683. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36684. serializationObject.customType = "BABYLON.PBRMaterial";
  36685. return serializationObject;
  36686. };
  36687. // Statics
  36688. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36689. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36690. };
  36691. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36692. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36693. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36694. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36695. __decorate([
  36696. BABYLON.serialize(),
  36697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36698. ], PBRMaterial.prototype, "directIntensity", void 0);
  36699. __decorate([
  36700. BABYLON.serialize(),
  36701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36702. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36703. __decorate([
  36704. BABYLON.serialize(),
  36705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36706. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36707. __decorate([
  36708. BABYLON.serialize(),
  36709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36710. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36711. __decorate([
  36712. BABYLON.serialize(),
  36713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36714. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36715. __decorate([
  36716. BABYLON.serializeAsTexture(),
  36717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36718. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36719. __decorate([
  36720. BABYLON.serializeAsTexture(),
  36721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36722. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36723. __decorate([
  36724. BABYLON.serialize(),
  36725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36726. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36727. __decorate([
  36728. BABYLON.serializeAsTexture(),
  36729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36730. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36731. __decorate([
  36732. BABYLON.serializeAsTexture(),
  36733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36734. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36735. __decorate([
  36736. BABYLON.serializeAsTexture(),
  36737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36738. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36739. __decorate([
  36740. BABYLON.serializeAsTexture(),
  36741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36742. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36743. __decorate([
  36744. BABYLON.serializeAsTexture(),
  36745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36746. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36747. __decorate([
  36748. BABYLON.serialize(),
  36749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36750. ], PBRMaterial.prototype, "metallic", void 0);
  36751. __decorate([
  36752. BABYLON.serialize(),
  36753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36754. ], PBRMaterial.prototype, "roughness", void 0);
  36755. __decorate([
  36756. BABYLON.serializeAsTexture(),
  36757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36758. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36759. __decorate([
  36760. BABYLON.serializeAsTexture(),
  36761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36762. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36763. __decorate([
  36764. BABYLON.serializeAsTexture(),
  36765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36766. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36767. __decorate([
  36768. BABYLON.serializeAsTexture(),
  36769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36770. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36771. __decorate([
  36772. BABYLON.serializeAsColor3("ambient"),
  36773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36774. ], PBRMaterial.prototype, "ambientColor", void 0);
  36775. __decorate([
  36776. BABYLON.serializeAsColor3("albedo"),
  36777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36778. ], PBRMaterial.prototype, "albedoColor", void 0);
  36779. __decorate([
  36780. BABYLON.serializeAsColor3("reflectivity"),
  36781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36782. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36783. __decorate([
  36784. BABYLON.serializeAsColor3("reflection"),
  36785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36786. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36787. __decorate([
  36788. BABYLON.serializeAsColor3("emissive"),
  36789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36790. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36791. __decorate([
  36792. BABYLON.serialize(),
  36793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36794. ], PBRMaterial.prototype, "microSurface", void 0);
  36795. __decorate([
  36796. BABYLON.serialize(),
  36797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36798. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36799. __decorate([
  36800. BABYLON.serialize(),
  36801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36802. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36803. __decorate([
  36804. BABYLON.serialize(),
  36805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36806. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36807. __decorate([
  36808. BABYLON.serialize(),
  36809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36810. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36811. __decorate([
  36812. BABYLON.serialize(),
  36813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36814. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36815. __decorate([
  36816. BABYLON.serialize(),
  36817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36818. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36819. __decorate([
  36820. BABYLON.serialize(),
  36821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36822. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36823. __decorate([
  36824. BABYLON.serialize(),
  36825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36826. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36827. __decorate([
  36828. BABYLON.serialize(),
  36829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36830. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36831. __decorate([
  36832. BABYLON.serialize(),
  36833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36834. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36835. __decorate([
  36836. BABYLON.serialize(),
  36837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36838. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36839. __decorate([
  36840. BABYLON.serialize(),
  36841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36842. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36843. __decorate([
  36844. BABYLON.serialize(),
  36845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36846. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36847. __decorate([
  36848. BABYLON.serialize(),
  36849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36850. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36851. __decorate([
  36852. BABYLON.serialize(),
  36853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36854. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36855. __decorate([
  36856. BABYLON.serialize(),
  36857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36858. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36859. __decorate([
  36860. BABYLON.serialize(),
  36861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36862. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36863. __decorate([
  36864. BABYLON.serialize(),
  36865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36866. ], PBRMaterial.prototype, "useParallax", void 0);
  36867. __decorate([
  36868. BABYLON.serialize(),
  36869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36870. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36871. __decorate([
  36872. BABYLON.serialize(),
  36873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36874. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36875. __decorate([
  36876. BABYLON.serialize(),
  36877. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36878. ], PBRMaterial.prototype, "disableLighting", void 0);
  36879. __decorate([
  36880. BABYLON.serialize(),
  36881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36882. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36883. __decorate([
  36884. BABYLON.serialize(),
  36885. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36886. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36887. __decorate([
  36888. BABYLON.serialize(),
  36889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36890. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36891. __decorate([
  36892. BABYLON.serialize(),
  36893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36894. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36895. __decorate([
  36896. BABYLON.serialize(),
  36897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36898. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36899. __decorate([
  36900. BABYLON.serialize(),
  36901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36902. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36903. __decorate([
  36904. BABYLON.serializeAsTexture(),
  36905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36906. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36907. __decorate([
  36908. BABYLON.serialize(),
  36909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36910. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36911. return PBRMaterial;
  36912. }(BABYLON.PBRBaseMaterial));
  36913. BABYLON.PBRMaterial = PBRMaterial;
  36914. })(BABYLON || (BABYLON = {}));
  36915. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36916. var BABYLON;
  36917. (function (BABYLON) {
  36918. /**
  36919. * The PBR material of BJS following the metal roughness convention.
  36920. *
  36921. * This fits to the PBR convention in the GLTF definition:
  36922. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36923. */
  36924. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36925. __extends(PBRMetallicRoughnessMaterial, _super);
  36926. /**
  36927. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36928. *
  36929. * @param name The material name
  36930. * @param scene The scene the material will be use in.
  36931. */
  36932. function PBRMetallicRoughnessMaterial(name, scene) {
  36933. var _this = _super.call(this, name, scene) || this;
  36934. _this._useRoughnessFromMetallicTextureAlpha = false;
  36935. _this._useRoughnessFromMetallicTextureGreen = true;
  36936. _this._useMetallnessFromMetallicTextureBlue = true;
  36937. return _this;
  36938. }
  36939. /**
  36940. * Return the currrent class name of the material.
  36941. */
  36942. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36943. return "PBRMetallicRoughnessMaterial";
  36944. };
  36945. /**
  36946. * Return the active textures of the material.
  36947. */
  36948. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36949. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36950. if (this.baseTexture) {
  36951. activeTextures.push(this.baseTexture);
  36952. }
  36953. if (this.metallicRoughnessTexture) {
  36954. activeTextures.push(this.metallicRoughnessTexture);
  36955. }
  36956. return activeTextures;
  36957. };
  36958. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36959. if (_super.prototype.hasTexture.call(this, texture)) {
  36960. return true;
  36961. }
  36962. if (this.baseTexture === texture) {
  36963. return true;
  36964. }
  36965. if (this.metallicRoughnessTexture === texture) {
  36966. return true;
  36967. }
  36968. return false;
  36969. };
  36970. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36971. var _this = this;
  36972. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36973. clone.id = name;
  36974. clone.name = name;
  36975. return clone;
  36976. };
  36977. /**
  36978. * Serialize the material to a parsable JSON object.
  36979. */
  36980. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36981. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36982. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36983. return serializationObject;
  36984. };
  36985. /**
  36986. * Parses a JSON object correponding to the serialize function.
  36987. */
  36988. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36989. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36990. };
  36991. __decorate([
  36992. BABYLON.serializeAsColor3(),
  36993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36994. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36995. __decorate([
  36996. BABYLON.serializeAsTexture(),
  36997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36998. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36999. __decorate([
  37000. BABYLON.serialize(),
  37001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37002. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  37003. __decorate([
  37004. BABYLON.serialize(),
  37005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37006. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  37007. __decorate([
  37008. BABYLON.serializeAsTexture(),
  37009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  37010. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  37011. return PBRMetallicRoughnessMaterial;
  37012. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37013. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  37014. })(BABYLON || (BABYLON = {}));
  37015. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  37016. var BABYLON;
  37017. (function (BABYLON) {
  37018. /**
  37019. * The PBR material of BJS following the specular glossiness convention.
  37020. *
  37021. * This fits to the PBR convention in the GLTF definition:
  37022. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  37023. */
  37024. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  37025. __extends(PBRSpecularGlossinessMaterial, _super);
  37026. /**
  37027. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  37028. *
  37029. * @param name The material name
  37030. * @param scene The scene the material will be use in.
  37031. */
  37032. function PBRSpecularGlossinessMaterial(name, scene) {
  37033. var _this = _super.call(this, name, scene) || this;
  37034. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  37035. return _this;
  37036. }
  37037. /**
  37038. * Return the currrent class name of the material.
  37039. */
  37040. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  37041. return "PBRSpecularGlossinessMaterial";
  37042. };
  37043. /**
  37044. * Return the active textures of the material.
  37045. */
  37046. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  37047. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37048. if (this.diffuseTexture) {
  37049. activeTextures.push(this.diffuseTexture);
  37050. }
  37051. if (this.specularGlossinessTexture) {
  37052. activeTextures.push(this.specularGlossinessTexture);
  37053. }
  37054. return activeTextures;
  37055. };
  37056. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  37057. if (_super.prototype.hasTexture.call(this, texture)) {
  37058. return true;
  37059. }
  37060. if (this.diffuseTexture === texture) {
  37061. return true;
  37062. }
  37063. if (this.specularGlossinessTexture === texture) {
  37064. return true;
  37065. }
  37066. return false;
  37067. };
  37068. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  37069. var _this = this;
  37070. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  37071. clone.id = name;
  37072. clone.name = name;
  37073. return clone;
  37074. };
  37075. /**
  37076. * Serialize the material to a parsable JSON object.
  37077. */
  37078. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  37079. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37080. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  37081. return serializationObject;
  37082. };
  37083. /**
  37084. * Parses a JSON object correponding to the serialize function.
  37085. */
  37086. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  37087. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  37088. };
  37089. __decorate([
  37090. BABYLON.serializeAsColor3("diffuse"),
  37091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37092. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  37093. __decorate([
  37094. BABYLON.serializeAsTexture(),
  37095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37096. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  37097. __decorate([
  37098. BABYLON.serializeAsColor3("specular"),
  37099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  37100. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  37101. __decorate([
  37102. BABYLON.serialize(),
  37103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  37104. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  37105. __decorate([
  37106. BABYLON.serializeAsTexture(),
  37107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  37108. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  37109. return PBRSpecularGlossinessMaterial;
  37110. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37111. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  37112. })(BABYLON || (BABYLON = {}));
  37113. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  37114. var BABYLON;
  37115. (function (BABYLON) {
  37116. BABYLON.CameraInputTypes = {};
  37117. var CameraInputsManager = /** @class */ (function () {
  37118. function CameraInputsManager(camera) {
  37119. this.attached = {};
  37120. this.camera = camera;
  37121. this.checkInputs = function () { };
  37122. }
  37123. CameraInputsManager.prototype.add = function (input) {
  37124. var type = input.getSimpleName();
  37125. if (this.attached[type]) {
  37126. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  37127. return;
  37128. }
  37129. this.attached[type] = input;
  37130. input.camera = this.camera;
  37131. //for checkInputs, we are dynamically creating a function
  37132. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  37133. if (input.checkInputs) {
  37134. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37135. }
  37136. if (this.attachedElement) {
  37137. input.attachControl(this.attachedElement);
  37138. }
  37139. };
  37140. CameraInputsManager.prototype.remove = function (inputToRemove) {
  37141. for (var cam in this.attached) {
  37142. var input = this.attached[cam];
  37143. if (input === inputToRemove) {
  37144. input.detachControl(this.attachedElement);
  37145. input.camera = null;
  37146. delete this.attached[cam];
  37147. this.rebuildInputCheck();
  37148. }
  37149. }
  37150. };
  37151. CameraInputsManager.prototype.removeByType = function (inputType) {
  37152. for (var cam in this.attached) {
  37153. var input = this.attached[cam];
  37154. if (input.getClassName() === inputType) {
  37155. input.detachControl(this.attachedElement);
  37156. input.camera = null;
  37157. delete this.attached[cam];
  37158. this.rebuildInputCheck();
  37159. }
  37160. }
  37161. };
  37162. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  37163. var current = this.checkInputs;
  37164. return function () {
  37165. current();
  37166. fn();
  37167. };
  37168. };
  37169. CameraInputsManager.prototype.attachInput = function (input) {
  37170. if (this.attachedElement) {
  37171. input.attachControl(this.attachedElement, this.noPreventDefault);
  37172. }
  37173. };
  37174. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  37175. if (noPreventDefault === void 0) { noPreventDefault = false; }
  37176. if (this.attachedElement) {
  37177. return;
  37178. }
  37179. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37180. this.attachedElement = element;
  37181. this.noPreventDefault = noPreventDefault;
  37182. for (var cam in this.attached) {
  37183. this.attached[cam].attachControl(element, noPreventDefault);
  37184. }
  37185. };
  37186. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37187. if (disconnect === void 0) { disconnect = false; }
  37188. if (this.attachedElement !== element) {
  37189. return;
  37190. }
  37191. for (var cam in this.attached) {
  37192. this.attached[cam].detachControl(element);
  37193. if (disconnect) {
  37194. this.attached[cam].camera = null;
  37195. }
  37196. }
  37197. this.attachedElement = null;
  37198. };
  37199. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37200. this.checkInputs = function () { };
  37201. for (var cam in this.attached) {
  37202. var input = this.attached[cam];
  37203. if (input.checkInputs) {
  37204. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37205. }
  37206. }
  37207. };
  37208. CameraInputsManager.prototype.clear = function () {
  37209. if (this.attachedElement) {
  37210. this.detachElement(this.attachedElement, true);
  37211. }
  37212. this.attached = {};
  37213. this.attachedElement = null;
  37214. this.checkInputs = function () { };
  37215. };
  37216. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37217. var inputs = {};
  37218. for (var cam in this.attached) {
  37219. var input = this.attached[cam];
  37220. var res = BABYLON.SerializationHelper.Serialize(input);
  37221. inputs[input.getClassName()] = res;
  37222. }
  37223. serializedCamera.inputsmgr = inputs;
  37224. };
  37225. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37226. var parsedInputs = parsedCamera.inputsmgr;
  37227. if (parsedInputs) {
  37228. this.clear();
  37229. for (var n in parsedInputs) {
  37230. var construct = BABYLON.CameraInputTypes[n];
  37231. if (construct) {
  37232. var parsedinput = parsedInputs[n];
  37233. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37234. this.add(input);
  37235. }
  37236. }
  37237. }
  37238. else {
  37239. //2016-03-08 this part is for managing backward compatibility
  37240. for (var n in this.attached) {
  37241. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37242. if (construct) {
  37243. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37244. this.remove(this.attached[n]);
  37245. this.add(input);
  37246. }
  37247. }
  37248. }
  37249. };
  37250. return CameraInputsManager;
  37251. }());
  37252. BABYLON.CameraInputsManager = CameraInputsManager;
  37253. })(BABYLON || (BABYLON = {}));
  37254. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37255. var BABYLON;
  37256. (function (BABYLON) {
  37257. var FreeCameraMouseInput = /** @class */ (function () {
  37258. function FreeCameraMouseInput(touchEnabled) {
  37259. if (touchEnabled === void 0) { touchEnabled = true; }
  37260. this.touchEnabled = touchEnabled;
  37261. this.buttons = [0, 1, 2];
  37262. this.angularSensibility = 2000.0;
  37263. this.previousPosition = null;
  37264. }
  37265. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37266. var _this = this;
  37267. var engine = this.camera.getEngine();
  37268. if (!this._pointerInput) {
  37269. this._pointerInput = function (p, s) {
  37270. var evt = p.event;
  37271. if (engine.isInVRExclusivePointerMode) {
  37272. return;
  37273. }
  37274. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37275. return;
  37276. }
  37277. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37278. return;
  37279. }
  37280. var srcElement = (evt.srcElement || evt.target);
  37281. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37282. try {
  37283. srcElement.setPointerCapture(evt.pointerId);
  37284. }
  37285. catch (e) {
  37286. //Nothing to do with the error. Execution will continue.
  37287. }
  37288. _this.previousPosition = {
  37289. x: evt.clientX,
  37290. y: evt.clientY
  37291. };
  37292. if (!noPreventDefault) {
  37293. evt.preventDefault();
  37294. element.focus();
  37295. }
  37296. }
  37297. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37298. try {
  37299. srcElement.releasePointerCapture(evt.pointerId);
  37300. }
  37301. catch (e) {
  37302. //Nothing to do with the error.
  37303. }
  37304. _this.previousPosition = null;
  37305. if (!noPreventDefault) {
  37306. evt.preventDefault();
  37307. }
  37308. }
  37309. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37310. if (!_this.previousPosition || engine.isPointerLock) {
  37311. return;
  37312. }
  37313. var offsetX = evt.clientX - _this.previousPosition.x;
  37314. var offsetY = evt.clientY - _this.previousPosition.y;
  37315. if (_this.camera.getScene().useRightHandedSystem) {
  37316. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37317. }
  37318. else {
  37319. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37320. }
  37321. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37322. _this.previousPosition = {
  37323. x: evt.clientX,
  37324. y: evt.clientY
  37325. };
  37326. if (!noPreventDefault) {
  37327. evt.preventDefault();
  37328. }
  37329. }
  37330. };
  37331. }
  37332. this._onMouseMove = function (evt) {
  37333. if (!engine.isPointerLock) {
  37334. return;
  37335. }
  37336. if (engine.isInVRExclusivePointerMode) {
  37337. return;
  37338. }
  37339. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37340. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37341. if (_this.camera.getScene().useRightHandedSystem) {
  37342. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37343. }
  37344. else {
  37345. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37346. }
  37347. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37348. _this.previousPosition = null;
  37349. if (!noPreventDefault) {
  37350. evt.preventDefault();
  37351. }
  37352. };
  37353. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37354. element.addEventListener("mousemove", this._onMouseMove, false);
  37355. };
  37356. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37357. if (this._observer && element) {
  37358. this.camera.getScene().onPointerObservable.remove(this._observer);
  37359. if (this._onMouseMove) {
  37360. element.removeEventListener("mousemove", this._onMouseMove);
  37361. }
  37362. this._observer = null;
  37363. this._onMouseMove = null;
  37364. this.previousPosition = null;
  37365. }
  37366. };
  37367. FreeCameraMouseInput.prototype.getClassName = function () {
  37368. return "FreeCameraMouseInput";
  37369. };
  37370. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37371. return "mouse";
  37372. };
  37373. __decorate([
  37374. BABYLON.serialize()
  37375. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37376. __decorate([
  37377. BABYLON.serialize()
  37378. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37379. return FreeCameraMouseInput;
  37380. }());
  37381. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37382. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37383. })(BABYLON || (BABYLON = {}));
  37384. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37385. var BABYLON;
  37386. (function (BABYLON) {
  37387. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37388. function FreeCameraKeyboardMoveInput() {
  37389. this._keys = new Array();
  37390. this.keysUp = [38];
  37391. this.keysDown = [40];
  37392. this.keysLeft = [37];
  37393. this.keysRight = [39];
  37394. }
  37395. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37396. var _this = this;
  37397. if (this._onCanvasBlurObserver) {
  37398. return;
  37399. }
  37400. this._scene = this.camera.getScene();
  37401. this._engine = this._scene.getEngine();
  37402. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37403. _this._keys = [];
  37404. });
  37405. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37406. var evt = info.event;
  37407. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37408. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37409. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37410. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37411. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37412. var index = _this._keys.indexOf(evt.keyCode);
  37413. if (index === -1) {
  37414. _this._keys.push(evt.keyCode);
  37415. }
  37416. if (!noPreventDefault) {
  37417. evt.preventDefault();
  37418. }
  37419. }
  37420. }
  37421. else {
  37422. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37423. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37424. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37425. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37426. var index = _this._keys.indexOf(evt.keyCode);
  37427. if (index >= 0) {
  37428. _this._keys.splice(index, 1);
  37429. }
  37430. if (!noPreventDefault) {
  37431. evt.preventDefault();
  37432. }
  37433. }
  37434. }
  37435. });
  37436. };
  37437. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37438. if (this._scene) {
  37439. if (this._onKeyboardObserver) {
  37440. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37441. }
  37442. if (this._onCanvasBlurObserver) {
  37443. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37444. }
  37445. this._onKeyboardObserver = null;
  37446. this._onCanvasBlurObserver = null;
  37447. }
  37448. this._keys = [];
  37449. };
  37450. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37451. if (this._onKeyboardObserver) {
  37452. var camera = this.camera;
  37453. // Keyboard
  37454. for (var index = 0; index < this._keys.length; index++) {
  37455. var keyCode = this._keys[index];
  37456. var speed = camera._computeLocalCameraSpeed();
  37457. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37458. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37459. }
  37460. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37461. camera._localDirection.copyFromFloats(0, 0, speed);
  37462. }
  37463. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37464. camera._localDirection.copyFromFloats(speed, 0, 0);
  37465. }
  37466. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37467. camera._localDirection.copyFromFloats(0, 0, -speed);
  37468. }
  37469. if (camera.getScene().useRightHandedSystem) {
  37470. camera._localDirection.z *= -1;
  37471. }
  37472. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37473. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37474. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37475. }
  37476. }
  37477. };
  37478. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37479. return "FreeCameraKeyboardMoveInput";
  37480. };
  37481. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37482. this._keys = [];
  37483. };
  37484. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37485. return "keyboard";
  37486. };
  37487. __decorate([
  37488. BABYLON.serialize()
  37489. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37490. __decorate([
  37491. BABYLON.serialize()
  37492. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37493. __decorate([
  37494. BABYLON.serialize()
  37495. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37496. __decorate([
  37497. BABYLON.serialize()
  37498. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37499. return FreeCameraKeyboardMoveInput;
  37500. }());
  37501. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37502. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37503. })(BABYLON || (BABYLON = {}));
  37504. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37505. var BABYLON;
  37506. (function (BABYLON) {
  37507. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37508. __extends(FreeCameraInputsManager, _super);
  37509. function FreeCameraInputsManager(camera) {
  37510. return _super.call(this, camera) || this;
  37511. }
  37512. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37513. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37514. return this;
  37515. };
  37516. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37517. if (touchEnabled === void 0) { touchEnabled = true; }
  37518. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37519. return this;
  37520. };
  37521. FreeCameraInputsManager.prototype.addGamepad = function () {
  37522. this.add(new BABYLON.FreeCameraGamepadInput());
  37523. return this;
  37524. };
  37525. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37526. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37527. return this;
  37528. };
  37529. FreeCameraInputsManager.prototype.addTouch = function () {
  37530. this.add(new BABYLON.FreeCameraTouchInput());
  37531. return this;
  37532. };
  37533. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37534. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37535. return this;
  37536. };
  37537. return FreeCameraInputsManager;
  37538. }(BABYLON.CameraInputsManager));
  37539. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37540. })(BABYLON || (BABYLON = {}));
  37541. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37542. var BABYLON;
  37543. (function (BABYLON) {
  37544. var TargetCamera = /** @class */ (function (_super) {
  37545. __extends(TargetCamera, _super);
  37546. function TargetCamera(name, position, scene) {
  37547. var _this = _super.call(this, name, position, scene) || this;
  37548. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37549. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37550. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37551. _this.speed = 2.0;
  37552. _this.noRotationConstraint = false;
  37553. _this.lockedTarget = null;
  37554. _this._currentTarget = BABYLON.Vector3.Zero();
  37555. _this._viewMatrix = BABYLON.Matrix.Zero();
  37556. _this._camMatrix = BABYLON.Matrix.Zero();
  37557. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37558. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37559. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37560. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37561. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37562. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37563. _this._tempMatrix = BABYLON.Matrix.Zero();
  37564. return _this;
  37565. }
  37566. TargetCamera.prototype.getFrontPosition = function (distance) {
  37567. var direction = this.getTarget().subtract(this.position);
  37568. direction.normalize();
  37569. direction.scaleInPlace(distance);
  37570. return this.globalPosition.add(direction);
  37571. };
  37572. TargetCamera.prototype._getLockedTargetPosition = function () {
  37573. if (!this.lockedTarget) {
  37574. return null;
  37575. }
  37576. if (this.lockedTarget.absolutePosition) {
  37577. this.lockedTarget.computeWorldMatrix();
  37578. }
  37579. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37580. };
  37581. TargetCamera.prototype.storeState = function () {
  37582. this._storedPosition = this.position.clone();
  37583. this._storedRotation = this.rotation.clone();
  37584. if (this.rotationQuaternion) {
  37585. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37586. }
  37587. return _super.prototype.storeState.call(this);
  37588. };
  37589. /**
  37590. * Restored camera state. You must call storeState() first
  37591. */
  37592. TargetCamera.prototype._restoreStateValues = function () {
  37593. if (!_super.prototype._restoreStateValues.call(this)) {
  37594. return false;
  37595. }
  37596. this.position = this._storedPosition.clone();
  37597. this.rotation = this._storedRotation.clone();
  37598. if (this.rotationQuaternion) {
  37599. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37600. }
  37601. this.cameraDirection.copyFromFloats(0, 0, 0);
  37602. this.cameraRotation.copyFromFloats(0, 0);
  37603. return true;
  37604. };
  37605. // Cache
  37606. TargetCamera.prototype._initCache = function () {
  37607. _super.prototype._initCache.call(this);
  37608. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37609. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37610. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37611. };
  37612. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37613. if (!ignoreParentClass) {
  37614. _super.prototype._updateCache.call(this);
  37615. }
  37616. var lockedTargetPosition = this._getLockedTargetPosition();
  37617. if (!lockedTargetPosition) {
  37618. this._cache.lockedTarget = null;
  37619. }
  37620. else {
  37621. if (!this._cache.lockedTarget) {
  37622. this._cache.lockedTarget = lockedTargetPosition.clone();
  37623. }
  37624. else {
  37625. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37626. }
  37627. }
  37628. this._cache.rotation.copyFrom(this.rotation);
  37629. if (this.rotationQuaternion)
  37630. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37631. };
  37632. // Synchronized
  37633. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37634. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37635. return false;
  37636. }
  37637. var lockedTargetPosition = this._getLockedTargetPosition();
  37638. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37639. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37640. };
  37641. // Methods
  37642. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37643. var engine = this.getEngine();
  37644. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37645. };
  37646. // Target
  37647. TargetCamera.prototype.setTarget = function (target) {
  37648. this.upVector.normalize();
  37649. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37650. this._camMatrix.invert();
  37651. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37652. var vDir = target.subtract(this.position);
  37653. if (vDir.x >= 0.0) {
  37654. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37655. }
  37656. else {
  37657. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37658. }
  37659. this.rotation.z = 0;
  37660. if (isNaN(this.rotation.x)) {
  37661. this.rotation.x = 0;
  37662. }
  37663. if (isNaN(this.rotation.y)) {
  37664. this.rotation.y = 0;
  37665. }
  37666. if (isNaN(this.rotation.z)) {
  37667. this.rotation.z = 0;
  37668. }
  37669. if (this.rotationQuaternion) {
  37670. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37671. }
  37672. };
  37673. /**
  37674. * Return the current target position of the camera. This value is expressed in local space.
  37675. */
  37676. TargetCamera.prototype.getTarget = function () {
  37677. return this._currentTarget;
  37678. };
  37679. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37680. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37681. };
  37682. TargetCamera.prototype._updatePosition = function () {
  37683. if (this.parent) {
  37684. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37685. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37686. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37687. return;
  37688. }
  37689. this.position.addInPlace(this.cameraDirection);
  37690. };
  37691. TargetCamera.prototype._checkInputs = function () {
  37692. var needToMove = this._decideIfNeedsToMove();
  37693. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37694. // Move
  37695. if (needToMove) {
  37696. this._updatePosition();
  37697. }
  37698. // Rotate
  37699. if (needToRotate) {
  37700. this.rotation.x += this.cameraRotation.x;
  37701. this.rotation.y += this.cameraRotation.y;
  37702. //rotate, if quaternion is set and rotation was used
  37703. if (this.rotationQuaternion) {
  37704. var len = this.rotation.lengthSquared();
  37705. if (len) {
  37706. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37707. }
  37708. }
  37709. if (!this.noRotationConstraint) {
  37710. var limit = (Math.PI / 2) * 0.95;
  37711. if (this.rotation.x > limit)
  37712. this.rotation.x = limit;
  37713. if (this.rotation.x < -limit)
  37714. this.rotation.x = -limit;
  37715. }
  37716. }
  37717. // Inertia
  37718. if (needToMove) {
  37719. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37720. this.cameraDirection.x = 0;
  37721. }
  37722. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37723. this.cameraDirection.y = 0;
  37724. }
  37725. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37726. this.cameraDirection.z = 0;
  37727. }
  37728. this.cameraDirection.scaleInPlace(this.inertia);
  37729. }
  37730. if (needToRotate) {
  37731. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37732. this.cameraRotation.x = 0;
  37733. }
  37734. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37735. this.cameraRotation.y = 0;
  37736. }
  37737. this.cameraRotation.scaleInPlace(this.inertia);
  37738. }
  37739. _super.prototype._checkInputs.call(this);
  37740. };
  37741. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37742. if (this.rotationQuaternion) {
  37743. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37744. }
  37745. else {
  37746. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37747. }
  37748. //update the up vector!
  37749. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37750. };
  37751. TargetCamera.prototype._getViewMatrix = function () {
  37752. if (!this.lockedTarget) {
  37753. // Compute
  37754. this._updateCameraRotationMatrix();
  37755. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37756. // Computing target and final matrix
  37757. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37758. }
  37759. else {
  37760. var targetPosition = this._getLockedTargetPosition();
  37761. if (targetPosition) {
  37762. this._currentTarget.copyFrom(targetPosition);
  37763. }
  37764. }
  37765. if (this.getScene().useRightHandedSystem) {
  37766. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37767. }
  37768. else {
  37769. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37770. }
  37771. return this._viewMatrix;
  37772. };
  37773. /**
  37774. * @override
  37775. * Override Camera.createRigCamera
  37776. */
  37777. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37778. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37779. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37780. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37781. if (!this.rotationQuaternion) {
  37782. this.rotationQuaternion = new BABYLON.Quaternion();
  37783. }
  37784. rigCamera._cameraRigParams = {};
  37785. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37786. }
  37787. return rigCamera;
  37788. }
  37789. return null;
  37790. };
  37791. /**
  37792. * @override
  37793. * Override Camera._updateRigCameras
  37794. */
  37795. TargetCamera.prototype._updateRigCameras = function () {
  37796. var camLeft = this._rigCameras[0];
  37797. var camRight = this._rigCameras[1];
  37798. switch (this.cameraRigMode) {
  37799. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37800. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37801. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37802. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37803. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37804. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37805. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37806. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37807. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37808. camLeft.setTarget(this.getTarget());
  37809. camRight.setTarget(this.getTarget());
  37810. break;
  37811. case BABYLON.Camera.RIG_MODE_VR:
  37812. if (camLeft.rotationQuaternion) {
  37813. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37814. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37815. }
  37816. else {
  37817. camLeft.rotation.copyFrom(this.rotation);
  37818. camRight.rotation.copyFrom(this.rotation);
  37819. }
  37820. camLeft.position.copyFrom(this.position);
  37821. camRight.position.copyFrom(this.position);
  37822. break;
  37823. }
  37824. _super.prototype._updateRigCameras.call(this);
  37825. };
  37826. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37827. if (!this._rigCamTransformMatrix) {
  37828. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37829. }
  37830. var target = this.getTarget();
  37831. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37832. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37833. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37834. };
  37835. TargetCamera.prototype.getClassName = function () {
  37836. return "TargetCamera";
  37837. };
  37838. __decorate([
  37839. BABYLON.serializeAsVector3()
  37840. ], TargetCamera.prototype, "rotation", void 0);
  37841. __decorate([
  37842. BABYLON.serialize()
  37843. ], TargetCamera.prototype, "speed", void 0);
  37844. __decorate([
  37845. BABYLON.serializeAsMeshReference("lockedTargetId")
  37846. ], TargetCamera.prototype, "lockedTarget", void 0);
  37847. return TargetCamera;
  37848. }(BABYLON.Camera));
  37849. BABYLON.TargetCamera = TargetCamera;
  37850. })(BABYLON || (BABYLON = {}));
  37851. //# sourceMappingURL=babylon.targetCamera.js.map
  37852. var BABYLON;
  37853. (function (BABYLON) {
  37854. var FreeCamera = /** @class */ (function (_super) {
  37855. __extends(FreeCamera, _super);
  37856. function FreeCamera(name, position, scene) {
  37857. var _this = _super.call(this, name, position, scene) || this;
  37858. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37859. _this.checkCollisions = false;
  37860. _this.applyGravity = false;
  37861. _this._needMoveForGravity = false;
  37862. _this._oldPosition = BABYLON.Vector3.Zero();
  37863. _this._diffPosition = BABYLON.Vector3.Zero();
  37864. _this._newPosition = BABYLON.Vector3.Zero();
  37865. // Collisions
  37866. _this._collisionMask = -1;
  37867. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37868. if (collidedMesh === void 0) { collidedMesh = null; }
  37869. //TODO move this to the collision coordinator!
  37870. if (_this.getScene().workerCollisions)
  37871. newPosition.multiplyInPlace(_this._collider.radius);
  37872. var updatePosition = function (newPos) {
  37873. _this._newPosition.copyFrom(newPos);
  37874. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37875. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37876. _this.position.addInPlace(_this._diffPosition);
  37877. if (_this.onCollide && collidedMesh) {
  37878. _this.onCollide(collidedMesh);
  37879. }
  37880. }
  37881. };
  37882. updatePosition(newPosition);
  37883. };
  37884. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37885. _this.inputs.addKeyboard().addMouse();
  37886. return _this;
  37887. }
  37888. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37889. //-- begin properties for backward compatibility for inputs
  37890. get: function () {
  37891. var mouse = this.inputs.attached["mouse"];
  37892. if (mouse)
  37893. return mouse.angularSensibility;
  37894. return 0;
  37895. },
  37896. set: function (value) {
  37897. var mouse = this.inputs.attached["mouse"];
  37898. if (mouse)
  37899. mouse.angularSensibility = value;
  37900. },
  37901. enumerable: true,
  37902. configurable: true
  37903. });
  37904. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37905. get: function () {
  37906. var keyboard = this.inputs.attached["keyboard"];
  37907. if (keyboard)
  37908. return keyboard.keysUp;
  37909. return [];
  37910. },
  37911. set: function (value) {
  37912. var keyboard = this.inputs.attached["keyboard"];
  37913. if (keyboard)
  37914. keyboard.keysUp = value;
  37915. },
  37916. enumerable: true,
  37917. configurable: true
  37918. });
  37919. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37920. get: function () {
  37921. var keyboard = this.inputs.attached["keyboard"];
  37922. if (keyboard)
  37923. return keyboard.keysDown;
  37924. return [];
  37925. },
  37926. set: function (value) {
  37927. var keyboard = this.inputs.attached["keyboard"];
  37928. if (keyboard)
  37929. keyboard.keysDown = value;
  37930. },
  37931. enumerable: true,
  37932. configurable: true
  37933. });
  37934. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37935. get: function () {
  37936. var keyboard = this.inputs.attached["keyboard"];
  37937. if (keyboard)
  37938. return keyboard.keysLeft;
  37939. return [];
  37940. },
  37941. set: function (value) {
  37942. var keyboard = this.inputs.attached["keyboard"];
  37943. if (keyboard)
  37944. keyboard.keysLeft = value;
  37945. },
  37946. enumerable: true,
  37947. configurable: true
  37948. });
  37949. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37950. get: function () {
  37951. var keyboard = this.inputs.attached["keyboard"];
  37952. if (keyboard)
  37953. return keyboard.keysRight;
  37954. return [];
  37955. },
  37956. set: function (value) {
  37957. var keyboard = this.inputs.attached["keyboard"];
  37958. if (keyboard)
  37959. keyboard.keysRight = value;
  37960. },
  37961. enumerable: true,
  37962. configurable: true
  37963. });
  37964. // Controls
  37965. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37966. this.inputs.attachElement(element, noPreventDefault);
  37967. };
  37968. FreeCamera.prototype.detachControl = function (element) {
  37969. this.inputs.detachElement(element);
  37970. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37971. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37972. };
  37973. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37974. get: function () {
  37975. return this._collisionMask;
  37976. },
  37977. set: function (mask) {
  37978. this._collisionMask = !isNaN(mask) ? mask : -1;
  37979. },
  37980. enumerable: true,
  37981. configurable: true
  37982. });
  37983. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37984. var globalPosition;
  37985. if (this.parent) {
  37986. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37987. }
  37988. else {
  37989. globalPosition = this.position;
  37990. }
  37991. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37992. if (!this._collider) {
  37993. this._collider = new BABYLON.Collider();
  37994. }
  37995. this._collider.radius = this.ellipsoid;
  37996. this._collider.collisionMask = this._collisionMask;
  37997. //no need for clone, as long as gravity is not on.
  37998. var actualDisplacement = displacement;
  37999. //add gravity to the direction to prevent the dual-collision checking
  38000. if (this.applyGravity) {
  38001. //this prevents mending with cameraDirection, a global variable of the free camera class.
  38002. actualDisplacement = displacement.add(this.getScene().gravity);
  38003. }
  38004. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38005. };
  38006. FreeCamera.prototype._checkInputs = function () {
  38007. if (!this._localDirection) {
  38008. this._localDirection = BABYLON.Vector3.Zero();
  38009. this._transformedDirection = BABYLON.Vector3.Zero();
  38010. }
  38011. this.inputs.checkInputs();
  38012. _super.prototype._checkInputs.call(this);
  38013. };
  38014. FreeCamera.prototype._decideIfNeedsToMove = function () {
  38015. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38016. };
  38017. FreeCamera.prototype._updatePosition = function () {
  38018. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  38019. this._collideWithWorld(this.cameraDirection);
  38020. }
  38021. else {
  38022. _super.prototype._updatePosition.call(this);
  38023. }
  38024. };
  38025. FreeCamera.prototype.dispose = function () {
  38026. this.inputs.clear();
  38027. _super.prototype.dispose.call(this);
  38028. };
  38029. FreeCamera.prototype.getClassName = function () {
  38030. return "FreeCamera";
  38031. };
  38032. __decorate([
  38033. BABYLON.serializeAsVector3()
  38034. ], FreeCamera.prototype, "ellipsoid", void 0);
  38035. __decorate([
  38036. BABYLON.serialize()
  38037. ], FreeCamera.prototype, "checkCollisions", void 0);
  38038. __decorate([
  38039. BABYLON.serialize()
  38040. ], FreeCamera.prototype, "applyGravity", void 0);
  38041. return FreeCamera;
  38042. }(BABYLON.TargetCamera));
  38043. BABYLON.FreeCamera = FreeCamera;
  38044. })(BABYLON || (BABYLON = {}));
  38045. //# sourceMappingURL=babylon.freeCamera.js.map
  38046. var BABYLON;
  38047. (function (BABYLON) {
  38048. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  38049. function ArcRotateCameraKeyboardMoveInput() {
  38050. this._keys = new Array();
  38051. this.keysUp = [38];
  38052. this.keysDown = [40];
  38053. this.keysLeft = [37];
  38054. this.keysRight = [39];
  38055. this.keysReset = [220];
  38056. this.panningSensibility = 50.0;
  38057. this.zoomingSensibility = 25.0;
  38058. this.useAltToZoom = true;
  38059. }
  38060. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38061. var _this = this;
  38062. if (this._onCanvasBlurObserver) {
  38063. return;
  38064. }
  38065. this._scene = this.camera.getScene();
  38066. this._engine = this._scene.getEngine();
  38067. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38068. _this._keys = [];
  38069. });
  38070. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38071. var evt = info.event;
  38072. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38073. _this._ctrlPressed = evt.ctrlKey;
  38074. _this._altPressed = evt.altKey;
  38075. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38076. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38077. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38078. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38079. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38080. var index = _this._keys.indexOf(evt.keyCode);
  38081. if (index === -1) {
  38082. _this._keys.push(evt.keyCode);
  38083. }
  38084. if (evt.preventDefault) {
  38085. if (!noPreventDefault) {
  38086. evt.preventDefault();
  38087. }
  38088. }
  38089. }
  38090. }
  38091. else {
  38092. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38093. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38094. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38095. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38096. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38097. var index = _this._keys.indexOf(evt.keyCode);
  38098. if (index >= 0) {
  38099. _this._keys.splice(index, 1);
  38100. }
  38101. if (evt.preventDefault) {
  38102. if (!noPreventDefault) {
  38103. evt.preventDefault();
  38104. }
  38105. }
  38106. }
  38107. }
  38108. });
  38109. };
  38110. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38111. if (this._scene) {
  38112. if (this._onKeyboardObserver) {
  38113. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38114. }
  38115. if (this._onCanvasBlurObserver) {
  38116. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38117. }
  38118. this._onKeyboardObserver = null;
  38119. this._onCanvasBlurObserver = null;
  38120. }
  38121. this._keys = [];
  38122. };
  38123. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38124. if (this._onKeyboardObserver) {
  38125. var camera = this.camera;
  38126. for (var index = 0; index < this._keys.length; index++) {
  38127. var keyCode = this._keys[index];
  38128. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38129. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38130. camera.inertialPanningX -= 1 / this.panningSensibility;
  38131. }
  38132. else {
  38133. camera.inertialAlphaOffset -= 0.01;
  38134. }
  38135. }
  38136. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38137. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38138. camera.inertialPanningY += 1 / this.panningSensibility;
  38139. }
  38140. else if (this._altPressed && this.useAltToZoom) {
  38141. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  38142. }
  38143. else {
  38144. camera.inertialBetaOffset -= 0.01;
  38145. }
  38146. }
  38147. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38148. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38149. camera.inertialPanningX += 1 / this.panningSensibility;
  38150. }
  38151. else {
  38152. camera.inertialAlphaOffset += 0.01;
  38153. }
  38154. }
  38155. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38156. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38157. camera.inertialPanningY -= 1 / this.panningSensibility;
  38158. }
  38159. else if (this._altPressed && this.useAltToZoom) {
  38160. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  38161. }
  38162. else {
  38163. camera.inertialBetaOffset += 0.01;
  38164. }
  38165. }
  38166. else if (this.keysReset.indexOf(keyCode) !== -1) {
  38167. camera.restoreState();
  38168. }
  38169. }
  38170. }
  38171. };
  38172. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  38173. return "ArcRotateCameraKeyboardMoveInput";
  38174. };
  38175. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38176. return "keyboard";
  38177. };
  38178. __decorate([
  38179. BABYLON.serialize()
  38180. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38181. __decorate([
  38182. BABYLON.serialize()
  38183. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38184. __decorate([
  38185. BABYLON.serialize()
  38186. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38187. __decorate([
  38188. BABYLON.serialize()
  38189. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38190. __decorate([
  38191. BABYLON.serialize()
  38192. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38193. __decorate([
  38194. BABYLON.serialize()
  38195. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38196. __decorate([
  38197. BABYLON.serialize()
  38198. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38199. __decorate([
  38200. BABYLON.serialize()
  38201. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38202. return ArcRotateCameraKeyboardMoveInput;
  38203. }());
  38204. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38205. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38206. })(BABYLON || (BABYLON = {}));
  38207. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38208. var BABYLON;
  38209. (function (BABYLON) {
  38210. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38211. function ArcRotateCameraMouseWheelInput() {
  38212. this.wheelPrecision = 3.0;
  38213. /**
  38214. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38215. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38216. */
  38217. this.wheelDeltaPercentage = 0;
  38218. }
  38219. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38220. var _this = this;
  38221. this._wheel = function (p, s) {
  38222. //sanity check - this should be a PointerWheel event.
  38223. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38224. return;
  38225. var event = p.event;
  38226. var delta = 0;
  38227. if (event.wheelDelta) {
  38228. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38229. }
  38230. else if (event.detail) {
  38231. delta = -event.detail / _this.wheelPrecision;
  38232. }
  38233. if (delta)
  38234. _this.camera.inertialRadiusOffset += delta;
  38235. if (event.preventDefault) {
  38236. if (!noPreventDefault) {
  38237. event.preventDefault();
  38238. }
  38239. }
  38240. };
  38241. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38242. };
  38243. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38244. if (this._observer && element) {
  38245. this.camera.getScene().onPointerObservable.remove(this._observer);
  38246. this._observer = null;
  38247. this._wheel = null;
  38248. }
  38249. };
  38250. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38251. return "ArcRotateCameraMouseWheelInput";
  38252. };
  38253. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38254. return "mousewheel";
  38255. };
  38256. __decorate([
  38257. BABYLON.serialize()
  38258. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38259. __decorate([
  38260. BABYLON.serialize()
  38261. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38262. return ArcRotateCameraMouseWheelInput;
  38263. }());
  38264. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38265. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38266. })(BABYLON || (BABYLON = {}));
  38267. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38268. var BABYLON;
  38269. (function (BABYLON) {
  38270. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38271. function ArcRotateCameraPointersInput() {
  38272. this.buttons = [0, 1, 2];
  38273. this.angularSensibilityX = 1000.0;
  38274. this.angularSensibilityY = 1000.0;
  38275. this.pinchPrecision = 12.0;
  38276. /**
  38277. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38278. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38279. */
  38280. this.pinchDeltaPercentage = 0;
  38281. this.panningSensibility = 1000.0;
  38282. this.multiTouchPanning = true;
  38283. this.multiTouchPanAndZoom = true;
  38284. this._isPanClick = false;
  38285. this.pinchInwards = true;
  38286. }
  38287. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38288. var _this = this;
  38289. var engine = this.camera.getEngine();
  38290. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38291. var pointA = null;
  38292. var pointB = null;
  38293. var previousPinchSquaredDistance = 0;
  38294. var initialDistance = 0;
  38295. var twoFingerActivityCount = 0;
  38296. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38297. this._pointerInput = function (p, s) {
  38298. var evt = p.event;
  38299. var isTouch = p.event.pointerType === "touch";
  38300. if (engine.isInVRExclusivePointerMode) {
  38301. return;
  38302. }
  38303. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38304. return;
  38305. }
  38306. var srcElement = (evt.srcElement || evt.target);
  38307. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38308. try {
  38309. srcElement.setPointerCapture(evt.pointerId);
  38310. }
  38311. catch (e) {
  38312. //Nothing to do with the error. Execution will continue.
  38313. }
  38314. // Manage panning with pan button click
  38315. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38316. // manage pointers
  38317. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38318. if (pointA === null) {
  38319. pointA = cacheSoloPointer;
  38320. }
  38321. else if (pointB === null) {
  38322. pointB = cacheSoloPointer;
  38323. }
  38324. if (!noPreventDefault) {
  38325. evt.preventDefault();
  38326. element.focus();
  38327. }
  38328. }
  38329. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38330. _this.camera.restoreState();
  38331. }
  38332. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38333. try {
  38334. srcElement.releasePointerCapture(evt.pointerId);
  38335. }
  38336. catch (e) {
  38337. //Nothing to do with the error.
  38338. }
  38339. cacheSoloPointer = null;
  38340. previousPinchSquaredDistance = 0;
  38341. previousMultiTouchPanPosition.isPaning = false;
  38342. previousMultiTouchPanPosition.isPinching = false;
  38343. twoFingerActivityCount = 0;
  38344. initialDistance = 0;
  38345. if (!isTouch) {
  38346. pointB = null; // Mouse and pen are mono pointer
  38347. }
  38348. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38349. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38350. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38351. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38352. if (engine.badOS) {
  38353. pointA = pointB = null;
  38354. }
  38355. else {
  38356. //only remove the impacted pointer in case of multitouch allowing on most
  38357. //platforms switching from rotate to zoom and pan seamlessly.
  38358. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38359. pointA = pointB;
  38360. pointB = null;
  38361. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38362. }
  38363. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38364. pointB = null;
  38365. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38366. }
  38367. else {
  38368. pointA = pointB = null;
  38369. }
  38370. }
  38371. if (!noPreventDefault) {
  38372. evt.preventDefault();
  38373. }
  38374. }
  38375. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38376. if (!noPreventDefault) {
  38377. evt.preventDefault();
  38378. }
  38379. // One button down
  38380. if (pointA && pointB === null && cacheSoloPointer) {
  38381. if (_this.panningSensibility !== 0 &&
  38382. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38383. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38384. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38385. }
  38386. else {
  38387. var offsetX = evt.clientX - cacheSoloPointer.x;
  38388. var offsetY = evt.clientY - cacheSoloPointer.y;
  38389. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38390. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38391. }
  38392. cacheSoloPointer.x = evt.clientX;
  38393. cacheSoloPointer.y = evt.clientY;
  38394. }
  38395. else if (pointA && pointB) {
  38396. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38397. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38398. ed.x = evt.clientX;
  38399. ed.y = evt.clientY;
  38400. var direction = _this.pinchInwards ? 1 : -1;
  38401. var distX = pointA.x - pointB.x;
  38402. var distY = pointA.y - pointB.y;
  38403. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38404. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38405. if (previousPinchSquaredDistance === 0) {
  38406. initialDistance = pinchDistance;
  38407. previousPinchSquaredDistance = pinchSquaredDistance;
  38408. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38409. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38410. return;
  38411. }
  38412. if (_this.multiTouchPanAndZoom) {
  38413. if (_this.pinchDeltaPercentage) {
  38414. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38415. }
  38416. else {
  38417. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38418. (_this.pinchPrecision *
  38419. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38420. direction);
  38421. }
  38422. if (_this.panningSensibility !== 0) {
  38423. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38424. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38425. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38426. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38427. previousMultiTouchPanPosition.x = pointersCenterX;
  38428. previousMultiTouchPanPosition.y = pointersCenterY;
  38429. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38430. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38431. }
  38432. }
  38433. else {
  38434. twoFingerActivityCount++;
  38435. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38436. if (_this.pinchDeltaPercentage) {
  38437. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38438. }
  38439. else {
  38440. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38441. (_this.pinchPrecision *
  38442. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38443. direction);
  38444. }
  38445. previousMultiTouchPanPosition.isPaning = false;
  38446. previousMultiTouchPanPosition.isPinching = true;
  38447. }
  38448. else {
  38449. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38450. if (!previousMultiTouchPanPosition.isPaning) {
  38451. previousMultiTouchPanPosition.isPaning = true;
  38452. previousMultiTouchPanPosition.isPinching = false;
  38453. previousMultiTouchPanPosition.x = ed.x;
  38454. previousMultiTouchPanPosition.y = ed.y;
  38455. return;
  38456. }
  38457. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38458. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38459. }
  38460. }
  38461. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38462. previousMultiTouchPanPosition.x = ed.x;
  38463. previousMultiTouchPanPosition.y = ed.y;
  38464. }
  38465. }
  38466. previousPinchSquaredDistance = pinchSquaredDistance;
  38467. }
  38468. }
  38469. };
  38470. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38471. this._onContextMenu = function (evt) {
  38472. evt.preventDefault();
  38473. };
  38474. if (!this.camera._useCtrlForPanning) {
  38475. element.addEventListener("contextmenu", this._onContextMenu, false);
  38476. }
  38477. this._onLostFocus = function () {
  38478. //this._keys = [];
  38479. pointA = pointB = null;
  38480. previousPinchSquaredDistance = 0;
  38481. previousMultiTouchPanPosition.isPaning = false;
  38482. previousMultiTouchPanPosition.isPinching = false;
  38483. twoFingerActivityCount = 0;
  38484. cacheSoloPointer = null;
  38485. initialDistance = 0;
  38486. };
  38487. this._onMouseMove = function (evt) {
  38488. if (!engine.isPointerLock) {
  38489. return;
  38490. }
  38491. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38492. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38493. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38494. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38495. if (!noPreventDefault) {
  38496. evt.preventDefault();
  38497. }
  38498. };
  38499. this._onGestureStart = function (e) {
  38500. if (window.MSGesture === undefined) {
  38501. return;
  38502. }
  38503. if (!_this._MSGestureHandler) {
  38504. _this._MSGestureHandler = new MSGesture();
  38505. _this._MSGestureHandler.target = element;
  38506. }
  38507. _this._MSGestureHandler.addPointer(e.pointerId);
  38508. };
  38509. this._onGesture = function (e) {
  38510. _this.camera.radius *= e.scale;
  38511. if (e.preventDefault) {
  38512. if (!noPreventDefault) {
  38513. e.stopPropagation();
  38514. e.preventDefault();
  38515. }
  38516. }
  38517. };
  38518. element.addEventListener("mousemove", this._onMouseMove, false);
  38519. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38520. element.addEventListener("MSGestureChange", this._onGesture, false);
  38521. BABYLON.Tools.RegisterTopRootEvents([
  38522. { name: "blur", handler: this._onLostFocus }
  38523. ]);
  38524. };
  38525. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38526. if (this._onLostFocus) {
  38527. BABYLON.Tools.UnregisterTopRootEvents([
  38528. { name: "blur", handler: this._onLostFocus }
  38529. ]);
  38530. }
  38531. if (element && this._observer) {
  38532. this.camera.getScene().onPointerObservable.remove(this._observer);
  38533. this._observer = null;
  38534. if (this._onContextMenu) {
  38535. element.removeEventListener("contextmenu", this._onContextMenu);
  38536. }
  38537. if (this._onMouseMove) {
  38538. element.removeEventListener("mousemove", this._onMouseMove);
  38539. }
  38540. if (this._onGestureStart) {
  38541. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38542. }
  38543. if (this._onGesture) {
  38544. element.removeEventListener("MSGestureChange", this._onGesture);
  38545. }
  38546. this._isPanClick = false;
  38547. this.pinchInwards = true;
  38548. this._onMouseMove = null;
  38549. this._onGestureStart = null;
  38550. this._onGesture = null;
  38551. this._MSGestureHandler = null;
  38552. this._onLostFocus = null;
  38553. this._onContextMenu = null;
  38554. }
  38555. };
  38556. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38557. return "ArcRotateCameraPointersInput";
  38558. };
  38559. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38560. return "pointers";
  38561. };
  38562. __decorate([
  38563. BABYLON.serialize()
  38564. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38565. __decorate([
  38566. BABYLON.serialize()
  38567. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38568. __decorate([
  38569. BABYLON.serialize()
  38570. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38571. __decorate([
  38572. BABYLON.serialize()
  38573. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38574. __decorate([
  38575. BABYLON.serialize()
  38576. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38577. __decorate([
  38578. BABYLON.serialize()
  38579. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38580. __decorate([
  38581. BABYLON.serialize()
  38582. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38583. __decorate([
  38584. BABYLON.serialize()
  38585. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38586. return ArcRotateCameraPointersInput;
  38587. }());
  38588. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38589. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38590. })(BABYLON || (BABYLON = {}));
  38591. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38592. var BABYLON;
  38593. (function (BABYLON) {
  38594. var ArcRotateCamera = /** @class */ (function (_super) {
  38595. __extends(ArcRotateCamera, _super);
  38596. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38597. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38598. _this.inertialAlphaOffset = 0;
  38599. _this.inertialBetaOffset = 0;
  38600. _this.inertialRadiusOffset = 0;
  38601. _this.lowerAlphaLimit = null;
  38602. _this.upperAlphaLimit = null;
  38603. _this.lowerBetaLimit = 0.01;
  38604. _this.upperBetaLimit = Math.PI;
  38605. _this.lowerRadiusLimit = null;
  38606. _this.upperRadiusLimit = null;
  38607. _this.inertialPanningX = 0;
  38608. _this.inertialPanningY = 0;
  38609. _this.pinchToPanMaxDistance = 20;
  38610. _this.panningDistanceLimit = null;
  38611. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38612. _this.panningInertia = 0.9;
  38613. //-- end properties for backward compatibility for inputs
  38614. _this.zoomOnFactor = 1;
  38615. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38616. _this.allowUpsideDown = true;
  38617. _this._viewMatrix = new BABYLON.Matrix();
  38618. // Panning
  38619. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38620. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38621. _this.checkCollisions = false;
  38622. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38623. _this._previousPosition = BABYLON.Vector3.Zero();
  38624. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38625. _this._newPosition = BABYLON.Vector3.Zero();
  38626. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38627. if (collidedMesh === void 0) { collidedMesh = null; }
  38628. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38629. newPosition.multiplyInPlace(_this._collider.radius);
  38630. }
  38631. if (!collidedMesh) {
  38632. _this._previousPosition.copyFrom(_this.position);
  38633. }
  38634. else {
  38635. _this.setPosition(newPosition);
  38636. if (_this.onCollide) {
  38637. _this.onCollide(collidedMesh);
  38638. }
  38639. }
  38640. // Recompute because of constraints
  38641. var cosa = Math.cos(_this.alpha);
  38642. var sina = Math.sin(_this.alpha);
  38643. var cosb = Math.cos(_this.beta);
  38644. var sinb = Math.sin(_this.beta);
  38645. if (sinb === 0) {
  38646. sinb = 0.0001;
  38647. }
  38648. var target = _this._getTargetPosition();
  38649. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38650. _this.position.copyFrom(_this._newPosition);
  38651. var up = _this.upVector;
  38652. if (_this.allowUpsideDown && _this.beta < 0) {
  38653. up = up.clone();
  38654. up = up.negate();
  38655. }
  38656. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38657. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38658. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38659. _this._collisionTriggered = false;
  38660. };
  38661. _this._target = BABYLON.Vector3.Zero();
  38662. if (target) {
  38663. _this.setTarget(target);
  38664. }
  38665. _this.alpha = alpha;
  38666. _this.beta = beta;
  38667. _this.radius = radius;
  38668. _this.getViewMatrix();
  38669. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38670. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38671. return _this;
  38672. }
  38673. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38674. get: function () {
  38675. return this._target;
  38676. },
  38677. set: function (value) {
  38678. this.setTarget(value);
  38679. },
  38680. enumerable: true,
  38681. configurable: true
  38682. });
  38683. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38684. //-- begin properties for backward compatibility for inputs
  38685. get: function () {
  38686. var pointers = this.inputs.attached["pointers"];
  38687. if (pointers)
  38688. return pointers.angularSensibilityX;
  38689. return 0;
  38690. },
  38691. set: function (value) {
  38692. var pointers = this.inputs.attached["pointers"];
  38693. if (pointers) {
  38694. pointers.angularSensibilityX = value;
  38695. }
  38696. },
  38697. enumerable: true,
  38698. configurable: true
  38699. });
  38700. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38701. get: function () {
  38702. var pointers = this.inputs.attached["pointers"];
  38703. if (pointers)
  38704. return pointers.angularSensibilityY;
  38705. return 0;
  38706. },
  38707. set: function (value) {
  38708. var pointers = this.inputs.attached["pointers"];
  38709. if (pointers) {
  38710. pointers.angularSensibilityY = value;
  38711. }
  38712. },
  38713. enumerable: true,
  38714. configurable: true
  38715. });
  38716. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38717. get: function () {
  38718. var pointers = this.inputs.attached["pointers"];
  38719. if (pointers)
  38720. return pointers.pinchPrecision;
  38721. return 0;
  38722. },
  38723. set: function (value) {
  38724. var pointers = this.inputs.attached["pointers"];
  38725. if (pointers) {
  38726. pointers.pinchPrecision = value;
  38727. }
  38728. },
  38729. enumerable: true,
  38730. configurable: true
  38731. });
  38732. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38733. get: function () {
  38734. var pointers = this.inputs.attached["pointers"];
  38735. if (pointers)
  38736. return pointers.pinchDeltaPercentage;
  38737. return 0;
  38738. },
  38739. set: function (value) {
  38740. var pointers = this.inputs.attached["pointers"];
  38741. if (pointers) {
  38742. pointers.pinchDeltaPercentage = value;
  38743. }
  38744. },
  38745. enumerable: true,
  38746. configurable: true
  38747. });
  38748. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38749. get: function () {
  38750. var pointers = this.inputs.attached["pointers"];
  38751. if (pointers)
  38752. return pointers.panningSensibility;
  38753. return 0;
  38754. },
  38755. set: function (value) {
  38756. var pointers = this.inputs.attached["pointers"];
  38757. if (pointers) {
  38758. pointers.panningSensibility = value;
  38759. }
  38760. },
  38761. enumerable: true,
  38762. configurable: true
  38763. });
  38764. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38765. get: function () {
  38766. var keyboard = this.inputs.attached["keyboard"];
  38767. if (keyboard)
  38768. return keyboard.keysUp;
  38769. return [];
  38770. },
  38771. set: function (value) {
  38772. var keyboard = this.inputs.attached["keyboard"];
  38773. if (keyboard)
  38774. keyboard.keysUp = value;
  38775. },
  38776. enumerable: true,
  38777. configurable: true
  38778. });
  38779. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38780. get: function () {
  38781. var keyboard = this.inputs.attached["keyboard"];
  38782. if (keyboard)
  38783. return keyboard.keysDown;
  38784. return [];
  38785. },
  38786. set: function (value) {
  38787. var keyboard = this.inputs.attached["keyboard"];
  38788. if (keyboard)
  38789. keyboard.keysDown = value;
  38790. },
  38791. enumerable: true,
  38792. configurable: true
  38793. });
  38794. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38795. get: function () {
  38796. var keyboard = this.inputs.attached["keyboard"];
  38797. if (keyboard)
  38798. return keyboard.keysLeft;
  38799. return [];
  38800. },
  38801. set: function (value) {
  38802. var keyboard = this.inputs.attached["keyboard"];
  38803. if (keyboard)
  38804. keyboard.keysLeft = value;
  38805. },
  38806. enumerable: true,
  38807. configurable: true
  38808. });
  38809. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38810. get: function () {
  38811. var keyboard = this.inputs.attached["keyboard"];
  38812. if (keyboard)
  38813. return keyboard.keysRight;
  38814. return [];
  38815. },
  38816. set: function (value) {
  38817. var keyboard = this.inputs.attached["keyboard"];
  38818. if (keyboard)
  38819. keyboard.keysRight = value;
  38820. },
  38821. enumerable: true,
  38822. configurable: true
  38823. });
  38824. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38825. get: function () {
  38826. var mousewheel = this.inputs.attached["mousewheel"];
  38827. if (mousewheel)
  38828. return mousewheel.wheelPrecision;
  38829. return 0;
  38830. },
  38831. set: function (value) {
  38832. var mousewheel = this.inputs.attached["mousewheel"];
  38833. if (mousewheel)
  38834. mousewheel.wheelPrecision = value;
  38835. },
  38836. enumerable: true,
  38837. configurable: true
  38838. });
  38839. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38840. get: function () {
  38841. var mousewheel = this.inputs.attached["mousewheel"];
  38842. if (mousewheel)
  38843. return mousewheel.wheelDeltaPercentage;
  38844. return 0;
  38845. },
  38846. set: function (value) {
  38847. var mousewheel = this.inputs.attached["mousewheel"];
  38848. if (mousewheel)
  38849. mousewheel.wheelDeltaPercentage = value;
  38850. },
  38851. enumerable: true,
  38852. configurable: true
  38853. });
  38854. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38855. get: function () {
  38856. return this._bouncingBehavior;
  38857. },
  38858. enumerable: true,
  38859. configurable: true
  38860. });
  38861. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38862. get: function () {
  38863. return this._bouncingBehavior != null;
  38864. },
  38865. set: function (value) {
  38866. if (value === this.useBouncingBehavior) {
  38867. return;
  38868. }
  38869. if (value) {
  38870. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38871. this.addBehavior(this._bouncingBehavior);
  38872. }
  38873. else if (this._bouncingBehavior) {
  38874. this.removeBehavior(this._bouncingBehavior);
  38875. this._bouncingBehavior = null;
  38876. }
  38877. },
  38878. enumerable: true,
  38879. configurable: true
  38880. });
  38881. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38882. get: function () {
  38883. return this._framingBehavior;
  38884. },
  38885. enumerable: true,
  38886. configurable: true
  38887. });
  38888. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38889. get: function () {
  38890. return this._framingBehavior != null;
  38891. },
  38892. set: function (value) {
  38893. if (value === this.useFramingBehavior) {
  38894. return;
  38895. }
  38896. if (value) {
  38897. this._framingBehavior = new BABYLON.FramingBehavior();
  38898. this.addBehavior(this._framingBehavior);
  38899. }
  38900. else if (this._framingBehavior) {
  38901. this.removeBehavior(this._framingBehavior);
  38902. this._framingBehavior = null;
  38903. }
  38904. },
  38905. enumerable: true,
  38906. configurable: true
  38907. });
  38908. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38909. get: function () {
  38910. return this._autoRotationBehavior;
  38911. },
  38912. enumerable: true,
  38913. configurable: true
  38914. });
  38915. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38916. get: function () {
  38917. return this._autoRotationBehavior != null;
  38918. },
  38919. set: function (value) {
  38920. if (value === this.useAutoRotationBehavior) {
  38921. return;
  38922. }
  38923. if (value) {
  38924. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38925. this.addBehavior(this._autoRotationBehavior);
  38926. }
  38927. else if (this._autoRotationBehavior) {
  38928. this.removeBehavior(this._autoRotationBehavior);
  38929. this._autoRotationBehavior = null;
  38930. }
  38931. },
  38932. enumerable: true,
  38933. configurable: true
  38934. });
  38935. // Cache
  38936. ArcRotateCamera.prototype._initCache = function () {
  38937. _super.prototype._initCache.call(this);
  38938. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38939. this._cache.alpha = undefined;
  38940. this._cache.beta = undefined;
  38941. this._cache.radius = undefined;
  38942. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38943. };
  38944. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38945. if (!ignoreParentClass) {
  38946. _super.prototype._updateCache.call(this);
  38947. }
  38948. this._cache._target.copyFrom(this._getTargetPosition());
  38949. this._cache.alpha = this.alpha;
  38950. this._cache.beta = this.beta;
  38951. this._cache.radius = this.radius;
  38952. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38953. };
  38954. ArcRotateCamera.prototype._getTargetPosition = function () {
  38955. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38956. var pos = this._targetHost.getAbsolutePosition();
  38957. if (this._targetBoundingCenter) {
  38958. pos.addToRef(this._targetBoundingCenter, this._target);
  38959. }
  38960. else {
  38961. this._target.copyFrom(pos);
  38962. }
  38963. }
  38964. var lockedTargetPosition = this._getLockedTargetPosition();
  38965. if (lockedTargetPosition) {
  38966. return lockedTargetPosition;
  38967. }
  38968. return this._target;
  38969. };
  38970. ArcRotateCamera.prototype.storeState = function () {
  38971. this._storedAlpha = this.alpha;
  38972. this._storedBeta = this.beta;
  38973. this._storedRadius = this.radius;
  38974. this._storedTarget = this._getTargetPosition().clone();
  38975. return _super.prototype.storeState.call(this);
  38976. };
  38977. /**
  38978. * Restored camera state. You must call storeState() first
  38979. */
  38980. ArcRotateCamera.prototype._restoreStateValues = function () {
  38981. if (!_super.prototype._restoreStateValues.call(this)) {
  38982. return false;
  38983. }
  38984. this.alpha = this._storedAlpha;
  38985. this.beta = this._storedBeta;
  38986. this.radius = this._storedRadius;
  38987. this.setTarget(this._storedTarget.clone());
  38988. this.inertialAlphaOffset = 0;
  38989. this.inertialBetaOffset = 0;
  38990. this.inertialRadiusOffset = 0;
  38991. this.inertialPanningX = 0;
  38992. this.inertialPanningY = 0;
  38993. return true;
  38994. };
  38995. // Synchronized
  38996. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38997. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38998. return false;
  38999. return this._cache._target.equals(this._getTargetPosition())
  39000. && this._cache.alpha === this.alpha
  39001. && this._cache.beta === this.beta
  39002. && this._cache.radius === this.radius
  39003. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  39004. };
  39005. // Methods
  39006. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  39007. var _this = this;
  39008. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  39009. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  39010. this._useCtrlForPanning = useCtrlForPanning;
  39011. this._panningMouseButton = panningMouseButton;
  39012. this.inputs.attachElement(element, noPreventDefault);
  39013. this._reset = function () {
  39014. _this.inertialAlphaOffset = 0;
  39015. _this.inertialBetaOffset = 0;
  39016. _this.inertialRadiusOffset = 0;
  39017. _this.inertialPanningX = 0;
  39018. _this.inertialPanningY = 0;
  39019. };
  39020. };
  39021. ArcRotateCamera.prototype.detachControl = function (element) {
  39022. this.inputs.detachElement(element);
  39023. if (this._reset) {
  39024. this._reset();
  39025. }
  39026. };
  39027. ArcRotateCamera.prototype._checkInputs = function () {
  39028. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  39029. if (this._collisionTriggered) {
  39030. return;
  39031. }
  39032. this.inputs.checkInputs();
  39033. // Inertia
  39034. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  39035. if (this.getScene().useRightHandedSystem) {
  39036. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39037. }
  39038. else {
  39039. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39040. }
  39041. this.beta += this.inertialBetaOffset;
  39042. this.radius -= this.inertialRadiusOffset;
  39043. this.inertialAlphaOffset *= this.inertia;
  39044. this.inertialBetaOffset *= this.inertia;
  39045. this.inertialRadiusOffset *= this.inertia;
  39046. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  39047. this.inertialAlphaOffset = 0;
  39048. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  39049. this.inertialBetaOffset = 0;
  39050. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  39051. this.inertialRadiusOffset = 0;
  39052. }
  39053. // Panning inertia
  39054. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  39055. if (!this._localDirection) {
  39056. this._localDirection = BABYLON.Vector3.Zero();
  39057. this._transformedDirection = BABYLON.Vector3.Zero();
  39058. }
  39059. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  39060. this._localDirection.multiplyInPlace(this.panningAxis);
  39061. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  39062. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  39063. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  39064. if (!this.panningAxis.y) {
  39065. this._transformedDirection.y = 0;
  39066. }
  39067. if (!this._targetHost) {
  39068. if (this.panningDistanceLimit) {
  39069. this._transformedDirection.addInPlace(this._target);
  39070. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  39071. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  39072. this._target.copyFrom(this._transformedDirection);
  39073. }
  39074. }
  39075. else {
  39076. this._target.addInPlace(this._transformedDirection);
  39077. }
  39078. }
  39079. this.inertialPanningX *= this.panningInertia;
  39080. this.inertialPanningY *= this.panningInertia;
  39081. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  39082. this.inertialPanningX = 0;
  39083. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  39084. this.inertialPanningY = 0;
  39085. }
  39086. // Limits
  39087. this._checkLimits();
  39088. _super.prototype._checkInputs.call(this);
  39089. };
  39090. ArcRotateCamera.prototype._checkLimits = function () {
  39091. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  39092. if (this.allowUpsideDown && this.beta > Math.PI) {
  39093. this.beta = this.beta - (2 * Math.PI);
  39094. }
  39095. }
  39096. else {
  39097. if (this.beta < this.lowerBetaLimit) {
  39098. this.beta = this.lowerBetaLimit;
  39099. }
  39100. }
  39101. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  39102. if (this.allowUpsideDown && this.beta < -Math.PI) {
  39103. this.beta = this.beta + (2 * Math.PI);
  39104. }
  39105. }
  39106. else {
  39107. if (this.beta > this.upperBetaLimit) {
  39108. this.beta = this.upperBetaLimit;
  39109. }
  39110. }
  39111. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  39112. this.alpha = this.lowerAlphaLimit;
  39113. }
  39114. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  39115. this.alpha = this.upperAlphaLimit;
  39116. }
  39117. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  39118. this.radius = this.lowerRadiusLimit;
  39119. }
  39120. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  39121. this.radius = this.upperRadiusLimit;
  39122. }
  39123. };
  39124. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  39125. var radiusv3 = this.position.subtract(this._getTargetPosition());
  39126. this.radius = radiusv3.length();
  39127. if (this.radius === 0) {
  39128. this.radius = 0.0001; // Just to avoid division by zero
  39129. }
  39130. // Alpha
  39131. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  39132. if (radiusv3.z < 0) {
  39133. this.alpha = 2 * Math.PI - this.alpha;
  39134. }
  39135. // Beta
  39136. this.beta = Math.acos(radiusv3.y / this.radius);
  39137. this._checkLimits();
  39138. };
  39139. ArcRotateCamera.prototype.setPosition = function (position) {
  39140. if (this.position.equals(position)) {
  39141. return;
  39142. }
  39143. this.position.copyFrom(position);
  39144. this.rebuildAnglesAndRadius();
  39145. };
  39146. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  39147. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  39148. if (allowSamePosition === void 0) { allowSamePosition = false; }
  39149. if (target.getBoundingInfo) {
  39150. if (toBoundingCenter) {
  39151. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  39152. }
  39153. else {
  39154. this._targetBoundingCenter = null;
  39155. }
  39156. this._targetHost = target;
  39157. this._target = this._getTargetPosition();
  39158. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  39159. }
  39160. else {
  39161. var newTarget = target;
  39162. var currentTarget = this._getTargetPosition();
  39163. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  39164. return;
  39165. }
  39166. this._targetHost = null;
  39167. this._target = newTarget;
  39168. this._targetBoundingCenter = null;
  39169. this.onMeshTargetChangedObservable.notifyObservers(null);
  39170. }
  39171. this.rebuildAnglesAndRadius();
  39172. };
  39173. ArcRotateCamera.prototype._getViewMatrix = function () {
  39174. // Compute
  39175. var cosa = Math.cos(this.alpha);
  39176. var sina = Math.sin(this.alpha);
  39177. var cosb = Math.cos(this.beta);
  39178. var sinb = Math.sin(this.beta);
  39179. if (sinb === 0) {
  39180. sinb = 0.0001;
  39181. }
  39182. var target = this._getTargetPosition();
  39183. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  39184. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39185. if (!this._collider) {
  39186. this._collider = new BABYLON.Collider();
  39187. }
  39188. this._collider.radius = this.collisionRadius;
  39189. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39190. this._collisionTriggered = true;
  39191. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39192. }
  39193. else {
  39194. this.position.copyFrom(this._newPosition);
  39195. var up = this.upVector;
  39196. if (this.allowUpsideDown && sinb < 0) {
  39197. up = up.clone();
  39198. up = up.negate();
  39199. }
  39200. if (this.getScene().useRightHandedSystem) {
  39201. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39202. }
  39203. else {
  39204. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39205. }
  39206. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39207. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39208. }
  39209. this._currentTarget = target;
  39210. return this._viewMatrix;
  39211. };
  39212. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39213. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39214. meshes = meshes || this.getScene().meshes;
  39215. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39216. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39217. this.radius = distance * this.zoomOnFactor;
  39218. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39219. };
  39220. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39221. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39222. var meshesOrMinMaxVector;
  39223. var distance;
  39224. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39225. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39226. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39227. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39228. }
  39229. else {
  39230. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39231. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39232. distance = minMaxVectorAndDistance.distance;
  39233. }
  39234. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39235. if (!doNotUpdateMaxZ) {
  39236. this.maxZ = distance * 2;
  39237. }
  39238. };
  39239. /**
  39240. * @override
  39241. * Override Camera.createRigCamera
  39242. */
  39243. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39244. var alphaShift = 0;
  39245. switch (this.cameraRigMode) {
  39246. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39247. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39248. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39249. case BABYLON.Camera.RIG_MODE_VR:
  39250. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39251. break;
  39252. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39253. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39254. break;
  39255. }
  39256. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39257. rigCam._cameraRigParams = {};
  39258. return rigCam;
  39259. };
  39260. /**
  39261. * @override
  39262. * Override Camera._updateRigCameras
  39263. */
  39264. ArcRotateCamera.prototype._updateRigCameras = function () {
  39265. var camLeft = this._rigCameras[0];
  39266. var camRight = this._rigCameras[1];
  39267. camLeft.beta = camRight.beta = this.beta;
  39268. camLeft.radius = camRight.radius = this.radius;
  39269. switch (this.cameraRigMode) {
  39270. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39271. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39272. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39273. case BABYLON.Camera.RIG_MODE_VR:
  39274. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39275. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39276. break;
  39277. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39278. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39279. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39280. break;
  39281. }
  39282. _super.prototype._updateRigCameras.call(this);
  39283. };
  39284. ArcRotateCamera.prototype.dispose = function () {
  39285. this.inputs.clear();
  39286. _super.prototype.dispose.call(this);
  39287. };
  39288. ArcRotateCamera.prototype.getClassName = function () {
  39289. return "ArcRotateCamera";
  39290. };
  39291. __decorate([
  39292. BABYLON.serialize()
  39293. ], ArcRotateCamera.prototype, "alpha", void 0);
  39294. __decorate([
  39295. BABYLON.serialize()
  39296. ], ArcRotateCamera.prototype, "beta", void 0);
  39297. __decorate([
  39298. BABYLON.serialize()
  39299. ], ArcRotateCamera.prototype, "radius", void 0);
  39300. __decorate([
  39301. BABYLON.serializeAsVector3("target")
  39302. ], ArcRotateCamera.prototype, "_target", void 0);
  39303. __decorate([
  39304. BABYLON.serialize()
  39305. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39306. __decorate([
  39307. BABYLON.serialize()
  39308. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39309. __decorate([
  39310. BABYLON.serialize()
  39311. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39312. __decorate([
  39313. BABYLON.serialize()
  39314. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39315. __decorate([
  39316. BABYLON.serialize()
  39317. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39318. __decorate([
  39319. BABYLON.serialize()
  39320. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39321. __decorate([
  39322. BABYLON.serialize()
  39323. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39324. __decorate([
  39325. BABYLON.serialize()
  39326. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39327. __decorate([
  39328. BABYLON.serialize()
  39329. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39330. __decorate([
  39331. BABYLON.serialize()
  39332. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39333. __decorate([
  39334. BABYLON.serialize()
  39335. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39336. __decorate([
  39337. BABYLON.serialize()
  39338. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39339. __decorate([
  39340. BABYLON.serialize()
  39341. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39342. __decorate([
  39343. BABYLON.serializeAsVector3()
  39344. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39345. __decorate([
  39346. BABYLON.serialize()
  39347. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39348. __decorate([
  39349. BABYLON.serialize()
  39350. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39351. __decorate([
  39352. BABYLON.serialize()
  39353. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39354. return ArcRotateCamera;
  39355. }(BABYLON.TargetCamera));
  39356. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39357. })(BABYLON || (BABYLON = {}));
  39358. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39359. var BABYLON;
  39360. (function (BABYLON) {
  39361. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39362. __extends(ArcRotateCameraInputsManager, _super);
  39363. function ArcRotateCameraInputsManager(camera) {
  39364. return _super.call(this, camera) || this;
  39365. }
  39366. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39367. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39368. return this;
  39369. };
  39370. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39371. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39372. return this;
  39373. };
  39374. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39375. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39376. return this;
  39377. };
  39378. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39379. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39380. return this;
  39381. };
  39382. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39383. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39384. return this;
  39385. };
  39386. return ArcRotateCameraInputsManager;
  39387. }(BABYLON.CameraInputsManager));
  39388. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39389. })(BABYLON || (BABYLON = {}));
  39390. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39391. var BABYLON;
  39392. (function (BABYLON) {
  39393. var HemisphericLight = /** @class */ (function (_super) {
  39394. __extends(HemisphericLight, _super);
  39395. /**
  39396. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39397. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39398. * The HemisphericLight can't cast shadows.
  39399. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39400. */
  39401. function HemisphericLight(name, direction, scene) {
  39402. var _this = _super.call(this, name, scene) || this;
  39403. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39404. _this.direction = direction || BABYLON.Vector3.Up();
  39405. return _this;
  39406. }
  39407. HemisphericLight.prototype._buildUniformLayout = function () {
  39408. this._uniformBuffer.addUniform("vLightData", 4);
  39409. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39410. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39411. this._uniformBuffer.addUniform("vLightGround", 3);
  39412. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39413. this._uniformBuffer.addUniform("depthValues", 2);
  39414. this._uniformBuffer.create();
  39415. };
  39416. /**
  39417. * Returns the string "HemisphericLight".
  39418. */
  39419. HemisphericLight.prototype.getClassName = function () {
  39420. return "HemisphericLight";
  39421. };
  39422. /**
  39423. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39424. * Returns the updated direction.
  39425. */
  39426. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39427. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39428. return this.direction;
  39429. };
  39430. HemisphericLight.prototype.getShadowGenerator = function () {
  39431. return null;
  39432. };
  39433. /**
  39434. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39435. * Returns the HemisphericLight.
  39436. */
  39437. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39438. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39439. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39440. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39441. return this;
  39442. };
  39443. HemisphericLight.prototype._getWorldMatrix = function () {
  39444. if (!this._worldMatrix) {
  39445. this._worldMatrix = BABYLON.Matrix.Identity();
  39446. }
  39447. return this._worldMatrix;
  39448. };
  39449. /**
  39450. * Returns the integer 3.
  39451. */
  39452. HemisphericLight.prototype.getTypeID = function () {
  39453. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39454. };
  39455. __decorate([
  39456. BABYLON.serializeAsColor3()
  39457. ], HemisphericLight.prototype, "groundColor", void 0);
  39458. __decorate([
  39459. BABYLON.serializeAsVector3()
  39460. ], HemisphericLight.prototype, "direction", void 0);
  39461. return HemisphericLight;
  39462. }(BABYLON.Light));
  39463. BABYLON.HemisphericLight = HemisphericLight;
  39464. })(BABYLON || (BABYLON = {}));
  39465. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39466. var BABYLON;
  39467. (function (BABYLON) {
  39468. var ShadowLight = /** @class */ (function (_super) {
  39469. __extends(ShadowLight, _super);
  39470. function ShadowLight() {
  39471. var _this = _super !== null && _super.apply(this, arguments) || this;
  39472. _this._needProjectionMatrixCompute = true;
  39473. return _this;
  39474. }
  39475. Object.defineProperty(ShadowLight.prototype, "direction", {
  39476. get: function () {
  39477. return this._direction;
  39478. },
  39479. set: function (value) {
  39480. this._direction = value;
  39481. },
  39482. enumerable: true,
  39483. configurable: true
  39484. });
  39485. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39486. get: function () {
  39487. return this._shadowMinZ;
  39488. },
  39489. set: function (value) {
  39490. this._shadowMinZ = value;
  39491. this.forceProjectionMatrixCompute();
  39492. },
  39493. enumerable: true,
  39494. configurable: true
  39495. });
  39496. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39497. get: function () {
  39498. return this._shadowMaxZ;
  39499. },
  39500. set: function (value) {
  39501. this._shadowMaxZ = value;
  39502. this.forceProjectionMatrixCompute();
  39503. },
  39504. enumerable: true,
  39505. configurable: true
  39506. });
  39507. /**
  39508. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39509. */
  39510. ShadowLight.prototype.computeTransformedInformation = function () {
  39511. if (this.parent && this.parent.getWorldMatrix) {
  39512. if (!this.transformedPosition) {
  39513. this.transformedPosition = BABYLON.Vector3.Zero();
  39514. }
  39515. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39516. // In case the direction is present.
  39517. if (this.direction) {
  39518. if (!this.transformedDirection) {
  39519. this.transformedDirection = BABYLON.Vector3.Zero();
  39520. }
  39521. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39522. }
  39523. return true;
  39524. }
  39525. return false;
  39526. };
  39527. /**
  39528. * Return the depth scale used for the shadow map.
  39529. */
  39530. ShadowLight.prototype.getDepthScale = function () {
  39531. return 50.0;
  39532. };
  39533. /**
  39534. * Returns the light direction (Vector3) for any passed face index.
  39535. */
  39536. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39537. return this.transformedDirection ? this.transformedDirection : this.direction;
  39538. };
  39539. /**
  39540. * Returns the DirectionalLight absolute position in the World.
  39541. */
  39542. ShadowLight.prototype.getAbsolutePosition = function () {
  39543. return this.transformedPosition ? this.transformedPosition : this.position;
  39544. };
  39545. /**
  39546. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39547. * Returns the updated DirectionalLight direction (Vector3).
  39548. */
  39549. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39550. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39551. return this.direction;
  39552. };
  39553. /**
  39554. * Returns the light rotation (Vector3).
  39555. */
  39556. ShadowLight.prototype.getRotation = function () {
  39557. this.direction.normalize();
  39558. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39559. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39560. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39561. };
  39562. /**
  39563. * Boolean : false by default.
  39564. */
  39565. ShadowLight.prototype.needCube = function () {
  39566. return false;
  39567. };
  39568. /**
  39569. * Specifies wether or not the projection matrix should be recomputed this frame.
  39570. */
  39571. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39572. return this._needProjectionMatrixCompute;
  39573. };
  39574. /**
  39575. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39576. */
  39577. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39578. this._needProjectionMatrixCompute = true;
  39579. };
  39580. /**
  39581. * Get the world matrix of the sahdow lights.
  39582. */
  39583. ShadowLight.prototype._getWorldMatrix = function () {
  39584. if (!this._worldMatrix) {
  39585. this._worldMatrix = BABYLON.Matrix.Identity();
  39586. }
  39587. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39588. return this._worldMatrix;
  39589. };
  39590. /**
  39591. * Gets the minZ used for shadow according to both the scene and the light.
  39592. * @param activeCamera
  39593. */
  39594. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39595. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39596. };
  39597. /**
  39598. * Gets the maxZ used for shadow according to both the scene and the light.
  39599. * @param activeCamera
  39600. */
  39601. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39602. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39603. };
  39604. /**
  39605. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39606. * Returns the light.
  39607. */
  39608. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39609. if (this.customProjectionMatrixBuilder) {
  39610. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39611. }
  39612. else {
  39613. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39614. }
  39615. return this;
  39616. };
  39617. __decorate([
  39618. BABYLON.serializeAsVector3()
  39619. ], ShadowLight.prototype, "position", void 0);
  39620. __decorate([
  39621. BABYLON.serializeAsVector3()
  39622. ], ShadowLight.prototype, "direction", null);
  39623. __decorate([
  39624. BABYLON.serialize()
  39625. ], ShadowLight.prototype, "shadowMinZ", null);
  39626. __decorate([
  39627. BABYLON.serialize()
  39628. ], ShadowLight.prototype, "shadowMaxZ", null);
  39629. return ShadowLight;
  39630. }(BABYLON.Light));
  39631. BABYLON.ShadowLight = ShadowLight;
  39632. })(BABYLON || (BABYLON = {}));
  39633. //# sourceMappingURL=babylon.shadowLight.js.map
  39634. var BABYLON;
  39635. (function (BABYLON) {
  39636. var PointLight = /** @class */ (function (_super) {
  39637. __extends(PointLight, _super);
  39638. /**
  39639. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39640. * A PointLight emits the light in every direction.
  39641. * It can cast shadows.
  39642. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39643. * ```javascript
  39644. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39645. * ```
  39646. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39647. */
  39648. function PointLight(name, position, scene) {
  39649. var _this = _super.call(this, name, scene) || this;
  39650. _this._shadowAngle = Math.PI / 2;
  39651. _this.position = position;
  39652. return _this;
  39653. }
  39654. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39655. /**
  39656. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39657. * This specifies what angle the shadow will use to be created.
  39658. *
  39659. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39660. */
  39661. get: function () {
  39662. return this._shadowAngle;
  39663. },
  39664. /**
  39665. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39666. * This specifies what angle the shadow will use to be created.
  39667. *
  39668. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39669. */
  39670. set: function (value) {
  39671. this._shadowAngle = value;
  39672. this.forceProjectionMatrixCompute();
  39673. },
  39674. enumerable: true,
  39675. configurable: true
  39676. });
  39677. Object.defineProperty(PointLight.prototype, "direction", {
  39678. get: function () {
  39679. return this._direction;
  39680. },
  39681. /**
  39682. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39683. */
  39684. set: function (value) {
  39685. var previousNeedCube = this.needCube();
  39686. this._direction = value;
  39687. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39688. this._shadowGenerator.recreateShadowMap();
  39689. }
  39690. },
  39691. enumerable: true,
  39692. configurable: true
  39693. });
  39694. /**
  39695. * Returns the string "PointLight"
  39696. */
  39697. PointLight.prototype.getClassName = function () {
  39698. return "PointLight";
  39699. };
  39700. /**
  39701. * Returns the integer 0.
  39702. */
  39703. PointLight.prototype.getTypeID = function () {
  39704. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39705. };
  39706. /**
  39707. * Specifies wether or not the shadowmap should be a cube texture.
  39708. */
  39709. PointLight.prototype.needCube = function () {
  39710. return !this.direction;
  39711. };
  39712. /**
  39713. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39714. */
  39715. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39716. if (this.direction) {
  39717. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39718. }
  39719. else {
  39720. switch (faceIndex) {
  39721. case 0:
  39722. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39723. case 1:
  39724. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39725. case 2:
  39726. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39727. case 3:
  39728. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39729. case 4:
  39730. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39731. case 5:
  39732. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39733. }
  39734. }
  39735. return BABYLON.Vector3.Zero();
  39736. };
  39737. /**
  39738. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39739. * - fov = PI / 2
  39740. * - aspect ratio : 1.0
  39741. * - z-near and far equal to the active camera minZ and maxZ.
  39742. * Returns the PointLight.
  39743. */
  39744. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39745. var activeCamera = this.getScene().activeCamera;
  39746. if (!activeCamera) {
  39747. return;
  39748. }
  39749. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39750. };
  39751. PointLight.prototype._buildUniformLayout = function () {
  39752. this._uniformBuffer.addUniform("vLightData", 4);
  39753. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39754. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39755. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39756. this._uniformBuffer.addUniform("depthValues", 2);
  39757. this._uniformBuffer.create();
  39758. };
  39759. /**
  39760. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39761. * Returns the PointLight.
  39762. */
  39763. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39764. if (this.computeTransformedInformation()) {
  39765. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39766. return this;
  39767. }
  39768. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39769. return this;
  39770. };
  39771. __decorate([
  39772. BABYLON.serialize()
  39773. ], PointLight.prototype, "shadowAngle", null);
  39774. return PointLight;
  39775. }(BABYLON.ShadowLight));
  39776. BABYLON.PointLight = PointLight;
  39777. })(BABYLON || (BABYLON = {}));
  39778. //# sourceMappingURL=babylon.pointLight.js.map
  39779. var BABYLON;
  39780. (function (BABYLON) {
  39781. var DirectionalLight = /** @class */ (function (_super) {
  39782. __extends(DirectionalLight, _super);
  39783. /**
  39784. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39785. * The directional light is emitted from everywhere in the given direction.
  39786. * It can cast shawdows.
  39787. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39788. */
  39789. function DirectionalLight(name, direction, scene) {
  39790. var _this = _super.call(this, name, scene) || this;
  39791. _this._shadowFrustumSize = 0;
  39792. _this._shadowOrthoScale = 0.5;
  39793. _this.autoUpdateExtends = true;
  39794. // Cache
  39795. _this._orthoLeft = Number.MAX_VALUE;
  39796. _this._orthoRight = Number.MIN_VALUE;
  39797. _this._orthoTop = Number.MIN_VALUE;
  39798. _this._orthoBottom = Number.MAX_VALUE;
  39799. _this.position = direction.scale(-1.0);
  39800. _this.direction = direction;
  39801. return _this;
  39802. }
  39803. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39804. /**
  39805. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39806. */
  39807. get: function () {
  39808. return this._shadowFrustumSize;
  39809. },
  39810. /**
  39811. * Specifies a fix frustum size for the shadow generation.
  39812. */
  39813. set: function (value) {
  39814. this._shadowFrustumSize = value;
  39815. this.forceProjectionMatrixCompute();
  39816. },
  39817. enumerable: true,
  39818. configurable: true
  39819. });
  39820. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39821. get: function () {
  39822. return this._shadowOrthoScale;
  39823. },
  39824. set: function (value) {
  39825. this._shadowOrthoScale = value;
  39826. this.forceProjectionMatrixCompute();
  39827. },
  39828. enumerable: true,
  39829. configurable: true
  39830. });
  39831. /**
  39832. * Returns the string "DirectionalLight".
  39833. */
  39834. DirectionalLight.prototype.getClassName = function () {
  39835. return "DirectionalLight";
  39836. };
  39837. /**
  39838. * Returns the integer 1.
  39839. */
  39840. DirectionalLight.prototype.getTypeID = function () {
  39841. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39842. };
  39843. /**
  39844. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39845. * Returns the DirectionalLight Shadow projection matrix.
  39846. */
  39847. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39848. if (this.shadowFrustumSize > 0) {
  39849. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39850. }
  39851. else {
  39852. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39853. }
  39854. };
  39855. /**
  39856. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39857. * Returns the DirectionalLight Shadow projection matrix.
  39858. */
  39859. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39860. var activeCamera = this.getScene().activeCamera;
  39861. if (!activeCamera) {
  39862. return;
  39863. }
  39864. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39865. };
  39866. /**
  39867. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39868. * Returns the DirectionalLight Shadow projection matrix.
  39869. */
  39870. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39871. var activeCamera = this.getScene().activeCamera;
  39872. if (!activeCamera) {
  39873. return;
  39874. }
  39875. // Check extends
  39876. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39877. var tempVector3 = BABYLON.Vector3.Zero();
  39878. this._orthoLeft = Number.MAX_VALUE;
  39879. this._orthoRight = Number.MIN_VALUE;
  39880. this._orthoTop = Number.MIN_VALUE;
  39881. this._orthoBottom = Number.MAX_VALUE;
  39882. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39883. var mesh = renderList[meshIndex];
  39884. if (!mesh) {
  39885. continue;
  39886. }
  39887. var boundingInfo = mesh.getBoundingInfo();
  39888. if (!boundingInfo) {
  39889. continue;
  39890. }
  39891. var boundingBox = boundingInfo.boundingBox;
  39892. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39893. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39894. if (tempVector3.x < this._orthoLeft)
  39895. this._orthoLeft = tempVector3.x;
  39896. if (tempVector3.y < this._orthoBottom)
  39897. this._orthoBottom = tempVector3.y;
  39898. if (tempVector3.x > this._orthoRight)
  39899. this._orthoRight = tempVector3.x;
  39900. if (tempVector3.y > this._orthoTop)
  39901. this._orthoTop = tempVector3.y;
  39902. }
  39903. }
  39904. }
  39905. var xOffset = this._orthoRight - this._orthoLeft;
  39906. var yOffset = this._orthoTop - this._orthoBottom;
  39907. 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);
  39908. };
  39909. DirectionalLight.prototype._buildUniformLayout = function () {
  39910. this._uniformBuffer.addUniform("vLightData", 4);
  39911. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39912. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39913. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39914. this._uniformBuffer.addUniform("depthValues", 2);
  39915. this._uniformBuffer.create();
  39916. };
  39917. /**
  39918. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39919. * Returns the DirectionalLight.
  39920. */
  39921. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39922. if (this.computeTransformedInformation()) {
  39923. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39924. return this;
  39925. }
  39926. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39927. return this;
  39928. };
  39929. /**
  39930. * Gets the minZ used for shadow according to both the scene and the light.
  39931. *
  39932. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39933. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39934. * @param activeCamera
  39935. */
  39936. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39937. return 1;
  39938. };
  39939. /**
  39940. * Gets the maxZ used for shadow according to both the scene and the light.
  39941. *
  39942. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39943. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39944. * @param activeCamera
  39945. */
  39946. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39947. return 1;
  39948. };
  39949. __decorate([
  39950. BABYLON.serialize()
  39951. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39952. __decorate([
  39953. BABYLON.serialize()
  39954. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39955. __decorate([
  39956. BABYLON.serialize()
  39957. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39958. return DirectionalLight;
  39959. }(BABYLON.ShadowLight));
  39960. BABYLON.DirectionalLight = DirectionalLight;
  39961. })(BABYLON || (BABYLON = {}));
  39962. //# sourceMappingURL=babylon.directionalLight.js.map
  39963. var BABYLON;
  39964. (function (BABYLON) {
  39965. var SpotLight = /** @class */ (function (_super) {
  39966. __extends(SpotLight, _super);
  39967. /**
  39968. * Creates a SpotLight object in the scene with the passed parameters :
  39969. * - `position` (Vector3) is the initial SpotLight position,
  39970. * - `direction` (Vector3) is the initial SpotLight direction,
  39971. * - `angle` (float, in radians) is the spot light cone angle,
  39972. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39973. * A spot light is a simply light oriented cone.
  39974. * It can cast shadows.
  39975. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39976. */
  39977. function SpotLight(name, position, direction, angle, exponent, scene) {
  39978. var _this = _super.call(this, name, scene) || this;
  39979. _this.position = position;
  39980. _this.direction = direction;
  39981. _this.angle = angle;
  39982. _this.exponent = exponent;
  39983. return _this;
  39984. }
  39985. Object.defineProperty(SpotLight.prototype, "angle", {
  39986. get: function () {
  39987. return this._angle;
  39988. },
  39989. set: function (value) {
  39990. this._angle = value;
  39991. this.forceProjectionMatrixCompute();
  39992. },
  39993. enumerable: true,
  39994. configurable: true
  39995. });
  39996. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39997. get: function () {
  39998. return this._shadowAngleScale;
  39999. },
  40000. /**
  40001. * Allows scaling the angle of the light for shadow generation only.
  40002. */
  40003. set: function (value) {
  40004. this._shadowAngleScale = value;
  40005. this.forceProjectionMatrixCompute();
  40006. },
  40007. enumerable: true,
  40008. configurable: true
  40009. });
  40010. /**
  40011. * Returns the string "SpotLight".
  40012. */
  40013. SpotLight.prototype.getClassName = function () {
  40014. return "SpotLight";
  40015. };
  40016. /**
  40017. * Returns the integer 2.
  40018. */
  40019. SpotLight.prototype.getTypeID = function () {
  40020. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40021. };
  40022. /**
  40023. * 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.
  40024. * Returns the SpotLight.
  40025. */
  40026. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40027. var activeCamera = this.getScene().activeCamera;
  40028. if (!activeCamera) {
  40029. return;
  40030. }
  40031. this._shadowAngleScale = this._shadowAngleScale || 1;
  40032. var angle = this._shadowAngleScale * this._angle;
  40033. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40034. };
  40035. SpotLight.prototype._buildUniformLayout = function () {
  40036. this._uniformBuffer.addUniform("vLightData", 4);
  40037. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40038. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40039. this._uniformBuffer.addUniform("vLightDirection", 3);
  40040. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40041. this._uniformBuffer.addUniform("depthValues", 2);
  40042. this._uniformBuffer.create();
  40043. };
  40044. /**
  40045. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40046. * Return the SpotLight.
  40047. */
  40048. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40049. var normalizeDirection;
  40050. if (this.computeTransformedInformation()) {
  40051. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40052. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40053. }
  40054. else {
  40055. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40056. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40057. }
  40058. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40059. return this;
  40060. };
  40061. __decorate([
  40062. BABYLON.serialize()
  40063. ], SpotLight.prototype, "angle", null);
  40064. __decorate([
  40065. BABYLON.serialize()
  40066. /**
  40067. * Allows scaling the angle of the light for shadow generation only.
  40068. */
  40069. ], SpotLight.prototype, "shadowAngleScale", null);
  40070. __decorate([
  40071. BABYLON.serialize()
  40072. ], SpotLight.prototype, "exponent", void 0);
  40073. return SpotLight;
  40074. }(BABYLON.ShadowLight));
  40075. BABYLON.SpotLight = SpotLight;
  40076. })(BABYLON || (BABYLON = {}));
  40077. //# sourceMappingURL=babylon.spotLight.js.map
  40078. var BABYLON;
  40079. (function (BABYLON) {
  40080. var AnimationRange = /** @class */ (function () {
  40081. function AnimationRange(name, from, to) {
  40082. this.name = name;
  40083. this.from = from;
  40084. this.to = to;
  40085. }
  40086. AnimationRange.prototype.clone = function () {
  40087. return new AnimationRange(this.name, this.from, this.to);
  40088. };
  40089. return AnimationRange;
  40090. }());
  40091. BABYLON.AnimationRange = AnimationRange;
  40092. /**
  40093. * Composed of a frame, and an action function
  40094. */
  40095. var AnimationEvent = /** @class */ (function () {
  40096. function AnimationEvent(frame, action, onlyOnce) {
  40097. this.frame = frame;
  40098. this.action = action;
  40099. this.onlyOnce = onlyOnce;
  40100. this.isDone = false;
  40101. }
  40102. return AnimationEvent;
  40103. }());
  40104. BABYLON.AnimationEvent = AnimationEvent;
  40105. var PathCursor = /** @class */ (function () {
  40106. function PathCursor(path) {
  40107. this.path = path;
  40108. this._onchange = new Array();
  40109. this.value = 0;
  40110. this.animations = new Array();
  40111. }
  40112. PathCursor.prototype.getPoint = function () {
  40113. var point = this.path.getPointAtLengthPosition(this.value);
  40114. return new BABYLON.Vector3(point.x, 0, point.y);
  40115. };
  40116. PathCursor.prototype.moveAhead = function (step) {
  40117. if (step === void 0) { step = 0.002; }
  40118. this.move(step);
  40119. return this;
  40120. };
  40121. PathCursor.prototype.moveBack = function (step) {
  40122. if (step === void 0) { step = 0.002; }
  40123. this.move(-step);
  40124. return this;
  40125. };
  40126. PathCursor.prototype.move = function (step) {
  40127. if (Math.abs(step) > 1) {
  40128. throw "step size should be less than 1.";
  40129. }
  40130. this.value += step;
  40131. this.ensureLimits();
  40132. this.raiseOnChange();
  40133. return this;
  40134. };
  40135. PathCursor.prototype.ensureLimits = function () {
  40136. while (this.value > 1) {
  40137. this.value -= 1;
  40138. }
  40139. while (this.value < 0) {
  40140. this.value += 1;
  40141. }
  40142. return this;
  40143. };
  40144. // used by animation engine
  40145. PathCursor.prototype.raiseOnChange = function () {
  40146. var _this = this;
  40147. this._onchange.forEach(function (f) { return f(_this); });
  40148. return this;
  40149. };
  40150. PathCursor.prototype.onchange = function (f) {
  40151. this._onchange.push(f);
  40152. return this;
  40153. };
  40154. return PathCursor;
  40155. }());
  40156. BABYLON.PathCursor = PathCursor;
  40157. var Animation = /** @class */ (function () {
  40158. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  40159. this.name = name;
  40160. this.targetProperty = targetProperty;
  40161. this.framePerSecond = framePerSecond;
  40162. this.dataType = dataType;
  40163. this.loopMode = loopMode;
  40164. this.enableBlending = enableBlending;
  40165. this._runtimeAnimations = new Array();
  40166. // The set of event that will be linked to this animation
  40167. this._events = new Array();
  40168. this.blendingSpeed = 0.01;
  40169. this._ranges = {};
  40170. this.targetPropertyPath = targetProperty.split(".");
  40171. this.dataType = dataType;
  40172. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  40173. }
  40174. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  40175. var dataType = undefined;
  40176. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  40177. dataType = Animation.ANIMATIONTYPE_FLOAT;
  40178. }
  40179. else if (from instanceof BABYLON.Quaternion) {
  40180. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  40181. }
  40182. else if (from instanceof BABYLON.Vector3) {
  40183. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  40184. }
  40185. else if (from instanceof BABYLON.Vector2) {
  40186. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40187. }
  40188. else if (from instanceof BABYLON.Color3) {
  40189. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40190. }
  40191. else if (from instanceof BABYLON.Size) {
  40192. dataType = Animation.ANIMATIONTYPE_SIZE;
  40193. }
  40194. if (dataType == undefined) {
  40195. return null;
  40196. }
  40197. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40198. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40199. animation.setKeys(keys);
  40200. if (easingFunction !== undefined) {
  40201. animation.setEasingFunction(easingFunction);
  40202. }
  40203. return animation;
  40204. };
  40205. /**
  40206. * Sets up an animation.
  40207. * @param property the property to animate
  40208. * @param animationType the animation type to apply
  40209. * @param easingFunction the easing function used in the animation
  40210. * @returns The created animation
  40211. */
  40212. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40213. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40214. animation.setEasingFunction(easingFunction);
  40215. return animation;
  40216. };
  40217. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40218. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40219. if (!animation) {
  40220. return null;
  40221. }
  40222. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40223. };
  40224. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40225. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40226. if (!animation) {
  40227. return null;
  40228. }
  40229. node.animations.push(animation);
  40230. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40231. };
  40232. /**
  40233. * Transition property of the Camera to the target Value.
  40234. * @param property The property to transition
  40235. * @param targetValue The target Value of the property
  40236. * @param host The object where the property to animate belongs
  40237. * @param scene Scene used to run the animation
  40238. * @param frameRate Framerate (in frame/s) to use
  40239. * @param transition The transition type we want to use
  40240. * @param duration The duration of the animation, in milliseconds
  40241. * @param onAnimationEnd Call back trigger at the end of the animation.
  40242. */
  40243. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40244. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40245. if (duration <= 0) {
  40246. host[property] = targetValue;
  40247. if (onAnimationEnd) {
  40248. onAnimationEnd();
  40249. }
  40250. return null;
  40251. }
  40252. var endFrame = frameRate * (duration / 1000);
  40253. transition.setKeys([{
  40254. frame: 0,
  40255. value: host[property].clone ? host[property].clone() : host[property]
  40256. },
  40257. {
  40258. frame: endFrame,
  40259. value: targetValue
  40260. }]);
  40261. if (!host.animations) {
  40262. host.animations = [];
  40263. }
  40264. host.animations.push(transition);
  40265. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40266. animation.onAnimationEnd = onAnimationEnd;
  40267. return animation;
  40268. };
  40269. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40270. /**
  40271. * Return the array of runtime animations currently using this animation
  40272. */
  40273. get: function () {
  40274. return this._runtimeAnimations;
  40275. },
  40276. enumerable: true,
  40277. configurable: true
  40278. });
  40279. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40280. get: function () {
  40281. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40282. var runtimeAnimation = _a[_i];
  40283. if (!runtimeAnimation.isStopped) {
  40284. return true;
  40285. }
  40286. }
  40287. return false;
  40288. },
  40289. enumerable: true,
  40290. configurable: true
  40291. });
  40292. // Methods
  40293. /**
  40294. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40295. */
  40296. Animation.prototype.toString = function (fullDetails) {
  40297. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40298. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40299. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40300. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40301. if (fullDetails) {
  40302. ret += ", Ranges: {";
  40303. var first = true;
  40304. for (var name in this._ranges) {
  40305. if (first) {
  40306. ret += ", ";
  40307. first = false;
  40308. }
  40309. ret += name;
  40310. }
  40311. ret += "}";
  40312. }
  40313. return ret;
  40314. };
  40315. /**
  40316. * Add an event to this animation.
  40317. */
  40318. Animation.prototype.addEvent = function (event) {
  40319. this._events.push(event);
  40320. };
  40321. /**
  40322. * Remove all events found at the given frame
  40323. * @param frame
  40324. */
  40325. Animation.prototype.removeEvents = function (frame) {
  40326. for (var index = 0; index < this._events.length; index++) {
  40327. if (this._events[index].frame === frame) {
  40328. this._events.splice(index, 1);
  40329. index--;
  40330. }
  40331. }
  40332. };
  40333. Animation.prototype.getEvents = function () {
  40334. return this._events;
  40335. };
  40336. Animation.prototype.createRange = function (name, from, to) {
  40337. // check name not already in use; could happen for bones after serialized
  40338. if (!this._ranges[name]) {
  40339. this._ranges[name] = new AnimationRange(name, from, to);
  40340. }
  40341. };
  40342. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40343. if (deleteFrames === void 0) { deleteFrames = true; }
  40344. var range = this._ranges[name];
  40345. if (!range) {
  40346. return;
  40347. }
  40348. if (deleteFrames) {
  40349. var from = range.from;
  40350. var to = range.to;
  40351. // this loop MUST go high to low for multiple splices to work
  40352. for (var key = this._keys.length - 1; key >= 0; key--) {
  40353. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40354. this._keys.splice(key, 1);
  40355. }
  40356. }
  40357. }
  40358. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40359. };
  40360. Animation.prototype.getRange = function (name) {
  40361. return this._ranges[name];
  40362. };
  40363. Animation.prototype.getKeys = function () {
  40364. return this._keys;
  40365. };
  40366. Animation.prototype.getHighestFrame = function () {
  40367. var ret = 0;
  40368. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40369. if (ret < this._keys[key].frame) {
  40370. ret = this._keys[key].frame;
  40371. }
  40372. }
  40373. return ret;
  40374. };
  40375. Animation.prototype.getEasingFunction = function () {
  40376. return this._easingFunction;
  40377. };
  40378. Animation.prototype.setEasingFunction = function (easingFunction) {
  40379. this._easingFunction = easingFunction;
  40380. };
  40381. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40382. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40383. };
  40384. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40385. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40386. };
  40387. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40388. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40389. };
  40390. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40391. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40392. };
  40393. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40394. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40395. };
  40396. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40397. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40398. };
  40399. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40400. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40401. };
  40402. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40403. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40404. };
  40405. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40406. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40407. };
  40408. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40409. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40410. };
  40411. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40412. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40413. };
  40414. Animation.prototype.clone = function () {
  40415. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40416. clone.enableBlending = this.enableBlending;
  40417. clone.blendingSpeed = this.blendingSpeed;
  40418. if (this._keys) {
  40419. clone.setKeys(this._keys);
  40420. }
  40421. if (this._ranges) {
  40422. clone._ranges = {};
  40423. for (var name in this._ranges) {
  40424. var range = this._ranges[name];
  40425. if (!range) {
  40426. continue;
  40427. }
  40428. clone._ranges[name] = range.clone();
  40429. }
  40430. }
  40431. return clone;
  40432. };
  40433. Animation.prototype.setKeys = function (values) {
  40434. this._keys = values.slice(0);
  40435. };
  40436. Animation.prototype.serialize = function () {
  40437. var serializationObject = {};
  40438. serializationObject.name = this.name;
  40439. serializationObject.property = this.targetProperty;
  40440. serializationObject.framePerSecond = this.framePerSecond;
  40441. serializationObject.dataType = this.dataType;
  40442. serializationObject.loopBehavior = this.loopMode;
  40443. serializationObject.enableBlending = this.enableBlending;
  40444. serializationObject.blendingSpeed = this.blendingSpeed;
  40445. var dataType = this.dataType;
  40446. serializationObject.keys = [];
  40447. var keys = this.getKeys();
  40448. for (var index = 0; index < keys.length; index++) {
  40449. var animationKey = keys[index];
  40450. var key = {};
  40451. key.frame = animationKey.frame;
  40452. switch (dataType) {
  40453. case Animation.ANIMATIONTYPE_FLOAT:
  40454. key.values = [animationKey.value];
  40455. break;
  40456. case Animation.ANIMATIONTYPE_QUATERNION:
  40457. case Animation.ANIMATIONTYPE_MATRIX:
  40458. case Animation.ANIMATIONTYPE_VECTOR3:
  40459. case Animation.ANIMATIONTYPE_COLOR3:
  40460. key.values = animationKey.value.asArray();
  40461. break;
  40462. }
  40463. serializationObject.keys.push(key);
  40464. }
  40465. serializationObject.ranges = [];
  40466. for (var name in this._ranges) {
  40467. var source = this._ranges[name];
  40468. if (!source) {
  40469. continue;
  40470. }
  40471. var range = {};
  40472. range.name = name;
  40473. range.from = source.from;
  40474. range.to = source.to;
  40475. serializationObject.ranges.push(range);
  40476. }
  40477. return serializationObject;
  40478. };
  40479. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40480. get: function () {
  40481. return Animation._ANIMATIONTYPE_FLOAT;
  40482. },
  40483. enumerable: true,
  40484. configurable: true
  40485. });
  40486. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40487. get: function () {
  40488. return Animation._ANIMATIONTYPE_VECTOR3;
  40489. },
  40490. enumerable: true,
  40491. configurable: true
  40492. });
  40493. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40494. get: function () {
  40495. return Animation._ANIMATIONTYPE_VECTOR2;
  40496. },
  40497. enumerable: true,
  40498. configurable: true
  40499. });
  40500. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40501. get: function () {
  40502. return Animation._ANIMATIONTYPE_SIZE;
  40503. },
  40504. enumerable: true,
  40505. configurable: true
  40506. });
  40507. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40508. get: function () {
  40509. return Animation._ANIMATIONTYPE_QUATERNION;
  40510. },
  40511. enumerable: true,
  40512. configurable: true
  40513. });
  40514. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40515. get: function () {
  40516. return Animation._ANIMATIONTYPE_MATRIX;
  40517. },
  40518. enumerable: true,
  40519. configurable: true
  40520. });
  40521. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40522. get: function () {
  40523. return Animation._ANIMATIONTYPE_COLOR3;
  40524. },
  40525. enumerable: true,
  40526. configurable: true
  40527. });
  40528. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40529. get: function () {
  40530. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40531. },
  40532. enumerable: true,
  40533. configurable: true
  40534. });
  40535. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40536. get: function () {
  40537. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40538. },
  40539. enumerable: true,
  40540. configurable: true
  40541. });
  40542. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40543. get: function () {
  40544. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40545. },
  40546. enumerable: true,
  40547. configurable: true
  40548. });
  40549. Animation.Parse = function (parsedAnimation) {
  40550. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40551. var dataType = parsedAnimation.dataType;
  40552. var keys = [];
  40553. var data;
  40554. var index;
  40555. if (parsedAnimation.enableBlending) {
  40556. animation.enableBlending = parsedAnimation.enableBlending;
  40557. }
  40558. if (parsedAnimation.blendingSpeed) {
  40559. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40560. }
  40561. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40562. var key = parsedAnimation.keys[index];
  40563. var inTangent;
  40564. var outTangent;
  40565. switch (dataType) {
  40566. case Animation.ANIMATIONTYPE_FLOAT:
  40567. data = key.values[0];
  40568. if (key.values.length >= 1) {
  40569. inTangent = key.values[1];
  40570. }
  40571. if (key.values.length >= 2) {
  40572. outTangent = key.values[2];
  40573. }
  40574. break;
  40575. case Animation.ANIMATIONTYPE_QUATERNION:
  40576. data = BABYLON.Quaternion.FromArray(key.values);
  40577. if (key.values.length >= 8) {
  40578. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40579. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40580. inTangent = _inTangent;
  40581. }
  40582. }
  40583. if (key.values.length >= 12) {
  40584. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40585. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40586. outTangent = _outTangent;
  40587. }
  40588. }
  40589. break;
  40590. case Animation.ANIMATIONTYPE_MATRIX:
  40591. data = BABYLON.Matrix.FromArray(key.values);
  40592. break;
  40593. case Animation.ANIMATIONTYPE_COLOR3:
  40594. data = BABYLON.Color3.FromArray(key.values);
  40595. break;
  40596. case Animation.ANIMATIONTYPE_VECTOR3:
  40597. default:
  40598. data = BABYLON.Vector3.FromArray(key.values);
  40599. break;
  40600. }
  40601. var keyData = {};
  40602. keyData.frame = key.frame;
  40603. keyData.value = data;
  40604. if (inTangent != undefined) {
  40605. keyData.inTangent = inTangent;
  40606. }
  40607. if (outTangent != undefined) {
  40608. keyData.outTangent = outTangent;
  40609. }
  40610. keys.push(keyData);
  40611. }
  40612. animation.setKeys(keys);
  40613. if (parsedAnimation.ranges) {
  40614. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40615. data = parsedAnimation.ranges[index];
  40616. animation.createRange(data.name, data.from, data.to);
  40617. }
  40618. }
  40619. return animation;
  40620. };
  40621. Animation.AppendSerializedAnimations = function (source, destination) {
  40622. if (source.animations) {
  40623. destination.animations = [];
  40624. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40625. var animation = source.animations[animationIndex];
  40626. destination.animations.push(animation.serialize());
  40627. }
  40628. }
  40629. };
  40630. Animation.AllowMatricesInterpolation = false;
  40631. // Statics
  40632. Animation._ANIMATIONTYPE_FLOAT = 0;
  40633. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40634. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40635. Animation._ANIMATIONTYPE_MATRIX = 3;
  40636. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40637. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40638. Animation._ANIMATIONTYPE_SIZE = 6;
  40639. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40640. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40641. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40642. return Animation;
  40643. }());
  40644. BABYLON.Animation = Animation;
  40645. })(BABYLON || (BABYLON = {}));
  40646. //# sourceMappingURL=babylon.animation.js.map
  40647. var BABYLON;
  40648. (function (BABYLON) {
  40649. var RuntimeAnimation = /** @class */ (function () {
  40650. function RuntimeAnimation(target, animation) {
  40651. this._offsetsCache = {};
  40652. this._highLimitsCache = {};
  40653. this._stopped = false;
  40654. this._blendingFactor = 0;
  40655. this._ratioOffset = 0;
  40656. this._animation = animation;
  40657. this._target = target;
  40658. animation._runtimeAnimations.push(this);
  40659. }
  40660. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40661. get: function () {
  40662. return this._animation;
  40663. },
  40664. enumerable: true,
  40665. configurable: true
  40666. });
  40667. RuntimeAnimation.prototype.reset = function () {
  40668. this._offsetsCache = {};
  40669. this._highLimitsCache = {};
  40670. this.currentFrame = 0;
  40671. this._blendingFactor = 0;
  40672. this._originalBlendValue = null;
  40673. };
  40674. RuntimeAnimation.prototype.isStopped = function () {
  40675. return this._stopped;
  40676. };
  40677. RuntimeAnimation.prototype.dispose = function () {
  40678. var index = this._animation.runtimeAnimations.indexOf(this);
  40679. if (index > -1) {
  40680. this._animation.runtimeAnimations.splice(index, 1);
  40681. }
  40682. };
  40683. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40684. if (typeof value === "function") {
  40685. return value();
  40686. }
  40687. return value;
  40688. };
  40689. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40690. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40691. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40692. }
  40693. this.currentFrame = currentFrame;
  40694. var keys = this._animation.getKeys();
  40695. // Try to get a hash to find the right key
  40696. 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));
  40697. if (keys[startKeyIndex].frame >= currentFrame) {
  40698. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40699. startKeyIndex--;
  40700. }
  40701. }
  40702. for (var key = startKeyIndex; key < keys.length; key++) {
  40703. var endKey = keys[key + 1];
  40704. if (endKey.frame >= currentFrame) {
  40705. var startKey = keys[key];
  40706. var startValue = this._getKeyValue(startKey.value);
  40707. var endValue = this._getKeyValue(endKey.value);
  40708. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40709. var frameDelta = endKey.frame - startKey.frame;
  40710. // gradient : percent of currentFrame between the frame inf and the frame sup
  40711. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40712. // check for easingFunction and correction of gradient
  40713. var easingFunction = this._animation.getEasingFunction();
  40714. if (easingFunction != null) {
  40715. gradient = easingFunction.ease(gradient);
  40716. }
  40717. switch (this._animation.dataType) {
  40718. // Float
  40719. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40720. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40721. switch (loopMode) {
  40722. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40723. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40724. return floatValue;
  40725. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40726. return offsetValue * repeatCount + floatValue;
  40727. }
  40728. break;
  40729. // Quaternion
  40730. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40731. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40732. switch (loopMode) {
  40733. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40734. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40735. return quatValue;
  40736. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40737. return quatValue.add(offsetValue.scale(repeatCount));
  40738. }
  40739. return quatValue;
  40740. // Vector3
  40741. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40742. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40743. switch (loopMode) {
  40744. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40745. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40746. return vec3Value;
  40747. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40748. return vec3Value.add(offsetValue.scale(repeatCount));
  40749. }
  40750. // Vector2
  40751. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40752. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40753. switch (loopMode) {
  40754. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40755. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40756. return vec2Value;
  40757. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40758. return vec2Value.add(offsetValue.scale(repeatCount));
  40759. }
  40760. // Size
  40761. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40762. switch (loopMode) {
  40763. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40764. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40765. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40766. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40767. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40768. }
  40769. // Color3
  40770. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40771. switch (loopMode) {
  40772. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40773. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40774. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40775. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40776. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40777. }
  40778. // Matrix
  40779. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40780. switch (loopMode) {
  40781. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40782. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40783. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40784. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40785. }
  40786. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40787. return startValue;
  40788. }
  40789. default:
  40790. break;
  40791. }
  40792. break;
  40793. }
  40794. }
  40795. return this._getKeyValue(keys[keys.length - 1].value);
  40796. };
  40797. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40798. if (blend === void 0) { blend = false; }
  40799. // Set value
  40800. var path;
  40801. var destination;
  40802. var targetPropertyPath = this._animation.targetPropertyPath;
  40803. if (targetPropertyPath.length > 1) {
  40804. var property = this._target[targetPropertyPath[0]];
  40805. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40806. property = property[targetPropertyPath[index]];
  40807. }
  40808. path = targetPropertyPath[targetPropertyPath.length - 1];
  40809. destination = property;
  40810. }
  40811. else {
  40812. path = targetPropertyPath[0];
  40813. destination = this._target;
  40814. }
  40815. // Blending
  40816. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40817. if (!this._originalBlendValue) {
  40818. if (destination[path].clone) {
  40819. this._originalBlendValue = destination[path].clone();
  40820. }
  40821. else {
  40822. this._originalBlendValue = destination[path];
  40823. }
  40824. }
  40825. if (this._originalBlendValue.prototype) {
  40826. if (this._originalBlendValue.prototype.Lerp) {
  40827. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40828. }
  40829. else {
  40830. destination[path] = currentValue;
  40831. }
  40832. }
  40833. else if (this._originalBlendValue.m) {
  40834. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40835. }
  40836. else {
  40837. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40838. }
  40839. this._blendingFactor += this._animation.blendingSpeed;
  40840. }
  40841. else {
  40842. destination[path] = currentValue;
  40843. }
  40844. if (this._target.markAsDirty) {
  40845. this._target.markAsDirty(this._animation.targetProperty);
  40846. }
  40847. };
  40848. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40849. var keys = this._animation.getKeys();
  40850. if (frame < keys[0].frame) {
  40851. frame = keys[0].frame;
  40852. }
  40853. else if (frame > keys[keys.length - 1].frame) {
  40854. frame = keys[keys.length - 1].frame;
  40855. }
  40856. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40857. this.setValue(currentValue);
  40858. };
  40859. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40860. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40861. this._ratioOffset = this._previousRatio - newRatio;
  40862. };
  40863. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40864. if (blend === void 0) { blend = false; }
  40865. var targetPropertyPath = this._animation.targetPropertyPath;
  40866. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40867. this._stopped = true;
  40868. return false;
  40869. }
  40870. var returnValue = true;
  40871. var keys = this._animation.getKeys();
  40872. // Adding a start key at frame 0 if missing
  40873. if (keys[0].frame !== 0) {
  40874. var newKey = { frame: 0, value: keys[0].value };
  40875. keys.splice(0, 0, newKey);
  40876. }
  40877. // Check limits
  40878. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40879. from = keys[0].frame;
  40880. }
  40881. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40882. to = keys[keys.length - 1].frame;
  40883. }
  40884. //to and from cannot be the same key
  40885. if (from === to) {
  40886. if (from > keys[0].frame) {
  40887. from--;
  40888. }
  40889. else if (to < keys[keys.length - 1].frame) {
  40890. to++;
  40891. }
  40892. }
  40893. // Compute ratio
  40894. var range = to - from;
  40895. var offsetValue;
  40896. // ratio represents the frame delta between from and to
  40897. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40898. var highLimitValue = 0;
  40899. this._previousDelay = delay;
  40900. this._previousRatio = ratio;
  40901. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40902. returnValue = false;
  40903. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40904. }
  40905. else {
  40906. // Get max value if required
  40907. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40908. var keyOffset = to.toString() + from.toString();
  40909. if (!this._offsetsCache[keyOffset]) {
  40910. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40911. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40912. switch (this._animation.dataType) {
  40913. // Float
  40914. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40915. this._offsetsCache[keyOffset] = toValue - fromValue;
  40916. break;
  40917. // Quaternion
  40918. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40919. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40920. break;
  40921. // Vector3
  40922. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40923. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40924. // Vector2
  40925. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40926. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40927. // Size
  40928. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40929. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40930. // Color3
  40931. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40932. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40933. default:
  40934. break;
  40935. }
  40936. this._highLimitsCache[keyOffset] = toValue;
  40937. }
  40938. highLimitValue = this._highLimitsCache[keyOffset];
  40939. offsetValue = this._offsetsCache[keyOffset];
  40940. }
  40941. }
  40942. if (offsetValue === undefined) {
  40943. switch (this._animation.dataType) {
  40944. // Float
  40945. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40946. offsetValue = 0;
  40947. break;
  40948. // Quaternion
  40949. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40950. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40951. break;
  40952. // Vector3
  40953. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40954. offsetValue = BABYLON.Vector3.Zero();
  40955. break;
  40956. // Vector2
  40957. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40958. offsetValue = BABYLON.Vector2.Zero();
  40959. break;
  40960. // Size
  40961. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40962. offsetValue = BABYLON.Size.Zero();
  40963. break;
  40964. // Color3
  40965. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40966. offsetValue = BABYLON.Color3.Black();
  40967. }
  40968. }
  40969. // Compute value
  40970. var repeatCount = (ratio / range) >> 0;
  40971. var currentFrame = returnValue ? from + ratio % range : to;
  40972. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40973. // Set value
  40974. this.setValue(currentValue);
  40975. // Check events
  40976. var events = this._animation.getEvents();
  40977. for (var index = 0; index < events.length; index++) {
  40978. // Make sure current frame has passed event frame and that event frame is within the current range
  40979. // Also, handle both forward and reverse animations
  40980. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40981. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40982. var event = events[index];
  40983. if (!event.isDone) {
  40984. // If event should be done only once, remove it.
  40985. if (event.onlyOnce) {
  40986. events.splice(index, 1);
  40987. index--;
  40988. }
  40989. event.isDone = true;
  40990. event.action();
  40991. } // Don't do anything if the event has already be done.
  40992. }
  40993. else if (events[index].isDone && !events[index].onlyOnce) {
  40994. // reset event, the animation is looping
  40995. events[index].isDone = false;
  40996. }
  40997. }
  40998. if (!returnValue) {
  40999. this._stopped = true;
  41000. }
  41001. return returnValue;
  41002. };
  41003. return RuntimeAnimation;
  41004. }());
  41005. BABYLON.RuntimeAnimation = RuntimeAnimation;
  41006. })(BABYLON || (BABYLON = {}));
  41007. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  41008. var BABYLON;
  41009. (function (BABYLON) {
  41010. var Animatable = /** @class */ (function () {
  41011. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  41012. if (fromFrame === void 0) { fromFrame = 0; }
  41013. if (toFrame === void 0) { toFrame = 100; }
  41014. if (loopAnimation === void 0) { loopAnimation = false; }
  41015. if (speedRatio === void 0) { speedRatio = 1.0; }
  41016. this.target = target;
  41017. this.fromFrame = fromFrame;
  41018. this.toFrame = toFrame;
  41019. this.loopAnimation = loopAnimation;
  41020. this.onAnimationEnd = onAnimationEnd;
  41021. this._localDelayOffset = null;
  41022. this._pausedDelay = null;
  41023. this._runtimeAnimations = new Array();
  41024. this._paused = false;
  41025. this._speedRatio = 1;
  41026. this.animationStarted = false;
  41027. if (animations) {
  41028. this.appendAnimations(target, animations);
  41029. }
  41030. this._speedRatio = speedRatio;
  41031. this._scene = scene;
  41032. scene._activeAnimatables.push(this);
  41033. }
  41034. Object.defineProperty(Animatable.prototype, "speedRatio", {
  41035. get: function () {
  41036. return this._speedRatio;
  41037. },
  41038. set: function (value) {
  41039. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  41040. var animation = this._runtimeAnimations[index];
  41041. animation._prepareForSpeedRatioChange(value);
  41042. }
  41043. this._speedRatio = value;
  41044. },
  41045. enumerable: true,
  41046. configurable: true
  41047. });
  41048. // Methods
  41049. Animatable.prototype.getAnimations = function () {
  41050. return this._runtimeAnimations;
  41051. };
  41052. Animatable.prototype.appendAnimations = function (target, animations) {
  41053. for (var index = 0; index < animations.length; index++) {
  41054. var animation = animations[index];
  41055. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  41056. }
  41057. };
  41058. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  41059. var runtimeAnimations = this._runtimeAnimations;
  41060. for (var index = 0; index < runtimeAnimations.length; index++) {
  41061. if (runtimeAnimations[index].animation.targetProperty === property) {
  41062. return runtimeAnimations[index].animation;
  41063. }
  41064. }
  41065. return null;
  41066. };
  41067. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  41068. var runtimeAnimations = this._runtimeAnimations;
  41069. for (var index = 0; index < runtimeAnimations.length; index++) {
  41070. if (runtimeAnimations[index].animation.targetProperty === property) {
  41071. return runtimeAnimations[index];
  41072. }
  41073. }
  41074. return null;
  41075. };
  41076. Animatable.prototype.reset = function () {
  41077. var runtimeAnimations = this._runtimeAnimations;
  41078. for (var index = 0; index < runtimeAnimations.length; index++) {
  41079. runtimeAnimations[index].reset();
  41080. }
  41081. this._localDelayOffset = null;
  41082. this._pausedDelay = null;
  41083. };
  41084. Animatable.prototype.enableBlending = function (blendingSpeed) {
  41085. var runtimeAnimations = this._runtimeAnimations;
  41086. for (var index = 0; index < runtimeAnimations.length; index++) {
  41087. runtimeAnimations[index].animation.enableBlending = true;
  41088. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  41089. }
  41090. };
  41091. Animatable.prototype.disableBlending = function () {
  41092. var runtimeAnimations = this._runtimeAnimations;
  41093. for (var index = 0; index < runtimeAnimations.length; index++) {
  41094. runtimeAnimations[index].animation.enableBlending = false;
  41095. }
  41096. };
  41097. Animatable.prototype.goToFrame = function (frame) {
  41098. var runtimeAnimations = this._runtimeAnimations;
  41099. if (runtimeAnimations[0]) {
  41100. var fps = runtimeAnimations[0].animation.framePerSecond;
  41101. var currentFrame = runtimeAnimations[0].currentFrame;
  41102. var adjustTime = frame - currentFrame;
  41103. var delay = adjustTime * 1000 / fps;
  41104. if (this._localDelayOffset === null) {
  41105. this._localDelayOffset = 0;
  41106. }
  41107. this._localDelayOffset -= delay;
  41108. }
  41109. for (var index = 0; index < runtimeAnimations.length; index++) {
  41110. runtimeAnimations[index].goToFrame(frame);
  41111. }
  41112. };
  41113. Animatable.prototype.pause = function () {
  41114. if (this._paused) {
  41115. return;
  41116. }
  41117. this._paused = true;
  41118. };
  41119. Animatable.prototype.restart = function () {
  41120. this._paused = false;
  41121. };
  41122. Animatable.prototype.stop = function (animationName) {
  41123. if (animationName) {
  41124. var idx = this._scene._activeAnimatables.indexOf(this);
  41125. if (idx > -1) {
  41126. var runtimeAnimations = this._runtimeAnimations;
  41127. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  41128. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  41129. continue;
  41130. }
  41131. runtimeAnimations[index].dispose();
  41132. runtimeAnimations.splice(index, 1);
  41133. }
  41134. if (runtimeAnimations.length == 0) {
  41135. this._scene._activeAnimatables.splice(idx, 1);
  41136. if (this.onAnimationEnd) {
  41137. this.onAnimationEnd();
  41138. }
  41139. }
  41140. }
  41141. }
  41142. else {
  41143. var index = this._scene._activeAnimatables.indexOf(this);
  41144. if (index > -1) {
  41145. this._scene._activeAnimatables.splice(index, 1);
  41146. var runtimeAnimations = this._runtimeAnimations;
  41147. for (var index = 0; index < runtimeAnimations.length; index++) {
  41148. runtimeAnimations[index].dispose();
  41149. }
  41150. if (this.onAnimationEnd) {
  41151. this.onAnimationEnd();
  41152. }
  41153. }
  41154. }
  41155. };
  41156. Animatable.prototype._animate = function (delay) {
  41157. if (this._paused) {
  41158. this.animationStarted = false;
  41159. if (this._pausedDelay === null) {
  41160. this._pausedDelay = delay;
  41161. }
  41162. return true;
  41163. }
  41164. if (this._localDelayOffset === null) {
  41165. this._localDelayOffset = delay;
  41166. }
  41167. else if (this._pausedDelay !== null) {
  41168. this._localDelayOffset += delay - this._pausedDelay;
  41169. this._pausedDelay = null;
  41170. }
  41171. // Animating
  41172. var running = false;
  41173. var runtimeAnimations = this._runtimeAnimations;
  41174. var index;
  41175. for (index = 0; index < runtimeAnimations.length; index++) {
  41176. var animation = runtimeAnimations[index];
  41177. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  41178. running = running || isRunning;
  41179. }
  41180. this.animationStarted = running;
  41181. if (!running) {
  41182. // Remove from active animatables
  41183. index = this._scene._activeAnimatables.indexOf(this);
  41184. this._scene._activeAnimatables.splice(index, 1);
  41185. // Dispose all runtime animations
  41186. for (index = 0; index < runtimeAnimations.length; index++) {
  41187. runtimeAnimations[index].dispose();
  41188. }
  41189. }
  41190. if (!running && this.onAnimationEnd) {
  41191. this.onAnimationEnd();
  41192. this.onAnimationEnd = null;
  41193. }
  41194. return running;
  41195. };
  41196. return Animatable;
  41197. }());
  41198. BABYLON.Animatable = Animatable;
  41199. })(BABYLON || (BABYLON = {}));
  41200. //# sourceMappingURL=babylon.animatable.js.map
  41201. var BABYLON;
  41202. (function (BABYLON) {
  41203. var EasingFunction = /** @class */ (function () {
  41204. function EasingFunction() {
  41205. // Properties
  41206. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41207. }
  41208. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41209. get: function () {
  41210. return EasingFunction._EASINGMODE_EASEIN;
  41211. },
  41212. enumerable: true,
  41213. configurable: true
  41214. });
  41215. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41216. get: function () {
  41217. return EasingFunction._EASINGMODE_EASEOUT;
  41218. },
  41219. enumerable: true,
  41220. configurable: true
  41221. });
  41222. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41223. get: function () {
  41224. return EasingFunction._EASINGMODE_EASEINOUT;
  41225. },
  41226. enumerable: true,
  41227. configurable: true
  41228. });
  41229. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41230. var n = Math.min(Math.max(easingMode, 0), 2);
  41231. this._easingMode = n;
  41232. };
  41233. EasingFunction.prototype.getEasingMode = function () {
  41234. return this._easingMode;
  41235. };
  41236. EasingFunction.prototype.easeInCore = function (gradient) {
  41237. throw new Error('You must implement this method');
  41238. };
  41239. EasingFunction.prototype.ease = function (gradient) {
  41240. switch (this._easingMode) {
  41241. case EasingFunction.EASINGMODE_EASEIN:
  41242. return this.easeInCore(gradient);
  41243. case EasingFunction.EASINGMODE_EASEOUT:
  41244. return (1 - this.easeInCore(1 - gradient));
  41245. }
  41246. if (gradient >= 0.5) {
  41247. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41248. }
  41249. return (this.easeInCore(gradient * 2) * 0.5);
  41250. };
  41251. //Statics
  41252. EasingFunction._EASINGMODE_EASEIN = 0;
  41253. EasingFunction._EASINGMODE_EASEOUT = 1;
  41254. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41255. return EasingFunction;
  41256. }());
  41257. BABYLON.EasingFunction = EasingFunction;
  41258. var CircleEase = /** @class */ (function (_super) {
  41259. __extends(CircleEase, _super);
  41260. function CircleEase() {
  41261. return _super !== null && _super.apply(this, arguments) || this;
  41262. }
  41263. CircleEase.prototype.easeInCore = function (gradient) {
  41264. gradient = Math.max(0, Math.min(1, gradient));
  41265. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41266. };
  41267. return CircleEase;
  41268. }(EasingFunction));
  41269. BABYLON.CircleEase = CircleEase;
  41270. var BackEase = /** @class */ (function (_super) {
  41271. __extends(BackEase, _super);
  41272. function BackEase(amplitude) {
  41273. if (amplitude === void 0) { amplitude = 1; }
  41274. var _this = _super.call(this) || this;
  41275. _this.amplitude = amplitude;
  41276. return _this;
  41277. }
  41278. BackEase.prototype.easeInCore = function (gradient) {
  41279. var num = Math.max(0, this.amplitude);
  41280. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41281. };
  41282. return BackEase;
  41283. }(EasingFunction));
  41284. BABYLON.BackEase = BackEase;
  41285. var BounceEase = /** @class */ (function (_super) {
  41286. __extends(BounceEase, _super);
  41287. function BounceEase(bounces, bounciness) {
  41288. if (bounces === void 0) { bounces = 3; }
  41289. if (bounciness === void 0) { bounciness = 2; }
  41290. var _this = _super.call(this) || this;
  41291. _this.bounces = bounces;
  41292. _this.bounciness = bounciness;
  41293. return _this;
  41294. }
  41295. BounceEase.prototype.easeInCore = function (gradient) {
  41296. var y = Math.max(0.0, this.bounces);
  41297. var bounciness = this.bounciness;
  41298. if (bounciness <= 1.0) {
  41299. bounciness = 1.001;
  41300. }
  41301. var num9 = Math.pow(bounciness, y);
  41302. var num5 = 1.0 - bounciness;
  41303. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41304. var num15 = gradient * num4;
  41305. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41306. var num3 = Math.floor(num65);
  41307. var num13 = num3 + 1.0;
  41308. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41309. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41310. var num7 = (num8 + num12) * 0.5;
  41311. var num6 = gradient - num7;
  41312. var num2 = num7 - num8;
  41313. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41314. };
  41315. return BounceEase;
  41316. }(EasingFunction));
  41317. BABYLON.BounceEase = BounceEase;
  41318. var CubicEase = /** @class */ (function (_super) {
  41319. __extends(CubicEase, _super);
  41320. function CubicEase() {
  41321. return _super !== null && _super.apply(this, arguments) || this;
  41322. }
  41323. CubicEase.prototype.easeInCore = function (gradient) {
  41324. return (gradient * gradient * gradient);
  41325. };
  41326. return CubicEase;
  41327. }(EasingFunction));
  41328. BABYLON.CubicEase = CubicEase;
  41329. var ElasticEase = /** @class */ (function (_super) {
  41330. __extends(ElasticEase, _super);
  41331. function ElasticEase(oscillations, springiness) {
  41332. if (oscillations === void 0) { oscillations = 3; }
  41333. if (springiness === void 0) { springiness = 3; }
  41334. var _this = _super.call(this) || this;
  41335. _this.oscillations = oscillations;
  41336. _this.springiness = springiness;
  41337. return _this;
  41338. }
  41339. ElasticEase.prototype.easeInCore = function (gradient) {
  41340. var num2;
  41341. var num3 = Math.max(0.0, this.oscillations);
  41342. var num = Math.max(0.0, this.springiness);
  41343. if (num == 0) {
  41344. num2 = gradient;
  41345. }
  41346. else {
  41347. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41348. }
  41349. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41350. };
  41351. return ElasticEase;
  41352. }(EasingFunction));
  41353. BABYLON.ElasticEase = ElasticEase;
  41354. var ExponentialEase = /** @class */ (function (_super) {
  41355. __extends(ExponentialEase, _super);
  41356. function ExponentialEase(exponent) {
  41357. if (exponent === void 0) { exponent = 2; }
  41358. var _this = _super.call(this) || this;
  41359. _this.exponent = exponent;
  41360. return _this;
  41361. }
  41362. ExponentialEase.prototype.easeInCore = function (gradient) {
  41363. if (this.exponent <= 0) {
  41364. return gradient;
  41365. }
  41366. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41367. };
  41368. return ExponentialEase;
  41369. }(EasingFunction));
  41370. BABYLON.ExponentialEase = ExponentialEase;
  41371. var PowerEase = /** @class */ (function (_super) {
  41372. __extends(PowerEase, _super);
  41373. function PowerEase(power) {
  41374. if (power === void 0) { power = 2; }
  41375. var _this = _super.call(this) || this;
  41376. _this.power = power;
  41377. return _this;
  41378. }
  41379. PowerEase.prototype.easeInCore = function (gradient) {
  41380. var y = Math.max(0.0, this.power);
  41381. return Math.pow(gradient, y);
  41382. };
  41383. return PowerEase;
  41384. }(EasingFunction));
  41385. BABYLON.PowerEase = PowerEase;
  41386. var QuadraticEase = /** @class */ (function (_super) {
  41387. __extends(QuadraticEase, _super);
  41388. function QuadraticEase() {
  41389. return _super !== null && _super.apply(this, arguments) || this;
  41390. }
  41391. QuadraticEase.prototype.easeInCore = function (gradient) {
  41392. return (gradient * gradient);
  41393. };
  41394. return QuadraticEase;
  41395. }(EasingFunction));
  41396. BABYLON.QuadraticEase = QuadraticEase;
  41397. var QuarticEase = /** @class */ (function (_super) {
  41398. __extends(QuarticEase, _super);
  41399. function QuarticEase() {
  41400. return _super !== null && _super.apply(this, arguments) || this;
  41401. }
  41402. QuarticEase.prototype.easeInCore = function (gradient) {
  41403. return (gradient * gradient * gradient * gradient);
  41404. };
  41405. return QuarticEase;
  41406. }(EasingFunction));
  41407. BABYLON.QuarticEase = QuarticEase;
  41408. var QuinticEase = /** @class */ (function (_super) {
  41409. __extends(QuinticEase, _super);
  41410. function QuinticEase() {
  41411. return _super !== null && _super.apply(this, arguments) || this;
  41412. }
  41413. QuinticEase.prototype.easeInCore = function (gradient) {
  41414. return (gradient * gradient * gradient * gradient * gradient);
  41415. };
  41416. return QuinticEase;
  41417. }(EasingFunction));
  41418. BABYLON.QuinticEase = QuinticEase;
  41419. var SineEase = /** @class */ (function (_super) {
  41420. __extends(SineEase, _super);
  41421. function SineEase() {
  41422. return _super !== null && _super.apply(this, arguments) || this;
  41423. }
  41424. SineEase.prototype.easeInCore = function (gradient) {
  41425. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41426. };
  41427. return SineEase;
  41428. }(EasingFunction));
  41429. BABYLON.SineEase = SineEase;
  41430. var BezierCurveEase = /** @class */ (function (_super) {
  41431. __extends(BezierCurveEase, _super);
  41432. function BezierCurveEase(x1, y1, x2, y2) {
  41433. if (x1 === void 0) { x1 = 0; }
  41434. if (y1 === void 0) { y1 = 0; }
  41435. if (x2 === void 0) { x2 = 1; }
  41436. if (y2 === void 0) { y2 = 1; }
  41437. var _this = _super.call(this) || this;
  41438. _this.x1 = x1;
  41439. _this.y1 = y1;
  41440. _this.x2 = x2;
  41441. _this.y2 = y2;
  41442. return _this;
  41443. }
  41444. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41445. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41446. };
  41447. return BezierCurveEase;
  41448. }(EasingFunction));
  41449. BABYLON.BezierCurveEase = BezierCurveEase;
  41450. })(BABYLON || (BABYLON = {}));
  41451. //# sourceMappingURL=babylon.easing.js.map
  41452. var BABYLON;
  41453. (function (BABYLON) {
  41454. var Condition = /** @class */ (function () {
  41455. function Condition(actionManager) {
  41456. this._actionManager = actionManager;
  41457. }
  41458. Condition.prototype.isValid = function () {
  41459. return true;
  41460. };
  41461. Condition.prototype._getProperty = function (propertyPath) {
  41462. return this._actionManager._getProperty(propertyPath);
  41463. };
  41464. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41465. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41466. };
  41467. Condition.prototype.serialize = function () {
  41468. };
  41469. Condition.prototype._serialize = function (serializedCondition) {
  41470. return {
  41471. type: 2,
  41472. children: [],
  41473. name: serializedCondition.name,
  41474. properties: serializedCondition.properties
  41475. };
  41476. };
  41477. return Condition;
  41478. }());
  41479. BABYLON.Condition = Condition;
  41480. var ValueCondition = /** @class */ (function (_super) {
  41481. __extends(ValueCondition, _super);
  41482. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41483. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41484. var _this = _super.call(this, actionManager) || this;
  41485. _this.propertyPath = propertyPath;
  41486. _this.value = value;
  41487. _this.operator = operator;
  41488. _this._target = target;
  41489. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41490. _this._property = _this._getProperty(_this.propertyPath);
  41491. return _this;
  41492. }
  41493. Object.defineProperty(ValueCondition, "IsEqual", {
  41494. get: function () {
  41495. return ValueCondition._IsEqual;
  41496. },
  41497. enumerable: true,
  41498. configurable: true
  41499. });
  41500. Object.defineProperty(ValueCondition, "IsDifferent", {
  41501. get: function () {
  41502. return ValueCondition._IsDifferent;
  41503. },
  41504. enumerable: true,
  41505. configurable: true
  41506. });
  41507. Object.defineProperty(ValueCondition, "IsGreater", {
  41508. get: function () {
  41509. return ValueCondition._IsGreater;
  41510. },
  41511. enumerable: true,
  41512. configurable: true
  41513. });
  41514. Object.defineProperty(ValueCondition, "IsLesser", {
  41515. get: function () {
  41516. return ValueCondition._IsLesser;
  41517. },
  41518. enumerable: true,
  41519. configurable: true
  41520. });
  41521. // Methods
  41522. ValueCondition.prototype.isValid = function () {
  41523. switch (this.operator) {
  41524. case ValueCondition.IsGreater:
  41525. return this._effectiveTarget[this._property] > this.value;
  41526. case ValueCondition.IsLesser:
  41527. return this._effectiveTarget[this._property] < this.value;
  41528. case ValueCondition.IsEqual:
  41529. case ValueCondition.IsDifferent:
  41530. var check;
  41531. if (this.value.equals) {
  41532. check = this.value.equals(this._effectiveTarget[this._property]);
  41533. }
  41534. else {
  41535. check = this.value === this._effectiveTarget[this._property];
  41536. }
  41537. return this.operator === ValueCondition.IsEqual ? check : !check;
  41538. }
  41539. return false;
  41540. };
  41541. ValueCondition.prototype.serialize = function () {
  41542. return this._serialize({
  41543. name: "ValueCondition",
  41544. properties: [
  41545. BABYLON.Action._GetTargetProperty(this._target),
  41546. { name: "propertyPath", value: this.propertyPath },
  41547. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41548. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41549. ]
  41550. });
  41551. };
  41552. ValueCondition.GetOperatorName = function (operator) {
  41553. switch (operator) {
  41554. case ValueCondition._IsEqual: return "IsEqual";
  41555. case ValueCondition._IsDifferent: return "IsDifferent";
  41556. case ValueCondition._IsGreater: return "IsGreater";
  41557. case ValueCondition._IsLesser: return "IsLesser";
  41558. default: return "";
  41559. }
  41560. };
  41561. // Statics
  41562. ValueCondition._IsEqual = 0;
  41563. ValueCondition._IsDifferent = 1;
  41564. ValueCondition._IsGreater = 2;
  41565. ValueCondition._IsLesser = 3;
  41566. return ValueCondition;
  41567. }(Condition));
  41568. BABYLON.ValueCondition = ValueCondition;
  41569. var PredicateCondition = /** @class */ (function (_super) {
  41570. __extends(PredicateCondition, _super);
  41571. function PredicateCondition(actionManager, predicate) {
  41572. var _this = _super.call(this, actionManager) || this;
  41573. _this.predicate = predicate;
  41574. return _this;
  41575. }
  41576. PredicateCondition.prototype.isValid = function () {
  41577. return this.predicate();
  41578. };
  41579. return PredicateCondition;
  41580. }(Condition));
  41581. BABYLON.PredicateCondition = PredicateCondition;
  41582. var StateCondition = /** @class */ (function (_super) {
  41583. __extends(StateCondition, _super);
  41584. function StateCondition(actionManager, target, value) {
  41585. var _this = _super.call(this, actionManager) || this;
  41586. _this.value = value;
  41587. _this._target = target;
  41588. return _this;
  41589. }
  41590. // Methods
  41591. StateCondition.prototype.isValid = function () {
  41592. return this._target.state === this.value;
  41593. };
  41594. StateCondition.prototype.serialize = function () {
  41595. return this._serialize({
  41596. name: "StateCondition",
  41597. properties: [
  41598. BABYLON.Action._GetTargetProperty(this._target),
  41599. { name: "value", value: this.value }
  41600. ]
  41601. });
  41602. };
  41603. return StateCondition;
  41604. }(Condition));
  41605. BABYLON.StateCondition = StateCondition;
  41606. })(BABYLON || (BABYLON = {}));
  41607. //# sourceMappingURL=babylon.condition.js.map
  41608. var BABYLON;
  41609. (function (BABYLON) {
  41610. var Action = /** @class */ (function () {
  41611. function Action(triggerOptions, condition) {
  41612. this.triggerOptions = triggerOptions;
  41613. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41614. if (triggerOptions.parameter) {
  41615. this.trigger = triggerOptions.trigger;
  41616. this._triggerParameter = triggerOptions.parameter;
  41617. }
  41618. else {
  41619. this.trigger = triggerOptions;
  41620. }
  41621. this._nextActiveAction = this;
  41622. this._condition = condition;
  41623. }
  41624. // Methods
  41625. Action.prototype._prepare = function () {
  41626. };
  41627. Action.prototype.getTriggerParameter = function () {
  41628. return this._triggerParameter;
  41629. };
  41630. Action.prototype._executeCurrent = function (evt) {
  41631. if (this._nextActiveAction._condition) {
  41632. var condition = this._nextActiveAction._condition;
  41633. var currentRenderId = this._actionManager.getScene().getRenderId();
  41634. // We cache the current evaluation for the current frame
  41635. if (condition._evaluationId === currentRenderId) {
  41636. if (!condition._currentResult) {
  41637. return;
  41638. }
  41639. }
  41640. else {
  41641. condition._evaluationId = currentRenderId;
  41642. if (!condition.isValid()) {
  41643. condition._currentResult = false;
  41644. return;
  41645. }
  41646. condition._currentResult = true;
  41647. }
  41648. }
  41649. this.onBeforeExecuteObservable.notifyObservers(this);
  41650. this._nextActiveAction.execute(evt);
  41651. this.skipToNextActiveAction();
  41652. };
  41653. Action.prototype.execute = function (evt) {
  41654. };
  41655. Action.prototype.skipToNextActiveAction = function () {
  41656. if (this._nextActiveAction._child) {
  41657. if (!this._nextActiveAction._child._actionManager) {
  41658. this._nextActiveAction._child._actionManager = this._actionManager;
  41659. }
  41660. this._nextActiveAction = this._nextActiveAction._child;
  41661. }
  41662. else {
  41663. this._nextActiveAction = this;
  41664. }
  41665. };
  41666. Action.prototype.then = function (action) {
  41667. this._child = action;
  41668. action._actionManager = this._actionManager;
  41669. action._prepare();
  41670. return action;
  41671. };
  41672. Action.prototype._getProperty = function (propertyPath) {
  41673. return this._actionManager._getProperty(propertyPath);
  41674. };
  41675. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41676. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41677. };
  41678. Action.prototype.serialize = function (parent) {
  41679. };
  41680. // Called by BABYLON.Action objects in serialize(...). Internal use
  41681. Action.prototype._serialize = function (serializedAction, parent) {
  41682. var serializationObject = {
  41683. type: 1,
  41684. children: [],
  41685. name: serializedAction.name,
  41686. properties: serializedAction.properties || []
  41687. };
  41688. // Serialize child
  41689. if (this._child) {
  41690. this._child.serialize(serializationObject);
  41691. }
  41692. // Check if "this" has a condition
  41693. if (this._condition) {
  41694. var serializedCondition = this._condition.serialize();
  41695. serializedCondition.children.push(serializationObject);
  41696. if (parent) {
  41697. parent.children.push(serializedCondition);
  41698. }
  41699. return serializedCondition;
  41700. }
  41701. if (parent) {
  41702. parent.children.push(serializationObject);
  41703. }
  41704. return serializationObject;
  41705. };
  41706. Action._SerializeValueAsString = function (value) {
  41707. if (typeof value === "number") {
  41708. return value.toString();
  41709. }
  41710. if (typeof value === "boolean") {
  41711. return value ? "true" : "false";
  41712. }
  41713. if (value instanceof BABYLON.Vector2) {
  41714. return value.x + ", " + value.y;
  41715. }
  41716. if (value instanceof BABYLON.Vector3) {
  41717. return value.x + ", " + value.y + ", " + value.z;
  41718. }
  41719. if (value instanceof BABYLON.Color3) {
  41720. return value.r + ", " + value.g + ", " + value.b;
  41721. }
  41722. if (value instanceof BABYLON.Color4) {
  41723. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41724. }
  41725. return value; // string
  41726. };
  41727. Action._GetTargetProperty = function (target) {
  41728. return {
  41729. name: "target",
  41730. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41731. : target instanceof BABYLON.Light ? "LightProperties"
  41732. : target instanceof BABYLON.Camera ? "CameraProperties"
  41733. : "SceneProperties",
  41734. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41735. };
  41736. };
  41737. return Action;
  41738. }());
  41739. BABYLON.Action = Action;
  41740. })(BABYLON || (BABYLON = {}));
  41741. //# sourceMappingURL=babylon.action.js.map
  41742. var BABYLON;
  41743. (function (BABYLON) {
  41744. /**
  41745. * ActionEvent is the event beint sent when an action is triggered.
  41746. */
  41747. var ActionEvent = /** @class */ (function () {
  41748. /**
  41749. * @param source The mesh or sprite that triggered the action.
  41750. * @param pointerX The X mouse cursor position at the time of the event
  41751. * @param pointerY The Y mouse cursor position at the time of the event
  41752. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41753. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41754. */
  41755. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41756. this.source = source;
  41757. this.pointerX = pointerX;
  41758. this.pointerY = pointerY;
  41759. this.meshUnderPointer = meshUnderPointer;
  41760. this.sourceEvent = sourceEvent;
  41761. this.additionalData = additionalData;
  41762. }
  41763. /**
  41764. * Helper function to auto-create an ActionEvent from a source mesh.
  41765. * @param source The source mesh that triggered the event
  41766. * @param evt {Event} The original (browser) event
  41767. */
  41768. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41769. var scene = source.getScene();
  41770. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41771. };
  41772. /**
  41773. * Helper function to auto-create an ActionEvent from a source mesh.
  41774. * @param source The source sprite that triggered the event
  41775. * @param scene Scene associated with the sprite
  41776. * @param evt {Event} The original (browser) event
  41777. */
  41778. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41779. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41780. };
  41781. /**
  41782. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41783. * @param scene the scene where the event occurred
  41784. * @param evt {Event} The original (browser) event
  41785. */
  41786. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41787. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41788. };
  41789. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41790. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41791. };
  41792. return ActionEvent;
  41793. }());
  41794. BABYLON.ActionEvent = ActionEvent;
  41795. /**
  41796. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41797. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41798. */
  41799. var ActionManager = /** @class */ (function () {
  41800. function ActionManager(scene) {
  41801. // Members
  41802. this.actions = new Array();
  41803. this.hoverCursor = '';
  41804. this._scene = scene;
  41805. scene._actionManagers.push(this);
  41806. }
  41807. Object.defineProperty(ActionManager, "NothingTrigger", {
  41808. get: function () {
  41809. return ActionManager._NothingTrigger;
  41810. },
  41811. enumerable: true,
  41812. configurable: true
  41813. });
  41814. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41815. get: function () {
  41816. return ActionManager._OnPickTrigger;
  41817. },
  41818. enumerable: true,
  41819. configurable: true
  41820. });
  41821. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41822. get: function () {
  41823. return ActionManager._OnLeftPickTrigger;
  41824. },
  41825. enumerable: true,
  41826. configurable: true
  41827. });
  41828. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41829. get: function () {
  41830. return ActionManager._OnRightPickTrigger;
  41831. },
  41832. enumerable: true,
  41833. configurable: true
  41834. });
  41835. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41836. get: function () {
  41837. return ActionManager._OnCenterPickTrigger;
  41838. },
  41839. enumerable: true,
  41840. configurable: true
  41841. });
  41842. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41843. get: function () {
  41844. return ActionManager._OnPickDownTrigger;
  41845. },
  41846. enumerable: true,
  41847. configurable: true
  41848. });
  41849. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41850. get: function () {
  41851. return ActionManager._OnDoublePickTrigger;
  41852. },
  41853. enumerable: true,
  41854. configurable: true
  41855. });
  41856. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41857. get: function () {
  41858. return ActionManager._OnPickUpTrigger;
  41859. },
  41860. enumerable: true,
  41861. configurable: true
  41862. });
  41863. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41864. /// This trigger will only be raised if you also declared a OnPickDown
  41865. get: function () {
  41866. return ActionManager._OnPickOutTrigger;
  41867. },
  41868. enumerable: true,
  41869. configurable: true
  41870. });
  41871. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41872. get: function () {
  41873. return ActionManager._OnLongPressTrigger;
  41874. },
  41875. enumerable: true,
  41876. configurable: true
  41877. });
  41878. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41879. get: function () {
  41880. return ActionManager._OnPointerOverTrigger;
  41881. },
  41882. enumerable: true,
  41883. configurable: true
  41884. });
  41885. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41886. get: function () {
  41887. return ActionManager._OnPointerOutTrigger;
  41888. },
  41889. enumerable: true,
  41890. configurable: true
  41891. });
  41892. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41893. get: function () {
  41894. return ActionManager._OnEveryFrameTrigger;
  41895. },
  41896. enumerable: true,
  41897. configurable: true
  41898. });
  41899. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41900. get: function () {
  41901. return ActionManager._OnIntersectionEnterTrigger;
  41902. },
  41903. enumerable: true,
  41904. configurable: true
  41905. });
  41906. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41907. get: function () {
  41908. return ActionManager._OnIntersectionExitTrigger;
  41909. },
  41910. enumerable: true,
  41911. configurable: true
  41912. });
  41913. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41914. get: function () {
  41915. return ActionManager._OnKeyDownTrigger;
  41916. },
  41917. enumerable: true,
  41918. configurable: true
  41919. });
  41920. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41921. get: function () {
  41922. return ActionManager._OnKeyUpTrigger;
  41923. },
  41924. enumerable: true,
  41925. configurable: true
  41926. });
  41927. // Methods
  41928. ActionManager.prototype.dispose = function () {
  41929. var index = this._scene._actionManagers.indexOf(this);
  41930. for (var i = 0; i < this.actions.length; i++) {
  41931. var action = this.actions[i];
  41932. ActionManager.Triggers[action.trigger]--;
  41933. if (ActionManager.Triggers[action.trigger] === 0) {
  41934. delete ActionManager.Triggers[action.trigger];
  41935. }
  41936. }
  41937. if (index > -1) {
  41938. this._scene._actionManagers.splice(index, 1);
  41939. }
  41940. };
  41941. ActionManager.prototype.getScene = function () {
  41942. return this._scene;
  41943. };
  41944. /**
  41945. * Does this action manager handles actions of any of the given triggers
  41946. * @param {number[]} triggers - the triggers to be tested
  41947. * @return {boolean} whether one (or more) of the triggers is handeled
  41948. */
  41949. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41950. for (var index = 0; index < this.actions.length; index++) {
  41951. var action = this.actions[index];
  41952. if (triggers.indexOf(action.trigger) > -1) {
  41953. return true;
  41954. }
  41955. }
  41956. return false;
  41957. };
  41958. /**
  41959. * Does this action manager handles actions of a given trigger
  41960. * @param {number} trigger - the trigger to be tested
  41961. * @return {boolean} whether the trigger is handeled
  41962. */
  41963. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41964. for (var index = 0; index < this.actions.length; index++) {
  41965. var action = this.actions[index];
  41966. if (action.trigger === trigger) {
  41967. return true;
  41968. }
  41969. }
  41970. return false;
  41971. };
  41972. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41973. /**
  41974. * Does this action manager has pointer triggers
  41975. * @return {boolean} whether or not it has pointer triggers
  41976. */
  41977. get: function () {
  41978. for (var index = 0; index < this.actions.length; index++) {
  41979. var action = this.actions[index];
  41980. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41981. return true;
  41982. }
  41983. }
  41984. return false;
  41985. },
  41986. enumerable: true,
  41987. configurable: true
  41988. });
  41989. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41990. /**
  41991. * Does this action manager has pick triggers
  41992. * @return {boolean} whether or not it has pick triggers
  41993. */
  41994. get: function () {
  41995. for (var index = 0; index < this.actions.length; index++) {
  41996. var action = this.actions[index];
  41997. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41998. return true;
  41999. }
  42000. }
  42001. return false;
  42002. },
  42003. enumerable: true,
  42004. configurable: true
  42005. });
  42006. Object.defineProperty(ActionManager, "HasTriggers", {
  42007. /**
  42008. * Does exist one action manager with at least one trigger
  42009. * @return {boolean} whether or not it exists one action manager with one trigger
  42010. **/
  42011. get: function () {
  42012. for (var t in ActionManager.Triggers) {
  42013. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42014. return true;
  42015. }
  42016. }
  42017. return false;
  42018. },
  42019. enumerable: true,
  42020. configurable: true
  42021. });
  42022. Object.defineProperty(ActionManager, "HasPickTriggers", {
  42023. /**
  42024. * Does exist one action manager with at least one pick trigger
  42025. * @return {boolean} whether or not it exists one action manager with one pick trigger
  42026. **/
  42027. get: function () {
  42028. for (var t in ActionManager.Triggers) {
  42029. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42030. var t_int = parseInt(t);
  42031. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  42032. return true;
  42033. }
  42034. }
  42035. }
  42036. return false;
  42037. },
  42038. enumerable: true,
  42039. configurable: true
  42040. });
  42041. /**
  42042. * Does exist one action manager that handles actions of a given trigger
  42043. * @param {number} trigger - the trigger to be tested
  42044. * @return {boolean} whether the trigger is handeled by at least one action manager
  42045. **/
  42046. ActionManager.HasSpecificTrigger = function (trigger) {
  42047. for (var t in ActionManager.Triggers) {
  42048. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42049. var t_int = parseInt(t);
  42050. if (t_int === trigger) {
  42051. return true;
  42052. }
  42053. }
  42054. }
  42055. return false;
  42056. };
  42057. /**
  42058. * Registers an action to this action manager
  42059. * @param {BABYLON.Action} action - the action to be registered
  42060. * @return {BABYLON.Action} the action amended (prepared) after registration
  42061. */
  42062. ActionManager.prototype.registerAction = function (action) {
  42063. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  42064. if (this.getScene().actionManager !== this) {
  42065. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  42066. return null;
  42067. }
  42068. }
  42069. this.actions.push(action);
  42070. if (ActionManager.Triggers[action.trigger]) {
  42071. ActionManager.Triggers[action.trigger]++;
  42072. }
  42073. else {
  42074. ActionManager.Triggers[action.trigger] = 1;
  42075. }
  42076. action._actionManager = this;
  42077. action._prepare();
  42078. return action;
  42079. };
  42080. /**
  42081. * Process a specific trigger
  42082. * @param {number} trigger - the trigger to process
  42083. * @param evt {BABYLON.ActionEvent} the event details to be processed
  42084. */
  42085. ActionManager.prototype.processTrigger = function (trigger, evt) {
  42086. for (var index = 0; index < this.actions.length; index++) {
  42087. var action = this.actions[index];
  42088. if (action.trigger === trigger) {
  42089. if (evt) {
  42090. if (trigger === ActionManager.OnKeyUpTrigger
  42091. || trigger === ActionManager.OnKeyDownTrigger) {
  42092. var parameter = action.getTriggerParameter();
  42093. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  42094. if (!parameter.toLowerCase) {
  42095. continue;
  42096. }
  42097. var lowerCase = parameter.toLowerCase();
  42098. if (lowerCase !== evt.sourceEvent.key) {
  42099. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  42100. var actualkey = String.fromCharCode(unicode).toLowerCase();
  42101. if (actualkey !== lowerCase) {
  42102. continue;
  42103. }
  42104. }
  42105. }
  42106. }
  42107. }
  42108. action._executeCurrent(evt);
  42109. }
  42110. }
  42111. };
  42112. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  42113. var properties = propertyPath.split(".");
  42114. for (var index = 0; index < properties.length - 1; index++) {
  42115. target = target[properties[index]];
  42116. }
  42117. return target;
  42118. };
  42119. ActionManager.prototype._getProperty = function (propertyPath) {
  42120. var properties = propertyPath.split(".");
  42121. return properties[properties.length - 1];
  42122. };
  42123. ActionManager.prototype.serialize = function (name) {
  42124. var root = {
  42125. children: new Array(),
  42126. name: name,
  42127. type: 3,
  42128. properties: new Array() // Empty for root but required
  42129. };
  42130. for (var i = 0; i < this.actions.length; i++) {
  42131. var triggerObject = {
  42132. type: 0,
  42133. children: new Array(),
  42134. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  42135. properties: new Array()
  42136. };
  42137. var triggerOptions = this.actions[i].triggerOptions;
  42138. if (triggerOptions && typeof triggerOptions !== "number") {
  42139. if (triggerOptions.parameter instanceof BABYLON.Node) {
  42140. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42141. }
  42142. else {
  42143. var parameter = {};
  42144. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42145. if (triggerOptions.parameter.mesh) {
  42146. parameter._meshId = triggerOptions.parameter.mesh.id;
  42147. }
  42148. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42149. }
  42150. }
  42151. // Serialize child action, recursively
  42152. this.actions[i].serialize(triggerObject);
  42153. // Add serialized trigger
  42154. root.children.push(triggerObject);
  42155. }
  42156. return root;
  42157. };
  42158. ActionManager.Parse = function (parsedActions, object, scene) {
  42159. var actionManager = new BABYLON.ActionManager(scene);
  42160. if (object === null)
  42161. scene.actionManager = actionManager;
  42162. else
  42163. object.actionManager = actionManager;
  42164. // instanciate a new object
  42165. var instanciate = function (name, params) {
  42166. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  42167. newInstance.constructor.apply(newInstance, params);
  42168. return newInstance;
  42169. };
  42170. var parseParameter = function (name, value, target, propertyPath) {
  42171. if (propertyPath === null) {
  42172. // String, boolean or float
  42173. var floatValue = parseFloat(value);
  42174. if (value === "true" || value === "false")
  42175. return value === "true";
  42176. else
  42177. return isNaN(floatValue) ? value : floatValue;
  42178. }
  42179. var effectiveTarget = propertyPath.split(".");
  42180. var values = value.split(",");
  42181. // Get effective Target
  42182. for (var i = 0; i < effectiveTarget.length; i++) {
  42183. target = target[effectiveTarget[i]];
  42184. }
  42185. // Return appropriate value with its type
  42186. if (typeof (target) === "boolean")
  42187. return values[0] === "true";
  42188. if (typeof (target) === "string")
  42189. return values[0];
  42190. // Parameters with multiple values such as Vector3 etc.
  42191. var split = new Array();
  42192. for (var i = 0; i < values.length; i++)
  42193. split.push(parseFloat(values[i]));
  42194. if (target instanceof BABYLON.Vector3)
  42195. return BABYLON.Vector3.FromArray(split);
  42196. if (target instanceof BABYLON.Vector4)
  42197. return BABYLON.Vector4.FromArray(split);
  42198. if (target instanceof BABYLON.Color3)
  42199. return BABYLON.Color3.FromArray(split);
  42200. if (target instanceof BABYLON.Color4)
  42201. return BABYLON.Color4.FromArray(split);
  42202. return parseFloat(values[0]);
  42203. };
  42204. // traverse graph per trigger
  42205. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42206. if (combineArray === void 0) { combineArray = null; }
  42207. if (parsedAction.detached)
  42208. return;
  42209. var parameters = new Array();
  42210. var target = null;
  42211. var propertyPath = null;
  42212. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42213. // Parameters
  42214. if (parsedAction.type === 2)
  42215. parameters.push(actionManager);
  42216. else
  42217. parameters.push(trigger);
  42218. if (combine) {
  42219. var actions = new Array();
  42220. for (var j = 0; j < parsedAction.combine.length; j++) {
  42221. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42222. }
  42223. parameters.push(actions);
  42224. }
  42225. else {
  42226. for (var i = 0; i < parsedAction.properties.length; i++) {
  42227. var value = parsedAction.properties[i].value;
  42228. var name = parsedAction.properties[i].name;
  42229. var targetType = parsedAction.properties[i].targetType;
  42230. if (name === "target")
  42231. if (targetType !== null && targetType === "SceneProperties")
  42232. value = target = scene;
  42233. else
  42234. value = target = scene.getNodeByName(value);
  42235. else if (name === "parent")
  42236. value = scene.getNodeByName(value);
  42237. else if (name === "sound")
  42238. value = scene.getSoundByName(value);
  42239. else if (name !== "propertyPath") {
  42240. if (parsedAction.type === 2 && name === "operator")
  42241. value = BABYLON.ValueCondition[value];
  42242. else
  42243. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42244. }
  42245. else {
  42246. propertyPath = value;
  42247. }
  42248. parameters.push(value);
  42249. }
  42250. }
  42251. if (combineArray === null) {
  42252. parameters.push(condition);
  42253. }
  42254. else {
  42255. parameters.push(null);
  42256. }
  42257. // If interpolate value action
  42258. if (parsedAction.name === "InterpolateValueAction") {
  42259. var param = parameters[parameters.length - 2];
  42260. parameters[parameters.length - 1] = param;
  42261. parameters[parameters.length - 2] = condition;
  42262. }
  42263. // Action or condition(s) and not CombineAction
  42264. var newAction = instanciate(parsedAction.name, parameters);
  42265. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42266. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42267. if (action)
  42268. action.then(nothing);
  42269. else
  42270. actionManager.registerAction(nothing);
  42271. action = nothing;
  42272. }
  42273. if (combineArray === null) {
  42274. if (newAction instanceof BABYLON.Condition) {
  42275. condition = newAction;
  42276. newAction = action;
  42277. }
  42278. else {
  42279. condition = null;
  42280. if (action)
  42281. action.then(newAction);
  42282. else
  42283. actionManager.registerAction(newAction);
  42284. }
  42285. }
  42286. else {
  42287. combineArray.push(newAction);
  42288. }
  42289. for (var i = 0; i < parsedAction.children.length; i++)
  42290. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42291. };
  42292. // triggers
  42293. for (var i = 0; i < parsedActions.children.length; i++) {
  42294. var triggerParams;
  42295. var trigger = parsedActions.children[i];
  42296. if (trigger.properties.length > 0) {
  42297. var param = trigger.properties[0].value;
  42298. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42299. if (value._meshId) {
  42300. value.mesh = scene.getMeshByID(value._meshId);
  42301. }
  42302. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42303. }
  42304. else
  42305. triggerParams = ActionManager[trigger.name];
  42306. for (var j = 0; j < trigger.children.length; j++) {
  42307. if (!trigger.detached)
  42308. traverse(trigger.children[j], triggerParams, null, null);
  42309. }
  42310. }
  42311. };
  42312. ActionManager.GetTriggerName = function (trigger) {
  42313. switch (trigger) {
  42314. case 0: return "NothingTrigger";
  42315. case 1: return "OnPickTrigger";
  42316. case 2: return "OnLeftPickTrigger";
  42317. case 3: return "OnRightPickTrigger";
  42318. case 4: return "OnCenterPickTrigger";
  42319. case 5: return "OnPickDownTrigger";
  42320. case 6: return "OnPickUpTrigger";
  42321. case 7: return "OnLongPressTrigger";
  42322. case 8: return "OnPointerOverTrigger";
  42323. case 9: return "OnPointerOutTrigger";
  42324. case 10: return "OnEveryFrameTrigger";
  42325. case 11: return "OnIntersectionEnterTrigger";
  42326. case 12: return "OnIntersectionExitTrigger";
  42327. case 13: return "OnKeyDownTrigger";
  42328. case 14: return "OnKeyUpTrigger";
  42329. case 15: return "OnPickOutTrigger";
  42330. default: return "";
  42331. }
  42332. };
  42333. // Statics
  42334. ActionManager._NothingTrigger = 0;
  42335. ActionManager._OnPickTrigger = 1;
  42336. ActionManager._OnLeftPickTrigger = 2;
  42337. ActionManager._OnRightPickTrigger = 3;
  42338. ActionManager._OnCenterPickTrigger = 4;
  42339. ActionManager._OnPickDownTrigger = 5;
  42340. ActionManager._OnDoublePickTrigger = 6;
  42341. ActionManager._OnPickUpTrigger = 7;
  42342. ActionManager._OnLongPressTrigger = 8;
  42343. ActionManager._OnPointerOverTrigger = 9;
  42344. ActionManager._OnPointerOutTrigger = 10;
  42345. ActionManager._OnEveryFrameTrigger = 11;
  42346. ActionManager._OnIntersectionEnterTrigger = 12;
  42347. ActionManager._OnIntersectionExitTrigger = 13;
  42348. ActionManager._OnKeyDownTrigger = 14;
  42349. ActionManager._OnKeyUpTrigger = 15;
  42350. ActionManager._OnPickOutTrigger = 16;
  42351. ActionManager.Triggers = {};
  42352. return ActionManager;
  42353. }());
  42354. BABYLON.ActionManager = ActionManager;
  42355. })(BABYLON || (BABYLON = {}));
  42356. //# sourceMappingURL=babylon.actionManager.js.map
  42357. var BABYLON;
  42358. (function (BABYLON) {
  42359. var InterpolateValueAction = /** @class */ (function (_super) {
  42360. __extends(InterpolateValueAction, _super);
  42361. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42362. if (duration === void 0) { duration = 1000; }
  42363. var _this = _super.call(this, triggerOptions, condition) || this;
  42364. _this.propertyPath = propertyPath;
  42365. _this.value = value;
  42366. _this.duration = duration;
  42367. _this.stopOtherAnimations = stopOtherAnimations;
  42368. _this.onInterpolationDone = onInterpolationDone;
  42369. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42370. _this._target = _this._effectiveTarget = target;
  42371. return _this;
  42372. }
  42373. InterpolateValueAction.prototype._prepare = function () {
  42374. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42375. this._property = this._getProperty(this.propertyPath);
  42376. };
  42377. InterpolateValueAction.prototype.execute = function () {
  42378. var _this = this;
  42379. var scene = this._actionManager.getScene();
  42380. var keys = [
  42381. {
  42382. frame: 0,
  42383. value: this._effectiveTarget[this._property]
  42384. }, {
  42385. frame: 100,
  42386. value: this.value
  42387. }
  42388. ];
  42389. var dataType;
  42390. if (typeof this.value === "number") {
  42391. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42392. }
  42393. else if (this.value instanceof BABYLON.Color3) {
  42394. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42395. }
  42396. else if (this.value instanceof BABYLON.Vector3) {
  42397. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42398. }
  42399. else if (this.value instanceof BABYLON.Matrix) {
  42400. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42401. }
  42402. else if (this.value instanceof BABYLON.Quaternion) {
  42403. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42404. }
  42405. else {
  42406. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42407. return;
  42408. }
  42409. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42410. animation.setKeys(keys);
  42411. if (this.stopOtherAnimations) {
  42412. scene.stopAnimation(this._effectiveTarget);
  42413. }
  42414. var wrapper = function () {
  42415. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42416. if (_this.onInterpolationDone) {
  42417. _this.onInterpolationDone();
  42418. }
  42419. };
  42420. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42421. };
  42422. InterpolateValueAction.prototype.serialize = function (parent) {
  42423. return _super.prototype._serialize.call(this, {
  42424. name: "InterpolateValueAction",
  42425. properties: [
  42426. BABYLON.Action._GetTargetProperty(this._target),
  42427. { name: "propertyPath", value: this.propertyPath },
  42428. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42429. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42430. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42431. ]
  42432. }, parent);
  42433. };
  42434. return InterpolateValueAction;
  42435. }(BABYLON.Action));
  42436. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42437. })(BABYLON || (BABYLON = {}));
  42438. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42439. var BABYLON;
  42440. (function (BABYLON) {
  42441. var SwitchBooleanAction = /** @class */ (function (_super) {
  42442. __extends(SwitchBooleanAction, _super);
  42443. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42444. var _this = _super.call(this, triggerOptions, condition) || this;
  42445. _this.propertyPath = propertyPath;
  42446. _this._target = _this._effectiveTarget = target;
  42447. return _this;
  42448. }
  42449. SwitchBooleanAction.prototype._prepare = function () {
  42450. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42451. this._property = this._getProperty(this.propertyPath);
  42452. };
  42453. SwitchBooleanAction.prototype.execute = function () {
  42454. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42455. };
  42456. SwitchBooleanAction.prototype.serialize = function (parent) {
  42457. return _super.prototype._serialize.call(this, {
  42458. name: "SwitchBooleanAction",
  42459. properties: [
  42460. BABYLON.Action._GetTargetProperty(this._target),
  42461. { name: "propertyPath", value: this.propertyPath }
  42462. ]
  42463. }, parent);
  42464. };
  42465. return SwitchBooleanAction;
  42466. }(BABYLON.Action));
  42467. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42468. var SetStateAction = /** @class */ (function (_super) {
  42469. __extends(SetStateAction, _super);
  42470. function SetStateAction(triggerOptions, target, value, condition) {
  42471. var _this = _super.call(this, triggerOptions, condition) || this;
  42472. _this.value = value;
  42473. _this._target = target;
  42474. return _this;
  42475. }
  42476. SetStateAction.prototype.execute = function () {
  42477. this._target.state = this.value;
  42478. };
  42479. SetStateAction.prototype.serialize = function (parent) {
  42480. return _super.prototype._serialize.call(this, {
  42481. name: "SetStateAction",
  42482. properties: [
  42483. BABYLON.Action._GetTargetProperty(this._target),
  42484. { name: "value", value: this.value }
  42485. ]
  42486. }, parent);
  42487. };
  42488. return SetStateAction;
  42489. }(BABYLON.Action));
  42490. BABYLON.SetStateAction = SetStateAction;
  42491. var SetValueAction = /** @class */ (function (_super) {
  42492. __extends(SetValueAction, _super);
  42493. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42494. var _this = _super.call(this, triggerOptions, condition) || this;
  42495. _this.propertyPath = propertyPath;
  42496. _this.value = value;
  42497. _this._target = _this._effectiveTarget = target;
  42498. return _this;
  42499. }
  42500. SetValueAction.prototype._prepare = function () {
  42501. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42502. this._property = this._getProperty(this.propertyPath);
  42503. };
  42504. SetValueAction.prototype.execute = function () {
  42505. this._effectiveTarget[this._property] = this.value;
  42506. if (this._target.markAsDirty) {
  42507. this._target.markAsDirty(this._property);
  42508. }
  42509. };
  42510. SetValueAction.prototype.serialize = function (parent) {
  42511. return _super.prototype._serialize.call(this, {
  42512. name: "SetValueAction",
  42513. properties: [
  42514. BABYLON.Action._GetTargetProperty(this._target),
  42515. { name: "propertyPath", value: this.propertyPath },
  42516. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42517. ]
  42518. }, parent);
  42519. };
  42520. return SetValueAction;
  42521. }(BABYLON.Action));
  42522. BABYLON.SetValueAction = SetValueAction;
  42523. var IncrementValueAction = /** @class */ (function (_super) {
  42524. __extends(IncrementValueAction, _super);
  42525. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42526. var _this = _super.call(this, triggerOptions, condition) || this;
  42527. _this.propertyPath = propertyPath;
  42528. _this.value = value;
  42529. _this._target = _this._effectiveTarget = target;
  42530. return _this;
  42531. }
  42532. IncrementValueAction.prototype._prepare = function () {
  42533. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42534. this._property = this._getProperty(this.propertyPath);
  42535. if (typeof this._effectiveTarget[this._property] !== "number") {
  42536. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42537. }
  42538. };
  42539. IncrementValueAction.prototype.execute = function () {
  42540. this._effectiveTarget[this._property] += this.value;
  42541. if (this._target.markAsDirty) {
  42542. this._target.markAsDirty(this._property);
  42543. }
  42544. };
  42545. IncrementValueAction.prototype.serialize = function (parent) {
  42546. return _super.prototype._serialize.call(this, {
  42547. name: "IncrementValueAction",
  42548. properties: [
  42549. BABYLON.Action._GetTargetProperty(this._target),
  42550. { name: "propertyPath", value: this.propertyPath },
  42551. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42552. ]
  42553. }, parent);
  42554. };
  42555. return IncrementValueAction;
  42556. }(BABYLON.Action));
  42557. BABYLON.IncrementValueAction = IncrementValueAction;
  42558. var PlayAnimationAction = /** @class */ (function (_super) {
  42559. __extends(PlayAnimationAction, _super);
  42560. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42561. var _this = _super.call(this, triggerOptions, condition) || this;
  42562. _this.from = from;
  42563. _this.to = to;
  42564. _this.loop = loop;
  42565. _this._target = target;
  42566. return _this;
  42567. }
  42568. PlayAnimationAction.prototype._prepare = function () {
  42569. };
  42570. PlayAnimationAction.prototype.execute = function () {
  42571. var scene = this._actionManager.getScene();
  42572. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42573. };
  42574. PlayAnimationAction.prototype.serialize = function (parent) {
  42575. return _super.prototype._serialize.call(this, {
  42576. name: "PlayAnimationAction",
  42577. properties: [
  42578. BABYLON.Action._GetTargetProperty(this._target),
  42579. { name: "from", value: String(this.from) },
  42580. { name: "to", value: String(this.to) },
  42581. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42582. ]
  42583. }, parent);
  42584. };
  42585. return PlayAnimationAction;
  42586. }(BABYLON.Action));
  42587. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42588. var StopAnimationAction = /** @class */ (function (_super) {
  42589. __extends(StopAnimationAction, _super);
  42590. function StopAnimationAction(triggerOptions, target, condition) {
  42591. var _this = _super.call(this, triggerOptions, condition) || this;
  42592. _this._target = target;
  42593. return _this;
  42594. }
  42595. StopAnimationAction.prototype._prepare = function () {
  42596. };
  42597. StopAnimationAction.prototype.execute = function () {
  42598. var scene = this._actionManager.getScene();
  42599. scene.stopAnimation(this._target);
  42600. };
  42601. StopAnimationAction.prototype.serialize = function (parent) {
  42602. return _super.prototype._serialize.call(this, {
  42603. name: "StopAnimationAction",
  42604. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42605. }, parent);
  42606. };
  42607. return StopAnimationAction;
  42608. }(BABYLON.Action));
  42609. BABYLON.StopAnimationAction = StopAnimationAction;
  42610. var DoNothingAction = /** @class */ (function (_super) {
  42611. __extends(DoNothingAction, _super);
  42612. function DoNothingAction(triggerOptions, condition) {
  42613. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42614. return _super.call(this, triggerOptions, condition) || this;
  42615. }
  42616. DoNothingAction.prototype.execute = function () {
  42617. };
  42618. DoNothingAction.prototype.serialize = function (parent) {
  42619. return _super.prototype._serialize.call(this, {
  42620. name: "DoNothingAction",
  42621. properties: []
  42622. }, parent);
  42623. };
  42624. return DoNothingAction;
  42625. }(BABYLON.Action));
  42626. BABYLON.DoNothingAction = DoNothingAction;
  42627. var CombineAction = /** @class */ (function (_super) {
  42628. __extends(CombineAction, _super);
  42629. function CombineAction(triggerOptions, children, condition) {
  42630. var _this = _super.call(this, triggerOptions, condition) || this;
  42631. _this.children = children;
  42632. return _this;
  42633. }
  42634. CombineAction.prototype._prepare = function () {
  42635. for (var index = 0; index < this.children.length; index++) {
  42636. this.children[index]._actionManager = this._actionManager;
  42637. this.children[index]._prepare();
  42638. }
  42639. };
  42640. CombineAction.prototype.execute = function (evt) {
  42641. for (var index = 0; index < this.children.length; index++) {
  42642. this.children[index].execute(evt);
  42643. }
  42644. };
  42645. CombineAction.prototype.serialize = function (parent) {
  42646. var serializationObject = _super.prototype._serialize.call(this, {
  42647. name: "CombineAction",
  42648. properties: [],
  42649. combine: []
  42650. }, parent);
  42651. for (var i = 0; i < this.children.length; i++) {
  42652. serializationObject.combine.push(this.children[i].serialize(null));
  42653. }
  42654. return serializationObject;
  42655. };
  42656. return CombineAction;
  42657. }(BABYLON.Action));
  42658. BABYLON.CombineAction = CombineAction;
  42659. var ExecuteCodeAction = /** @class */ (function (_super) {
  42660. __extends(ExecuteCodeAction, _super);
  42661. function ExecuteCodeAction(triggerOptions, func, condition) {
  42662. var _this = _super.call(this, triggerOptions, condition) || this;
  42663. _this.func = func;
  42664. return _this;
  42665. }
  42666. ExecuteCodeAction.prototype.execute = function (evt) {
  42667. this.func(evt);
  42668. };
  42669. return ExecuteCodeAction;
  42670. }(BABYLON.Action));
  42671. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42672. var SetParentAction = /** @class */ (function (_super) {
  42673. __extends(SetParentAction, _super);
  42674. function SetParentAction(triggerOptions, target, parent, condition) {
  42675. var _this = _super.call(this, triggerOptions, condition) || this;
  42676. _this._target = target;
  42677. _this._parent = parent;
  42678. return _this;
  42679. }
  42680. SetParentAction.prototype._prepare = function () {
  42681. };
  42682. SetParentAction.prototype.execute = function () {
  42683. if (this._target.parent === this._parent) {
  42684. return;
  42685. }
  42686. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42687. invertParentWorldMatrix.invert();
  42688. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42689. this._target.parent = this._parent;
  42690. };
  42691. SetParentAction.prototype.serialize = function (parent) {
  42692. return _super.prototype._serialize.call(this, {
  42693. name: "SetParentAction",
  42694. properties: [
  42695. BABYLON.Action._GetTargetProperty(this._target),
  42696. BABYLON.Action._GetTargetProperty(this._parent),
  42697. ]
  42698. }, parent);
  42699. };
  42700. return SetParentAction;
  42701. }(BABYLON.Action));
  42702. BABYLON.SetParentAction = SetParentAction;
  42703. var PlaySoundAction = /** @class */ (function (_super) {
  42704. __extends(PlaySoundAction, _super);
  42705. function PlaySoundAction(triggerOptions, sound, condition) {
  42706. var _this = _super.call(this, triggerOptions, condition) || this;
  42707. _this._sound = sound;
  42708. return _this;
  42709. }
  42710. PlaySoundAction.prototype._prepare = function () {
  42711. };
  42712. PlaySoundAction.prototype.execute = function () {
  42713. if (this._sound !== undefined)
  42714. this._sound.play();
  42715. };
  42716. PlaySoundAction.prototype.serialize = function (parent) {
  42717. return _super.prototype._serialize.call(this, {
  42718. name: "PlaySoundAction",
  42719. properties: [{ name: "sound", value: this._sound.name }]
  42720. }, parent);
  42721. };
  42722. return PlaySoundAction;
  42723. }(BABYLON.Action));
  42724. BABYLON.PlaySoundAction = PlaySoundAction;
  42725. var StopSoundAction = /** @class */ (function (_super) {
  42726. __extends(StopSoundAction, _super);
  42727. function StopSoundAction(triggerOptions, sound, condition) {
  42728. var _this = _super.call(this, triggerOptions, condition) || this;
  42729. _this._sound = sound;
  42730. return _this;
  42731. }
  42732. StopSoundAction.prototype._prepare = function () {
  42733. };
  42734. StopSoundAction.prototype.execute = function () {
  42735. if (this._sound !== undefined)
  42736. this._sound.stop();
  42737. };
  42738. StopSoundAction.prototype.serialize = function (parent) {
  42739. return _super.prototype._serialize.call(this, {
  42740. name: "StopSoundAction",
  42741. properties: [{ name: "sound", value: this._sound.name }]
  42742. }, parent);
  42743. };
  42744. return StopSoundAction;
  42745. }(BABYLON.Action));
  42746. BABYLON.StopSoundAction = StopSoundAction;
  42747. })(BABYLON || (BABYLON = {}));
  42748. //# sourceMappingURL=babylon.directActions.js.map
  42749. var BABYLON;
  42750. (function (BABYLON) {
  42751. var SpriteManager = /** @class */ (function () {
  42752. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42753. if (epsilon === void 0) { epsilon = 0.01; }
  42754. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42755. this.name = name;
  42756. this.sprites = new Array();
  42757. this.renderingGroupId = 0;
  42758. this.layerMask = 0x0FFFFFFF;
  42759. this.fogEnabled = true;
  42760. this.isPickable = false;
  42761. /**
  42762. * An event triggered when the manager is disposed.
  42763. * @type {BABYLON.Observable}
  42764. */
  42765. this.onDisposeObservable = new BABYLON.Observable();
  42766. this._vertexBuffers = {};
  42767. this._capacity = capacity;
  42768. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42769. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42770. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42771. if (cellSize.width && cellSize.height) {
  42772. this.cellWidth = cellSize.width;
  42773. this.cellHeight = cellSize.height;
  42774. }
  42775. else if (cellSize !== undefined) {
  42776. this.cellWidth = cellSize;
  42777. this.cellHeight = cellSize;
  42778. }
  42779. else {
  42780. return;
  42781. }
  42782. this._epsilon = epsilon;
  42783. this._scene = scene;
  42784. this._scene.spriteManagers.push(this);
  42785. var indices = [];
  42786. var index = 0;
  42787. for (var count = 0; count < capacity; count++) {
  42788. indices.push(index);
  42789. indices.push(index + 1);
  42790. indices.push(index + 2);
  42791. indices.push(index);
  42792. indices.push(index + 2);
  42793. indices.push(index + 3);
  42794. index += 4;
  42795. }
  42796. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42797. // VBO
  42798. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42799. this._vertexData = new Float32Array(capacity * 16 * 4);
  42800. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42801. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42802. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42803. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42804. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42805. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42806. this._vertexBuffers["options"] = options;
  42807. this._vertexBuffers["cellInfo"] = cellInfo;
  42808. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42809. // Effects
  42810. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42811. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42812. }
  42813. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42814. set: function (callback) {
  42815. if (this._onDisposeObserver) {
  42816. this.onDisposeObservable.remove(this._onDisposeObserver);
  42817. }
  42818. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42819. },
  42820. enumerable: true,
  42821. configurable: true
  42822. });
  42823. Object.defineProperty(SpriteManager.prototype, "texture", {
  42824. get: function () {
  42825. return this._spriteTexture;
  42826. },
  42827. set: function (value) {
  42828. this._spriteTexture = value;
  42829. },
  42830. enumerable: true,
  42831. configurable: true
  42832. });
  42833. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42834. var arrayOffset = index * 16;
  42835. if (offsetX === 0)
  42836. offsetX = this._epsilon;
  42837. else if (offsetX === 1)
  42838. offsetX = 1 - this._epsilon;
  42839. if (offsetY === 0)
  42840. offsetY = this._epsilon;
  42841. else if (offsetY === 1)
  42842. offsetY = 1 - this._epsilon;
  42843. this._vertexData[arrayOffset] = sprite.position.x;
  42844. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42845. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42846. this._vertexData[arrayOffset + 3] = sprite.angle;
  42847. this._vertexData[arrayOffset + 4] = sprite.width;
  42848. this._vertexData[arrayOffset + 5] = sprite.height;
  42849. this._vertexData[arrayOffset + 6] = offsetX;
  42850. this._vertexData[arrayOffset + 7] = offsetY;
  42851. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42852. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42853. var offset = (sprite.cellIndex / rowSize) >> 0;
  42854. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42855. this._vertexData[arrayOffset + 11] = offset;
  42856. // Color
  42857. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42858. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42859. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42860. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42861. };
  42862. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42863. var count = Math.min(this._capacity, this.sprites.length);
  42864. var min = BABYLON.Vector3.Zero();
  42865. var max = BABYLON.Vector3.Zero();
  42866. var distance = Number.MAX_VALUE;
  42867. var currentSprite = null;
  42868. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42869. var cameraView = camera.getViewMatrix();
  42870. for (var index = 0; index < count; index++) {
  42871. var sprite = this.sprites[index];
  42872. if (!sprite) {
  42873. continue;
  42874. }
  42875. if (predicate) {
  42876. if (!predicate(sprite)) {
  42877. continue;
  42878. }
  42879. }
  42880. else if (!sprite.isPickable) {
  42881. continue;
  42882. }
  42883. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42884. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42885. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42886. if (ray.intersectsBoxMinMax(min, max)) {
  42887. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42888. if (distance > currentDistance) {
  42889. distance = currentDistance;
  42890. currentSprite = sprite;
  42891. if (fastCheck) {
  42892. break;
  42893. }
  42894. }
  42895. }
  42896. }
  42897. if (currentSprite) {
  42898. var result = new BABYLON.PickingInfo();
  42899. result.hit = true;
  42900. result.pickedSprite = currentSprite;
  42901. result.distance = distance;
  42902. return result;
  42903. }
  42904. return null;
  42905. };
  42906. SpriteManager.prototype.render = function () {
  42907. // Check
  42908. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42909. return;
  42910. var engine = this._scene.getEngine();
  42911. var baseSize = this._spriteTexture.getBaseSize();
  42912. // Sprites
  42913. var deltaTime = engine.getDeltaTime();
  42914. var max = Math.min(this._capacity, this.sprites.length);
  42915. var rowSize = baseSize.width / this.cellWidth;
  42916. var offset = 0;
  42917. for (var index = 0; index < max; index++) {
  42918. var sprite = this.sprites[index];
  42919. if (!sprite) {
  42920. continue;
  42921. }
  42922. sprite._animate(deltaTime);
  42923. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42924. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42925. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42926. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42927. }
  42928. this._buffer.update(this._vertexData);
  42929. // Render
  42930. var effect = this._effectBase;
  42931. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42932. effect = this._effectFog;
  42933. }
  42934. engine.enableEffect(effect);
  42935. var viewMatrix = this._scene.getViewMatrix();
  42936. effect.setTexture("diffuseSampler", this._spriteTexture);
  42937. effect.setMatrix("view", viewMatrix);
  42938. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42939. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42940. // Fog
  42941. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42942. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42943. effect.setColor3("vFogColor", this._scene.fogColor);
  42944. }
  42945. // VBOs
  42946. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42947. // Draw order
  42948. engine.setDepthFunctionToLessOrEqual();
  42949. effect.setBool("alphaTest", true);
  42950. engine.setColorWrite(false);
  42951. engine.draw(true, 0, max * 6);
  42952. engine.setColorWrite(true);
  42953. effect.setBool("alphaTest", false);
  42954. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42955. engine.draw(true, 0, max * 6);
  42956. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42957. };
  42958. SpriteManager.prototype.dispose = function () {
  42959. if (this._buffer) {
  42960. this._buffer.dispose();
  42961. this._buffer = null;
  42962. }
  42963. if (this._indexBuffer) {
  42964. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42965. this._indexBuffer = null;
  42966. }
  42967. if (this._spriteTexture) {
  42968. this._spriteTexture.dispose();
  42969. this._spriteTexture = null;
  42970. }
  42971. // Remove from scene
  42972. var index = this._scene.spriteManagers.indexOf(this);
  42973. this._scene.spriteManagers.splice(index, 1);
  42974. // Callback
  42975. this.onDisposeObservable.notifyObservers(this);
  42976. this.onDisposeObservable.clear();
  42977. };
  42978. return SpriteManager;
  42979. }());
  42980. BABYLON.SpriteManager = SpriteManager;
  42981. })(BABYLON || (BABYLON = {}));
  42982. //# sourceMappingURL=babylon.spriteManager.js.map
  42983. var BABYLON;
  42984. (function (BABYLON) {
  42985. var Sprite = /** @class */ (function () {
  42986. function Sprite(name, manager) {
  42987. this.name = name;
  42988. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42989. this.width = 1.0;
  42990. this.height = 1.0;
  42991. this.angle = 0;
  42992. this.cellIndex = 0;
  42993. this.invertU = 0;
  42994. this.invertV = 0;
  42995. this.animations = new Array();
  42996. this.isPickable = false;
  42997. this._animationStarted = false;
  42998. this._loopAnimation = false;
  42999. this._fromIndex = 0;
  43000. this._toIndex = 0;
  43001. this._delay = 0;
  43002. this._direction = 1;
  43003. this._time = 0;
  43004. this._manager = manager;
  43005. this._manager.sprites.push(this);
  43006. this.position = BABYLON.Vector3.Zero();
  43007. }
  43008. Object.defineProperty(Sprite.prototype, "size", {
  43009. get: function () {
  43010. return this.width;
  43011. },
  43012. set: function (value) {
  43013. this.width = value;
  43014. this.height = value;
  43015. },
  43016. enumerable: true,
  43017. configurable: true
  43018. });
  43019. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  43020. this._fromIndex = from;
  43021. this._toIndex = to;
  43022. this._loopAnimation = loop;
  43023. this._delay = delay;
  43024. this._animationStarted = true;
  43025. this._direction = from < to ? 1 : -1;
  43026. this.cellIndex = from;
  43027. this._time = 0;
  43028. this._onAnimationEnd = onAnimationEnd;
  43029. };
  43030. Sprite.prototype.stopAnimation = function () {
  43031. this._animationStarted = false;
  43032. };
  43033. Sprite.prototype._animate = function (deltaTime) {
  43034. if (!this._animationStarted)
  43035. return;
  43036. this._time += deltaTime;
  43037. if (this._time > this._delay) {
  43038. this._time = this._time % this._delay;
  43039. this.cellIndex += this._direction;
  43040. if (this.cellIndex > this._toIndex) {
  43041. if (this._loopAnimation) {
  43042. this.cellIndex = this._fromIndex;
  43043. }
  43044. else {
  43045. this.cellIndex = this._toIndex;
  43046. this._animationStarted = false;
  43047. if (this._onAnimationEnd) {
  43048. this._onAnimationEnd();
  43049. }
  43050. if (this.disposeWhenFinishedAnimating) {
  43051. this.dispose();
  43052. }
  43053. }
  43054. }
  43055. }
  43056. };
  43057. Sprite.prototype.dispose = function () {
  43058. for (var i = 0; i < this._manager.sprites.length; i++) {
  43059. if (this._manager.sprites[i] == this) {
  43060. this._manager.sprites.splice(i, 1);
  43061. }
  43062. }
  43063. };
  43064. return Sprite;
  43065. }());
  43066. BABYLON.Sprite = Sprite;
  43067. })(BABYLON || (BABYLON = {}));
  43068. //# sourceMappingURL=babylon.sprite.js.map
  43069. var BABYLON;
  43070. (function (BABYLON) {
  43071. var IntersectionInfo = /** @class */ (function () {
  43072. function IntersectionInfo(bu, bv, distance) {
  43073. this.bu = bu;
  43074. this.bv = bv;
  43075. this.distance = distance;
  43076. this.faceId = 0;
  43077. this.subMeshId = 0;
  43078. }
  43079. return IntersectionInfo;
  43080. }());
  43081. BABYLON.IntersectionInfo = IntersectionInfo;
  43082. var PickingInfo = /** @class */ (function () {
  43083. function PickingInfo() {
  43084. this.hit = false;
  43085. this.distance = 0;
  43086. this.pickedPoint = null;
  43087. this.pickedMesh = null;
  43088. this.bu = 0;
  43089. this.bv = 0;
  43090. this.faceId = -1;
  43091. this.subMeshId = 0;
  43092. this.pickedSprite = null;
  43093. }
  43094. // Methods
  43095. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  43096. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  43097. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  43098. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43099. return null;
  43100. }
  43101. var indices = this.pickedMesh.getIndices();
  43102. if (!indices) {
  43103. return null;
  43104. }
  43105. var result;
  43106. if (useVerticesNormals) {
  43107. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43108. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  43109. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  43110. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  43111. normal0 = normal0.scale(this.bu);
  43112. normal1 = normal1.scale(this.bv);
  43113. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  43114. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  43115. }
  43116. else {
  43117. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43118. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  43119. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  43120. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  43121. var p1p2 = vertex1.subtract(vertex2);
  43122. var p3p2 = vertex3.subtract(vertex2);
  43123. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  43124. }
  43125. if (useWorldCoordinates) {
  43126. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  43127. }
  43128. return BABYLON.Vector3.Normalize(result);
  43129. };
  43130. PickingInfo.prototype.getTextureCoordinates = function () {
  43131. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43132. return null;
  43133. }
  43134. var indices = this.pickedMesh.getIndices();
  43135. if (!indices) {
  43136. return null;
  43137. }
  43138. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43139. if (!uvs) {
  43140. return null;
  43141. }
  43142. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  43143. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  43144. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  43145. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  43146. uv1 = uv1.scale(this.bu);
  43147. uv2 = uv2.scale(this.bv);
  43148. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  43149. };
  43150. return PickingInfo;
  43151. }());
  43152. BABYLON.PickingInfo = PickingInfo;
  43153. })(BABYLON || (BABYLON = {}));
  43154. //# sourceMappingURL=babylon.pickingInfo.js.map
  43155. var BABYLON;
  43156. (function (BABYLON) {
  43157. var Ray = /** @class */ (function () {
  43158. function Ray(origin, direction, length) {
  43159. if (length === void 0) { length = Number.MAX_VALUE; }
  43160. this.origin = origin;
  43161. this.direction = direction;
  43162. this.length = length;
  43163. }
  43164. // Methods
  43165. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  43166. var d = 0.0;
  43167. var maxValue = Number.MAX_VALUE;
  43168. var inv;
  43169. var min;
  43170. var max;
  43171. var temp;
  43172. if (Math.abs(this.direction.x) < 0.0000001) {
  43173. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  43174. return false;
  43175. }
  43176. }
  43177. else {
  43178. inv = 1.0 / this.direction.x;
  43179. min = (minimum.x - this.origin.x) * inv;
  43180. max = (maximum.x - this.origin.x) * inv;
  43181. if (max === -Infinity) {
  43182. max = Infinity;
  43183. }
  43184. if (min > max) {
  43185. temp = min;
  43186. min = max;
  43187. max = temp;
  43188. }
  43189. d = Math.max(min, d);
  43190. maxValue = Math.min(max, maxValue);
  43191. if (d > maxValue) {
  43192. return false;
  43193. }
  43194. }
  43195. if (Math.abs(this.direction.y) < 0.0000001) {
  43196. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43197. return false;
  43198. }
  43199. }
  43200. else {
  43201. inv = 1.0 / this.direction.y;
  43202. min = (minimum.y - this.origin.y) * inv;
  43203. max = (maximum.y - this.origin.y) * inv;
  43204. if (max === -Infinity) {
  43205. max = Infinity;
  43206. }
  43207. if (min > max) {
  43208. temp = min;
  43209. min = max;
  43210. max = temp;
  43211. }
  43212. d = Math.max(min, d);
  43213. maxValue = Math.min(max, maxValue);
  43214. if (d > maxValue) {
  43215. return false;
  43216. }
  43217. }
  43218. if (Math.abs(this.direction.z) < 0.0000001) {
  43219. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43220. return false;
  43221. }
  43222. }
  43223. else {
  43224. inv = 1.0 / this.direction.z;
  43225. min = (minimum.z - this.origin.z) * inv;
  43226. max = (maximum.z - this.origin.z) * inv;
  43227. if (max === -Infinity) {
  43228. max = Infinity;
  43229. }
  43230. if (min > max) {
  43231. temp = min;
  43232. min = max;
  43233. max = temp;
  43234. }
  43235. d = Math.max(min, d);
  43236. maxValue = Math.min(max, maxValue);
  43237. if (d > maxValue) {
  43238. return false;
  43239. }
  43240. }
  43241. return true;
  43242. };
  43243. Ray.prototype.intersectsBox = function (box) {
  43244. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43245. };
  43246. Ray.prototype.intersectsSphere = function (sphere) {
  43247. var x = sphere.center.x - this.origin.x;
  43248. var y = sphere.center.y - this.origin.y;
  43249. var z = sphere.center.z - this.origin.z;
  43250. var pyth = (x * x) + (y * y) + (z * z);
  43251. var rr = sphere.radius * sphere.radius;
  43252. if (pyth <= rr) {
  43253. return true;
  43254. }
  43255. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43256. if (dot < 0.0) {
  43257. return false;
  43258. }
  43259. var temp = pyth - (dot * dot);
  43260. return temp <= rr;
  43261. };
  43262. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43263. if (!this._edge1) {
  43264. this._edge1 = BABYLON.Vector3.Zero();
  43265. this._edge2 = BABYLON.Vector3.Zero();
  43266. this._pvec = BABYLON.Vector3.Zero();
  43267. this._tvec = BABYLON.Vector3.Zero();
  43268. this._qvec = BABYLON.Vector3.Zero();
  43269. }
  43270. vertex1.subtractToRef(vertex0, this._edge1);
  43271. vertex2.subtractToRef(vertex0, this._edge2);
  43272. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43273. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43274. if (det === 0) {
  43275. return null;
  43276. }
  43277. var invdet = 1 / det;
  43278. this.origin.subtractToRef(vertex0, this._tvec);
  43279. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43280. if (bu < 0 || bu > 1.0) {
  43281. return null;
  43282. }
  43283. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43284. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43285. if (bv < 0 || bu + bv > 1.0) {
  43286. return null;
  43287. }
  43288. //check if the distance is longer than the predefined length.
  43289. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43290. if (distance > this.length) {
  43291. return null;
  43292. }
  43293. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43294. };
  43295. Ray.prototype.intersectsPlane = function (plane) {
  43296. var distance;
  43297. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43298. if (Math.abs(result1) < 9.99999997475243E-07) {
  43299. return null;
  43300. }
  43301. else {
  43302. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43303. distance = (-plane.d - result2) / result1;
  43304. if (distance < 0.0) {
  43305. if (distance < -9.99999997475243E-07) {
  43306. return null;
  43307. }
  43308. else {
  43309. return 0;
  43310. }
  43311. }
  43312. return distance;
  43313. }
  43314. };
  43315. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43316. var tm = BABYLON.Tmp.Matrix[0];
  43317. mesh.getWorldMatrix().invertToRef(tm);
  43318. if (this._tmpRay) {
  43319. Ray.TransformToRef(this, tm, this._tmpRay);
  43320. }
  43321. else {
  43322. this._tmpRay = Ray.Transform(this, tm);
  43323. }
  43324. return mesh.intersects(this._tmpRay, fastCheck);
  43325. };
  43326. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43327. if (results) {
  43328. results.length = 0;
  43329. }
  43330. else {
  43331. results = [];
  43332. }
  43333. for (var i = 0; i < meshes.length; i++) {
  43334. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43335. if (pickInfo.hit) {
  43336. results.push(pickInfo);
  43337. }
  43338. }
  43339. results.sort(this._comparePickingInfo);
  43340. return results;
  43341. };
  43342. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43343. if (pickingInfoA.distance < pickingInfoB.distance) {
  43344. return -1;
  43345. }
  43346. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43347. return 1;
  43348. }
  43349. else {
  43350. return 0;
  43351. }
  43352. };
  43353. /**
  43354. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43355. * @param sega the first point of the segment to test the intersection against
  43356. * @param segb the second point of the segment to test the intersection against
  43357. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43358. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43359. */
  43360. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43361. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43362. var u = segb.subtract(sega);
  43363. var v = rsegb.subtract(this.origin);
  43364. var w = sega.subtract(this.origin);
  43365. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43366. var b = BABYLON.Vector3.Dot(u, v);
  43367. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43368. var d = BABYLON.Vector3.Dot(u, w);
  43369. var e = BABYLON.Vector3.Dot(v, w);
  43370. var D = a * c - b * b; // always >= 0
  43371. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43372. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43373. // compute the line parameters of the two closest points
  43374. if (D < Ray.smallnum) {
  43375. sN = 0.0; // force using point P0 on segment S1
  43376. sD = 1.0; // to prevent possible division by 0.0 later
  43377. tN = e;
  43378. tD = c;
  43379. }
  43380. else {
  43381. sN = (b * e - c * d);
  43382. tN = (a * e - b * d);
  43383. if (sN < 0.0) {
  43384. sN = 0.0;
  43385. tN = e;
  43386. tD = c;
  43387. }
  43388. else if (sN > sD) {
  43389. sN = sD;
  43390. tN = e + b;
  43391. tD = c;
  43392. }
  43393. }
  43394. if (tN < 0.0) {
  43395. tN = 0.0;
  43396. // recompute sc for this edge
  43397. if (-d < 0.0) {
  43398. sN = 0.0;
  43399. }
  43400. else if (-d > a)
  43401. sN = sD;
  43402. else {
  43403. sN = -d;
  43404. sD = a;
  43405. }
  43406. }
  43407. else if (tN > tD) {
  43408. tN = tD;
  43409. // recompute sc for this edge
  43410. if ((-d + b) < 0.0) {
  43411. sN = 0;
  43412. }
  43413. else if ((-d + b) > a) {
  43414. sN = sD;
  43415. }
  43416. else {
  43417. sN = (-d + b);
  43418. sD = a;
  43419. }
  43420. }
  43421. // finally do the division to get sc and tc
  43422. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43423. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43424. // get the difference of the two closest points
  43425. var qtc = v.multiplyByFloats(tc, tc, tc);
  43426. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43427. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43428. if (isIntersected) {
  43429. return qtc.length();
  43430. }
  43431. return -1;
  43432. };
  43433. // Statics
  43434. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43435. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43436. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43437. var direction = end.subtract(start);
  43438. direction.normalize();
  43439. return new Ray(start, direction);
  43440. };
  43441. /**
  43442. * 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
  43443. * transformed to the given world matrix.
  43444. * @param origin The origin point
  43445. * @param end The end point
  43446. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43447. */
  43448. Ray.CreateNewFromTo = function (origin, end, world) {
  43449. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43450. var direction = end.subtract(origin);
  43451. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43452. direction.normalize();
  43453. return Ray.Transform(new Ray(origin, direction, length), world);
  43454. };
  43455. Ray.Transform = function (ray, matrix) {
  43456. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43457. Ray.TransformToRef(ray, matrix, result);
  43458. return result;
  43459. };
  43460. Ray.TransformToRef = function (ray, matrix, result) {
  43461. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43462. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43463. result.length = ray.length;
  43464. var dir = result.direction;
  43465. var len = dir.length();
  43466. if (!(len === 0 || len === 1)) {
  43467. var num = 1.0 / len;
  43468. dir.x *= num;
  43469. dir.y *= num;
  43470. dir.z *= num;
  43471. result.length *= len;
  43472. }
  43473. };
  43474. Ray.smallnum = 0.00000001;
  43475. Ray.rayl = 10e8;
  43476. return Ray;
  43477. }());
  43478. BABYLON.Ray = Ray;
  43479. })(BABYLON || (BABYLON = {}));
  43480. //# sourceMappingURL=babylon.ray.js.map
  43481. var BABYLON;
  43482. (function (BABYLON) {
  43483. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43484. if (boxMin.x > sphereCenter.x + sphereRadius)
  43485. return false;
  43486. if (sphereCenter.x - sphereRadius > boxMax.x)
  43487. return false;
  43488. if (boxMin.y > sphereCenter.y + sphereRadius)
  43489. return false;
  43490. if (sphereCenter.y - sphereRadius > boxMax.y)
  43491. return false;
  43492. if (boxMin.z > sphereCenter.z + sphereRadius)
  43493. return false;
  43494. if (sphereCenter.z - sphereRadius > boxMax.z)
  43495. return false;
  43496. return true;
  43497. };
  43498. var getLowestRoot = (function () {
  43499. var result = { root: 0, found: false };
  43500. return function (a, b, c, maxR) {
  43501. result.root = 0;
  43502. result.found = false;
  43503. var determinant = b * b - 4.0 * a * c;
  43504. if (determinant < 0)
  43505. return result;
  43506. var sqrtD = Math.sqrt(determinant);
  43507. var r1 = (-b - sqrtD) / (2.0 * a);
  43508. var r2 = (-b + sqrtD) / (2.0 * a);
  43509. if (r1 > r2) {
  43510. var temp = r2;
  43511. r2 = r1;
  43512. r1 = temp;
  43513. }
  43514. if (r1 > 0 && r1 < maxR) {
  43515. result.root = r1;
  43516. result.found = true;
  43517. return result;
  43518. }
  43519. if (r2 > 0 && r2 < maxR) {
  43520. result.root = r2;
  43521. result.found = true;
  43522. return result;
  43523. }
  43524. return result;
  43525. };
  43526. })();
  43527. var Collider = /** @class */ (function () {
  43528. function Collider() {
  43529. this.radius = BABYLON.Vector3.One();
  43530. this.retry = 0;
  43531. this.basePointWorld = BABYLON.Vector3.Zero();
  43532. this.velocityWorld = BABYLON.Vector3.Zero();
  43533. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43534. this._collisionPoint = BABYLON.Vector3.Zero();
  43535. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43536. this._tempVector = BABYLON.Vector3.Zero();
  43537. this._tempVector2 = BABYLON.Vector3.Zero();
  43538. this._tempVector3 = BABYLON.Vector3.Zero();
  43539. this._tempVector4 = BABYLON.Vector3.Zero();
  43540. this._edge = BABYLON.Vector3.Zero();
  43541. this._baseToVertex = BABYLON.Vector3.Zero();
  43542. this._destinationPoint = BABYLON.Vector3.Zero();
  43543. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43544. this._displacementVector = BABYLON.Vector3.Zero();
  43545. this._collisionMask = -1;
  43546. }
  43547. Object.defineProperty(Collider.prototype, "collisionMask", {
  43548. get: function () {
  43549. return this._collisionMask;
  43550. },
  43551. set: function (mask) {
  43552. this._collisionMask = !isNaN(mask) ? mask : -1;
  43553. },
  43554. enumerable: true,
  43555. configurable: true
  43556. });
  43557. // Methods
  43558. Collider.prototype._initialize = function (source, dir, e) {
  43559. this.velocity = dir;
  43560. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43561. this.basePoint = source;
  43562. source.multiplyToRef(this.radius, this.basePointWorld);
  43563. dir.multiplyToRef(this.radius, this.velocityWorld);
  43564. this.velocityWorldLength = this.velocityWorld.length();
  43565. this.epsilon = e;
  43566. this.collisionFound = false;
  43567. };
  43568. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43569. pa.subtractToRef(point, this._tempVector);
  43570. pb.subtractToRef(point, this._tempVector2);
  43571. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43572. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43573. if (d < 0)
  43574. return false;
  43575. pc.subtractToRef(point, this._tempVector3);
  43576. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43577. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43578. if (d < 0)
  43579. return false;
  43580. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43581. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43582. return d >= 0;
  43583. };
  43584. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43585. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43586. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43587. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43588. return false;
  43589. }
  43590. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43591. return false;
  43592. return true;
  43593. };
  43594. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43595. var t0;
  43596. var embeddedInPlane = false;
  43597. //defensive programming, actually not needed.
  43598. if (!trianglePlaneArray) {
  43599. trianglePlaneArray = [];
  43600. }
  43601. if (!trianglePlaneArray[faceIndex]) {
  43602. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43603. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43604. }
  43605. var trianglePlane = trianglePlaneArray[faceIndex];
  43606. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43607. return;
  43608. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43609. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43610. if (normalDotVelocity == 0) {
  43611. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43612. return;
  43613. embeddedInPlane = true;
  43614. t0 = 0;
  43615. }
  43616. else {
  43617. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43618. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43619. if (t0 > t1) {
  43620. var temp = t1;
  43621. t1 = t0;
  43622. t0 = temp;
  43623. }
  43624. if (t0 > 1.0 || t1 < 0.0)
  43625. return;
  43626. if (t0 < 0)
  43627. t0 = 0;
  43628. if (t0 > 1.0)
  43629. t0 = 1.0;
  43630. }
  43631. this._collisionPoint.copyFromFloats(0, 0, 0);
  43632. var found = false;
  43633. var t = 1.0;
  43634. if (!embeddedInPlane) {
  43635. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43636. this.velocity.scaleToRef(t0, this._tempVector);
  43637. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43638. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43639. found = true;
  43640. t = t0;
  43641. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43642. }
  43643. }
  43644. if (!found) {
  43645. var velocitySquaredLength = this.velocity.lengthSquared();
  43646. var a = velocitySquaredLength;
  43647. this.basePoint.subtractToRef(p1, this._tempVector);
  43648. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43649. var c = this._tempVector.lengthSquared() - 1.0;
  43650. var lowestRoot = getLowestRoot(a, b, c, t);
  43651. if (lowestRoot.found) {
  43652. t = lowestRoot.root;
  43653. found = true;
  43654. this._collisionPoint.copyFrom(p1);
  43655. }
  43656. this.basePoint.subtractToRef(p2, this._tempVector);
  43657. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43658. c = this._tempVector.lengthSquared() - 1.0;
  43659. lowestRoot = getLowestRoot(a, b, c, t);
  43660. if (lowestRoot.found) {
  43661. t = lowestRoot.root;
  43662. found = true;
  43663. this._collisionPoint.copyFrom(p2);
  43664. }
  43665. this.basePoint.subtractToRef(p3, this._tempVector);
  43666. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43667. c = this._tempVector.lengthSquared() - 1.0;
  43668. lowestRoot = getLowestRoot(a, b, c, t);
  43669. if (lowestRoot.found) {
  43670. t = lowestRoot.root;
  43671. found = true;
  43672. this._collisionPoint.copyFrom(p3);
  43673. }
  43674. p2.subtractToRef(p1, this._edge);
  43675. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43676. var edgeSquaredLength = this._edge.lengthSquared();
  43677. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43678. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43679. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43680. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43681. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43682. lowestRoot = getLowestRoot(a, b, c, t);
  43683. if (lowestRoot.found) {
  43684. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43685. if (f >= 0.0 && f <= 1.0) {
  43686. t = lowestRoot.root;
  43687. found = true;
  43688. this._edge.scaleInPlace(f);
  43689. p1.addToRef(this._edge, this._collisionPoint);
  43690. }
  43691. }
  43692. p3.subtractToRef(p2, this._edge);
  43693. p2.subtractToRef(this.basePoint, this._baseToVertex);
  43694. edgeSquaredLength = this._edge.lengthSquared();
  43695. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43696. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43697. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43698. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43699. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43700. lowestRoot = getLowestRoot(a, b, c, t);
  43701. if (lowestRoot.found) {
  43702. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43703. if (f >= 0.0 && f <= 1.0) {
  43704. t = lowestRoot.root;
  43705. found = true;
  43706. this._edge.scaleInPlace(f);
  43707. p2.addToRef(this._edge, this._collisionPoint);
  43708. }
  43709. }
  43710. p1.subtractToRef(p3, this._edge);
  43711. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43712. edgeSquaredLength = this._edge.lengthSquared();
  43713. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43714. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43715. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43716. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43717. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43718. lowestRoot = getLowestRoot(a, b, c, t);
  43719. if (lowestRoot.found) {
  43720. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43721. if (f >= 0.0 && f <= 1.0) {
  43722. t = lowestRoot.root;
  43723. found = true;
  43724. this._edge.scaleInPlace(f);
  43725. p3.addToRef(this._edge, this._collisionPoint);
  43726. }
  43727. }
  43728. }
  43729. if (found) {
  43730. var distToCollision = t * this.velocity.length();
  43731. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43732. if (!this.intersectionPoint) {
  43733. this.intersectionPoint = this._collisionPoint.clone();
  43734. }
  43735. else {
  43736. this.intersectionPoint.copyFrom(this._collisionPoint);
  43737. }
  43738. this.nearestDistance = distToCollision;
  43739. this.collisionFound = true;
  43740. }
  43741. }
  43742. };
  43743. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43744. for (var i = indexStart; i < indexEnd; i += 3) {
  43745. var p1 = pts[indices[i] - decal];
  43746. var p2 = pts[indices[i + 1] - decal];
  43747. var p3 = pts[indices[i + 2] - decal];
  43748. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43749. }
  43750. };
  43751. Collider.prototype._getResponse = function (pos, vel) {
  43752. pos.addToRef(vel, this._destinationPoint);
  43753. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43754. this.basePoint.addToRef(vel, pos);
  43755. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43756. this._slidePlaneNormal.normalize();
  43757. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43758. pos.addInPlace(this._displacementVector);
  43759. this.intersectionPoint.addInPlace(this._displacementVector);
  43760. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43761. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43762. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43763. };
  43764. return Collider;
  43765. }());
  43766. BABYLON.Collider = Collider;
  43767. })(BABYLON || (BABYLON = {}));
  43768. //# sourceMappingURL=babylon.collider.js.map
  43769. var BABYLON;
  43770. (function (BABYLON) {
  43771. //WebWorker code will be inserted to this variable.
  43772. BABYLON.CollisionWorker = "";
  43773. var WorkerTaskType;
  43774. (function (WorkerTaskType) {
  43775. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43776. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43777. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43778. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43779. var WorkerReplyType;
  43780. (function (WorkerReplyType) {
  43781. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43782. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43783. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43784. var CollisionCoordinatorWorker = /** @class */ (function () {
  43785. function CollisionCoordinatorWorker() {
  43786. var _this = this;
  43787. this._scaledPosition = BABYLON.Vector3.Zero();
  43788. this._scaledVelocity = BABYLON.Vector3.Zero();
  43789. this.onMeshUpdated = function (mesh) {
  43790. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43791. };
  43792. this.onGeometryUpdated = function (geometry) {
  43793. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43794. };
  43795. this._afterRender = function () {
  43796. if (!_this._init)
  43797. return;
  43798. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43799. return;
  43800. }
  43801. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43802. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43803. if (_this._runningUpdated > 4) {
  43804. return;
  43805. }
  43806. ++_this._runningUpdated;
  43807. var payload = {
  43808. updatedMeshes: _this._addUpdateMeshesList,
  43809. updatedGeometries: _this._addUpdateGeometriesList,
  43810. removedGeometries: _this._toRemoveGeometryArray,
  43811. removedMeshes: _this._toRemoveMeshesArray
  43812. };
  43813. var message = {
  43814. payload: payload,
  43815. taskType: WorkerTaskType.UPDATE
  43816. };
  43817. var serializable = [];
  43818. for (var id in payload.updatedGeometries) {
  43819. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43820. //prepare transferables
  43821. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43822. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43823. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43824. }
  43825. }
  43826. _this._worker.postMessage(message, serializable);
  43827. _this._addUpdateMeshesList = {};
  43828. _this._addUpdateGeometriesList = {};
  43829. _this._toRemoveGeometryArray = [];
  43830. _this._toRemoveMeshesArray = [];
  43831. };
  43832. this._onMessageFromWorker = function (e) {
  43833. var returnData = e.data;
  43834. if (returnData.error != WorkerReplyType.SUCCESS) {
  43835. //TODO what errors can be returned from the worker?
  43836. BABYLON.Tools.Warn("error returned from worker!");
  43837. return;
  43838. }
  43839. switch (returnData.taskType) {
  43840. case WorkerTaskType.INIT:
  43841. _this._init = true;
  43842. //Update the worked with ALL of the scene's current state
  43843. _this._scene.meshes.forEach(function (mesh) {
  43844. _this.onMeshAdded(mesh);
  43845. });
  43846. _this._scene.getGeometries().forEach(function (geometry) {
  43847. _this.onGeometryAdded(geometry);
  43848. });
  43849. break;
  43850. case WorkerTaskType.UPDATE:
  43851. _this._runningUpdated--;
  43852. break;
  43853. case WorkerTaskType.COLLIDE:
  43854. _this._runningCollisionTask = false;
  43855. var returnPayload = returnData.payload;
  43856. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43857. return;
  43858. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43859. if (callback) {
  43860. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43861. if (mesh) {
  43862. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43863. }
  43864. }
  43865. //cleanup
  43866. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43867. break;
  43868. }
  43869. };
  43870. this._collisionsCallbackArray = [];
  43871. this._init = false;
  43872. this._runningUpdated = 0;
  43873. this._runningCollisionTask = false;
  43874. this._addUpdateMeshesList = {};
  43875. this._addUpdateGeometriesList = {};
  43876. this._toRemoveGeometryArray = [];
  43877. this._toRemoveMeshesArray = [];
  43878. }
  43879. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43880. if (!this._init)
  43881. return;
  43882. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43883. return;
  43884. position.divideToRef(collider.radius, this._scaledPosition);
  43885. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43886. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43887. var payload = {
  43888. collider: {
  43889. position: this._scaledPosition.asArray(),
  43890. velocity: this._scaledVelocity.asArray(),
  43891. radius: collider.radius.asArray()
  43892. },
  43893. collisionId: collisionIndex,
  43894. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43895. maximumRetry: maximumRetry
  43896. };
  43897. var message = {
  43898. payload: payload,
  43899. taskType: WorkerTaskType.COLLIDE
  43900. };
  43901. this._worker.postMessage(message);
  43902. };
  43903. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43904. this._scene = scene;
  43905. this._scene.registerAfterRender(this._afterRender);
  43906. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43907. this._worker = new Worker(workerUrl);
  43908. this._worker.onmessage = this._onMessageFromWorker;
  43909. var message = {
  43910. payload: {},
  43911. taskType: WorkerTaskType.INIT
  43912. };
  43913. this._worker.postMessage(message);
  43914. };
  43915. CollisionCoordinatorWorker.prototype.destroy = function () {
  43916. this._scene.unregisterAfterRender(this._afterRender);
  43917. this._worker.terminate();
  43918. };
  43919. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43920. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43921. this.onMeshUpdated(mesh);
  43922. };
  43923. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43924. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43925. };
  43926. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43927. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43928. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43929. this.onGeometryUpdated(geometry);
  43930. };
  43931. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43932. this._toRemoveGeometryArray.push(geometry.id);
  43933. };
  43934. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43935. var submeshes = [];
  43936. if (mesh.subMeshes) {
  43937. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43938. var boundingInfo = sm.getBoundingInfo();
  43939. return {
  43940. position: idx,
  43941. verticesStart: sm.verticesStart,
  43942. verticesCount: sm.verticesCount,
  43943. indexStart: sm.indexStart,
  43944. indexCount: sm.indexCount,
  43945. hasMaterial: !!sm.getMaterial(),
  43946. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43947. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43948. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43949. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43950. };
  43951. });
  43952. }
  43953. var geometryId = null;
  43954. if (mesh instanceof BABYLON.Mesh) {
  43955. var geometry = mesh.geometry;
  43956. geometryId = geometry ? geometry.id : null;
  43957. }
  43958. else if (mesh instanceof BABYLON.InstancedMesh) {
  43959. var geometry = mesh.sourceMesh.geometry;
  43960. geometryId = geometry ? geometry.id : null;
  43961. }
  43962. var boundingInfo = mesh.getBoundingInfo();
  43963. return {
  43964. uniqueId: mesh.uniqueId,
  43965. id: mesh.id,
  43966. name: mesh.name,
  43967. geometryId: geometryId,
  43968. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43969. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43970. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43971. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43972. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43973. subMeshes: submeshes,
  43974. checkCollisions: mesh.checkCollisions
  43975. };
  43976. };
  43977. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43978. return {
  43979. id: geometry.id,
  43980. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43981. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43982. indices: new Uint32Array(geometry.getIndices() || []),
  43983. };
  43984. };
  43985. return CollisionCoordinatorWorker;
  43986. }());
  43987. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43988. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43989. function CollisionCoordinatorLegacy() {
  43990. this._scaledPosition = BABYLON.Vector3.Zero();
  43991. this._scaledVelocity = BABYLON.Vector3.Zero();
  43992. this._finalPosition = BABYLON.Vector3.Zero();
  43993. }
  43994. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43995. position.divideToRef(collider.radius, this._scaledPosition);
  43996. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43997. collider.collidedMesh = null;
  43998. collider.retry = 0;
  43999. collider.initialVelocity = this._scaledVelocity;
  44000. collider.initialPosition = this._scaledPosition;
  44001. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  44002. this._finalPosition.multiplyInPlace(collider.radius);
  44003. //run the callback
  44004. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  44005. };
  44006. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  44007. this._scene = scene;
  44008. };
  44009. CollisionCoordinatorLegacy.prototype.destroy = function () {
  44010. //Legacy need no destruction method.
  44011. };
  44012. //No update in legacy mode
  44013. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  44014. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  44015. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  44016. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  44017. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  44018. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  44019. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  44020. if (excludedMesh === void 0) { excludedMesh = null; }
  44021. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  44022. if (collider.retry >= maximumRetry) {
  44023. finalPosition.copyFrom(position);
  44024. return;
  44025. }
  44026. // Check if this is a mesh else camera or -1
  44027. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  44028. collider._initialize(position, velocity, closeDistance);
  44029. // Check all meshes
  44030. for (var index = 0; index < this._scene.meshes.length; index++) {
  44031. var mesh = this._scene.meshes[index];
  44032. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  44033. mesh._checkCollision(collider);
  44034. }
  44035. }
  44036. if (!collider.collisionFound) {
  44037. position.addToRef(velocity, finalPosition);
  44038. return;
  44039. }
  44040. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  44041. collider._getResponse(position, velocity);
  44042. }
  44043. if (velocity.length() <= closeDistance) {
  44044. finalPosition.copyFrom(position);
  44045. return;
  44046. }
  44047. collider.retry++;
  44048. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  44049. };
  44050. return CollisionCoordinatorLegacy;
  44051. }());
  44052. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  44053. })(BABYLON || (BABYLON = {}));
  44054. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  44055. var BABYLON;
  44056. (function (BABYLON) {
  44057. var Particle = /** @class */ (function () {
  44058. function Particle(particleSystem) {
  44059. this.particleSystem = particleSystem;
  44060. this.position = BABYLON.Vector3.Zero();
  44061. this.direction = BABYLON.Vector3.Zero();
  44062. this.color = new BABYLON.Color4(0, 0, 0, 0);
  44063. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  44064. this.lifeTime = 1.0;
  44065. this.age = 0;
  44066. this.size = 0;
  44067. this.angle = 0;
  44068. this.angularSpeed = 0;
  44069. this._currentFrameCounter = 0;
  44070. this.cellIndex = 0;
  44071. if (!this.particleSystem.isAnimationSheetEnabled) {
  44072. return;
  44073. }
  44074. this.cellIndex = this.particleSystem.startSpriteCellID;
  44075. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  44076. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  44077. }
  44078. else {
  44079. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  44080. }
  44081. }
  44082. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  44083. // (ageOffset / scaledUpdateSpeed) / available cells
  44084. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  44085. this._currentFrameCounter += scaledUpdateSpeed;
  44086. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  44087. this._currentFrameCounter = 0;
  44088. this.cellIndex++;
  44089. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44090. this.cellIndex = this.particleSystem.endSpriteCellID;
  44091. }
  44092. }
  44093. };
  44094. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  44095. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  44096. this.cellIndex++;
  44097. this._currentFrameCounter = 0;
  44098. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44099. if (this.particleSystem.spriteCellLoop) {
  44100. this.cellIndex = this.particleSystem.startSpriteCellID;
  44101. }
  44102. else {
  44103. this.cellIndex = this.particleSystem.endSpriteCellID;
  44104. }
  44105. }
  44106. }
  44107. else {
  44108. this._currentFrameCounter++;
  44109. }
  44110. };
  44111. Particle.prototype.copyTo = function (other) {
  44112. other.position.copyFrom(this.position);
  44113. other.direction.copyFrom(this.direction);
  44114. other.color.copyFrom(this.color);
  44115. other.colorStep.copyFrom(this.colorStep);
  44116. other.lifeTime = this.lifeTime;
  44117. other.age = this.age;
  44118. other.size = this.size;
  44119. other.angle = this.angle;
  44120. other.angularSpeed = this.angularSpeed;
  44121. other.particleSystem = this.particleSystem;
  44122. other.cellIndex = this.cellIndex;
  44123. };
  44124. return Particle;
  44125. }());
  44126. BABYLON.Particle = Particle;
  44127. })(BABYLON || (BABYLON = {}));
  44128. //# sourceMappingURL=babylon.particle.js.map
  44129. var BABYLON;
  44130. (function (BABYLON) {
  44131. var randomNumber = function (min, max) {
  44132. if (min === max) {
  44133. return (min);
  44134. }
  44135. var random = Math.random();
  44136. return ((random * (max - min)) + min);
  44137. };
  44138. var ParticleSystem = /** @class */ (function () {
  44139. // end of sheet animation
  44140. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  44141. if (customEffect === void 0) { customEffect = null; }
  44142. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  44143. if (epsilon === void 0) { epsilon = 0.01; }
  44144. var _this = this;
  44145. this.name = name;
  44146. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  44147. // Members
  44148. this.animations = [];
  44149. this.renderingGroupId = 0;
  44150. this.emitter = null;
  44151. this.emitRate = 10;
  44152. this.manualEmitCount = -1;
  44153. this.updateSpeed = 0.01;
  44154. this.targetStopDuration = 0;
  44155. this.disposeOnStop = false;
  44156. this.minEmitPower = 1;
  44157. this.maxEmitPower = 1;
  44158. this.minLifeTime = 1;
  44159. this.maxLifeTime = 1;
  44160. this.minSize = 1;
  44161. this.maxSize = 1;
  44162. this.minAngularSpeed = 0;
  44163. this.maxAngularSpeed = 0;
  44164. this.layerMask = 0x0FFFFFFF;
  44165. this.customShader = null;
  44166. this.preventAutoStart = false;
  44167. /**
  44168. * An event triggered when the system is disposed.
  44169. * @type {BABYLON.Observable}
  44170. */
  44171. this.onDisposeObservable = new BABYLON.Observable();
  44172. this.onAnimationEnd = null;
  44173. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  44174. this.forceDepthWrite = false;
  44175. this.gravity = BABYLON.Vector3.Zero();
  44176. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  44177. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  44178. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  44179. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44180. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44181. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44182. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  44183. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44184. this.particles = new Array();
  44185. this._stockParticles = new Array();
  44186. this._newPartsExcess = 0;
  44187. this._vertexBuffers = {};
  44188. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44189. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44190. this._scaledDirection = BABYLON.Vector3.Zero();
  44191. this._scaledGravity = BABYLON.Vector3.Zero();
  44192. this._currentRenderId = -1;
  44193. this._started = false;
  44194. this._stopped = false;
  44195. this._actualFrame = 0;
  44196. // sheet animation
  44197. this.startSpriteCellID = 0;
  44198. this.endSpriteCellID = 0;
  44199. this.spriteCellLoop = true;
  44200. this.spriteCellChangeSpeed = 0;
  44201. this.spriteCellWidth = 0;
  44202. this.spriteCellHeight = 0;
  44203. this._vertexBufferSize = 11;
  44204. this.appendParticleVertexes = null;
  44205. this.id = name;
  44206. this._capacity = capacity;
  44207. this._epsilon = epsilon;
  44208. if (_isAnimationSheetEnabled) {
  44209. this._vertexBufferSize = 12;
  44210. }
  44211. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44212. this._customEffect = customEffect;
  44213. scene.particleSystems.push(this);
  44214. this._createIndexBuffer();
  44215. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44216. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44217. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44218. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44219. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44220. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44221. if (this._isAnimationSheetEnabled) {
  44222. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44223. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44224. }
  44225. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44226. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44227. this._vertexBuffers["options"] = options;
  44228. // Default behaviors
  44229. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44230. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44231. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44232. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44233. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44234. };
  44235. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44236. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44237. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44238. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44239. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44240. };
  44241. this.updateFunction = function (particles) {
  44242. for (var index = 0; index < particles.length; index++) {
  44243. var particle = particles[index];
  44244. particle.age += _this._scaledUpdateSpeed;
  44245. if (particle.age >= particle.lifeTime) {
  44246. _this.recycleParticle(particle);
  44247. index--;
  44248. continue;
  44249. }
  44250. else {
  44251. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44252. particle.color.addInPlace(_this._scaledColorStep);
  44253. if (particle.color.a < 0)
  44254. particle.color.a = 0;
  44255. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44256. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44257. particle.position.addInPlace(_this._scaledDirection);
  44258. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44259. particle.direction.addInPlace(_this._scaledGravity);
  44260. if (_this._isAnimationSheetEnabled) {
  44261. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44262. }
  44263. }
  44264. }
  44265. };
  44266. }
  44267. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44268. set: function (callback) {
  44269. if (this._onDisposeObserver) {
  44270. this.onDisposeObservable.remove(this._onDisposeObserver);
  44271. }
  44272. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44273. },
  44274. enumerable: true,
  44275. configurable: true
  44276. });
  44277. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44278. get: function () {
  44279. return this._isAnimationSheetEnabled;
  44280. },
  44281. enumerable: true,
  44282. configurable: true
  44283. });
  44284. ParticleSystem.prototype._createIndexBuffer = function () {
  44285. var indices = [];
  44286. var index = 0;
  44287. for (var count = 0; count < this._capacity; count++) {
  44288. indices.push(index);
  44289. indices.push(index + 1);
  44290. indices.push(index + 2);
  44291. indices.push(index);
  44292. indices.push(index + 2);
  44293. indices.push(index + 3);
  44294. index += 4;
  44295. }
  44296. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44297. };
  44298. ParticleSystem.prototype.recycleParticle = function (particle) {
  44299. var lastParticle = this.particles.pop();
  44300. if (lastParticle !== particle) {
  44301. lastParticle.copyTo(particle);
  44302. this._stockParticles.push(lastParticle);
  44303. }
  44304. };
  44305. ParticleSystem.prototype.getCapacity = function () {
  44306. return this._capacity;
  44307. };
  44308. ParticleSystem.prototype.isAlive = function () {
  44309. return this._alive;
  44310. };
  44311. ParticleSystem.prototype.isStarted = function () {
  44312. return this._started;
  44313. };
  44314. ParticleSystem.prototype.start = function () {
  44315. this._started = true;
  44316. this._stopped = false;
  44317. this._actualFrame = 0;
  44318. };
  44319. ParticleSystem.prototype.stop = function () {
  44320. this._stopped = true;
  44321. };
  44322. // animation sheet
  44323. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44324. var offset = index * this._vertexBufferSize;
  44325. this._vertexData[offset] = particle.position.x;
  44326. this._vertexData[offset + 1] = particle.position.y;
  44327. this._vertexData[offset + 2] = particle.position.z;
  44328. this._vertexData[offset + 3] = particle.color.r;
  44329. this._vertexData[offset + 4] = particle.color.g;
  44330. this._vertexData[offset + 5] = particle.color.b;
  44331. this._vertexData[offset + 6] = particle.color.a;
  44332. this._vertexData[offset + 7] = particle.angle;
  44333. this._vertexData[offset + 8] = particle.size;
  44334. this._vertexData[offset + 9] = offsetX;
  44335. this._vertexData[offset + 10] = offsetY;
  44336. };
  44337. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44338. if (offsetX === 0)
  44339. offsetX = this._epsilon;
  44340. else if (offsetX === 1)
  44341. offsetX = 1 - this._epsilon;
  44342. if (offsetY === 0)
  44343. offsetY = this._epsilon;
  44344. else if (offsetY === 1)
  44345. offsetY = 1 - this._epsilon;
  44346. var offset = index * this._vertexBufferSize;
  44347. this._vertexData[offset] = particle.position.x;
  44348. this._vertexData[offset + 1] = particle.position.y;
  44349. this._vertexData[offset + 2] = particle.position.z;
  44350. this._vertexData[offset + 3] = particle.color.r;
  44351. this._vertexData[offset + 4] = particle.color.g;
  44352. this._vertexData[offset + 5] = particle.color.b;
  44353. this._vertexData[offset + 6] = particle.color.a;
  44354. this._vertexData[offset + 7] = particle.angle;
  44355. this._vertexData[offset + 8] = particle.size;
  44356. this._vertexData[offset + 9] = offsetX;
  44357. this._vertexData[offset + 10] = offsetY;
  44358. this._vertexData[offset + 11] = particle.cellIndex;
  44359. };
  44360. ParticleSystem.prototype._update = function (newParticles) {
  44361. // Update current
  44362. this._alive = this.particles.length > 0;
  44363. this.updateFunction(this.particles);
  44364. // Add new ones
  44365. var worldMatrix;
  44366. if (this.emitter.position) {
  44367. var emitterMesh = this.emitter;
  44368. worldMatrix = emitterMesh.getWorldMatrix();
  44369. }
  44370. else {
  44371. var emitterPosition = this.emitter;
  44372. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44373. }
  44374. var particle;
  44375. for (var index = 0; index < newParticles; index++) {
  44376. if (this.particles.length === this._capacity) {
  44377. break;
  44378. }
  44379. if (this._stockParticles.length !== 0) {
  44380. particle = this._stockParticles.pop();
  44381. particle.age = 0;
  44382. particle.cellIndex = this.startSpriteCellID;
  44383. }
  44384. else {
  44385. particle = new BABYLON.Particle(this);
  44386. }
  44387. this.particles.push(particle);
  44388. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44389. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44390. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44391. particle.size = randomNumber(this.minSize, this.maxSize);
  44392. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44393. this.startPositionFunction(worldMatrix, particle.position, particle);
  44394. var step = randomNumber(0, 1.0);
  44395. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44396. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44397. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44398. }
  44399. };
  44400. ParticleSystem.prototype._getEffect = function () {
  44401. if (this._customEffect) {
  44402. return this._customEffect;
  44403. }
  44404. ;
  44405. var defines = [];
  44406. if (this._scene.clipPlane) {
  44407. defines.push("#define CLIPPLANE");
  44408. }
  44409. if (this._isAnimationSheetEnabled) {
  44410. defines.push("#define ANIMATESHEET");
  44411. }
  44412. // Effect
  44413. var join = defines.join("\n");
  44414. if (this._cachedDefines !== join) {
  44415. this._cachedDefines = join;
  44416. var attributesNamesOrOptions;
  44417. var effectCreationOption;
  44418. if (this._isAnimationSheetEnabled) {
  44419. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44420. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44421. }
  44422. else {
  44423. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44424. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44425. }
  44426. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44427. }
  44428. return this._effect;
  44429. };
  44430. ParticleSystem.prototype.animate = function () {
  44431. if (!this._started)
  44432. return;
  44433. var effect = this._getEffect();
  44434. // Check
  44435. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44436. return;
  44437. if (this._currentRenderId === this._scene.getRenderId()) {
  44438. return;
  44439. }
  44440. this._currentRenderId = this._scene.getRenderId();
  44441. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44442. // determine the number of particles we need to create
  44443. var newParticles;
  44444. if (this.manualEmitCount > -1) {
  44445. newParticles = this.manualEmitCount;
  44446. this._newPartsExcess = 0;
  44447. this.manualEmitCount = 0;
  44448. }
  44449. else {
  44450. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44451. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44452. }
  44453. if (this._newPartsExcess > 1.0) {
  44454. newParticles += this._newPartsExcess >> 0;
  44455. this._newPartsExcess -= this._newPartsExcess >> 0;
  44456. }
  44457. this._alive = false;
  44458. if (!this._stopped) {
  44459. this._actualFrame += this._scaledUpdateSpeed;
  44460. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44461. this.stop();
  44462. }
  44463. else {
  44464. newParticles = 0;
  44465. }
  44466. this._update(newParticles);
  44467. // Stopped?
  44468. if (this._stopped) {
  44469. if (!this._alive) {
  44470. this._started = false;
  44471. if (this.onAnimationEnd) {
  44472. this.onAnimationEnd();
  44473. }
  44474. if (this.disposeOnStop) {
  44475. this._scene._toBeDisposed.push(this);
  44476. }
  44477. }
  44478. }
  44479. // Animation sheet
  44480. if (this._isAnimationSheetEnabled) {
  44481. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44482. }
  44483. else {
  44484. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44485. }
  44486. // Update VBO
  44487. var offset = 0;
  44488. for (var index = 0; index < this.particles.length; index++) {
  44489. var particle = this.particles[index];
  44490. this.appendParticleVertexes(offset, particle);
  44491. offset += 4;
  44492. }
  44493. if (this._vertexBuffer) {
  44494. this._vertexBuffer.update(this._vertexData);
  44495. }
  44496. };
  44497. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44498. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44499. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44500. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44501. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44502. };
  44503. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44504. this._appendParticleVertex(offset++, particle, 0, 0);
  44505. this._appendParticleVertex(offset++, particle, 1, 0);
  44506. this._appendParticleVertex(offset++, particle, 1, 1);
  44507. this._appendParticleVertex(offset++, particle, 0, 1);
  44508. };
  44509. ParticleSystem.prototype.rebuild = function () {
  44510. this._createIndexBuffer();
  44511. if (this._vertexBuffer) {
  44512. this._vertexBuffer._rebuild();
  44513. }
  44514. };
  44515. ParticleSystem.prototype.render = function () {
  44516. var effect = this._getEffect();
  44517. // Check
  44518. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44519. return 0;
  44520. var engine = this._scene.getEngine();
  44521. // Render
  44522. engine.enableEffect(effect);
  44523. engine.setState(false);
  44524. var viewMatrix = this._scene.getViewMatrix();
  44525. effect.setTexture("diffuseSampler", this.particleTexture);
  44526. effect.setMatrix("view", viewMatrix);
  44527. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44528. if (this._isAnimationSheetEnabled) {
  44529. var baseSize = this.particleTexture.getBaseSize();
  44530. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44531. }
  44532. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44533. if (this._scene.clipPlane) {
  44534. var clipPlane = this._scene.clipPlane;
  44535. var invView = viewMatrix.clone();
  44536. invView.invert();
  44537. effect.setMatrix("invView", invView);
  44538. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44539. }
  44540. // VBOs
  44541. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44542. // Draw order
  44543. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44544. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44545. }
  44546. else {
  44547. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44548. }
  44549. if (this.forceDepthWrite) {
  44550. engine.setDepthWrite(true);
  44551. }
  44552. engine.draw(true, 0, this.particles.length * 6);
  44553. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44554. return this.particles.length;
  44555. };
  44556. ParticleSystem.prototype.dispose = function () {
  44557. if (this._vertexBuffer) {
  44558. this._vertexBuffer.dispose();
  44559. this._vertexBuffer = null;
  44560. }
  44561. if (this._indexBuffer) {
  44562. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44563. this._indexBuffer = null;
  44564. }
  44565. if (this.particleTexture) {
  44566. this.particleTexture.dispose();
  44567. this.particleTexture = null;
  44568. }
  44569. // Remove from scene
  44570. var index = this._scene.particleSystems.indexOf(this);
  44571. if (index > -1) {
  44572. this._scene.particleSystems.splice(index, 1);
  44573. }
  44574. // Callback
  44575. this.onDisposeObservable.notifyObservers(this);
  44576. this.onDisposeObservable.clear();
  44577. };
  44578. // Clone
  44579. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44580. var custom = null;
  44581. var program = null;
  44582. if (this.customShader != null) {
  44583. program = this.customShader;
  44584. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44585. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44586. }
  44587. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44588. result.customShader = program;
  44589. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44590. if (newEmitter === undefined) {
  44591. newEmitter = this.emitter;
  44592. }
  44593. result.emitter = newEmitter;
  44594. if (this.particleTexture) {
  44595. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44596. }
  44597. if (!this.preventAutoStart) {
  44598. result.start();
  44599. }
  44600. return result;
  44601. };
  44602. ParticleSystem.prototype.serialize = function () {
  44603. var serializationObject = {};
  44604. serializationObject.name = this.name;
  44605. serializationObject.id = this.id;
  44606. // Emitter
  44607. if (this.emitter.position) {
  44608. var emitterMesh = this.emitter;
  44609. serializationObject.emitterId = emitterMesh.id;
  44610. }
  44611. else {
  44612. var emitterPosition = this.emitter;
  44613. serializationObject.emitter = emitterPosition.asArray();
  44614. }
  44615. serializationObject.capacity = this.getCapacity();
  44616. if (this.particleTexture) {
  44617. serializationObject.textureName = this.particleTexture.name;
  44618. }
  44619. // Animations
  44620. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44621. // Particle system
  44622. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44623. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44624. serializationObject.minSize = this.minSize;
  44625. serializationObject.maxSize = this.maxSize;
  44626. serializationObject.minEmitPower = this.minEmitPower;
  44627. serializationObject.maxEmitPower = this.maxEmitPower;
  44628. serializationObject.minLifeTime = this.minLifeTime;
  44629. serializationObject.maxLifeTime = this.maxLifeTime;
  44630. serializationObject.emitRate = this.emitRate;
  44631. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44632. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44633. serializationObject.gravity = this.gravity.asArray();
  44634. serializationObject.direction1 = this.direction1.asArray();
  44635. serializationObject.direction2 = this.direction2.asArray();
  44636. serializationObject.color1 = this.color1.asArray();
  44637. serializationObject.color2 = this.color2.asArray();
  44638. serializationObject.colorDead = this.colorDead.asArray();
  44639. serializationObject.updateSpeed = this.updateSpeed;
  44640. serializationObject.targetStopDuration = this.targetStopDuration;
  44641. serializationObject.textureMask = this.textureMask.asArray();
  44642. serializationObject.blendMode = this.blendMode;
  44643. serializationObject.customShader = this.customShader;
  44644. serializationObject.preventAutoStart = this.preventAutoStart;
  44645. return serializationObject;
  44646. };
  44647. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44648. var name = parsedParticleSystem.name;
  44649. var custom = null;
  44650. var program = null;
  44651. if (parsedParticleSystem.customShader) {
  44652. program = parsedParticleSystem.customShader;
  44653. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44654. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44655. }
  44656. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44657. particleSystem.customShader = program;
  44658. if (parsedParticleSystem.id) {
  44659. particleSystem.id = parsedParticleSystem.id;
  44660. }
  44661. // Auto start
  44662. if (parsedParticleSystem.preventAutoStart) {
  44663. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44664. }
  44665. // Texture
  44666. if (parsedParticleSystem.textureName) {
  44667. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44668. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44669. }
  44670. // Emitter
  44671. if (parsedParticleSystem.emitterId) {
  44672. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44673. }
  44674. else {
  44675. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44676. }
  44677. // Animations
  44678. if (parsedParticleSystem.animations) {
  44679. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44680. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44681. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44682. }
  44683. }
  44684. if (parsedParticleSystem.autoAnimate) {
  44685. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44686. }
  44687. // Particle system
  44688. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44689. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44690. particleSystem.minSize = parsedParticleSystem.minSize;
  44691. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44692. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44693. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44694. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44695. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44696. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44697. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44698. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44699. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44700. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44701. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44702. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44703. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44704. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44705. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44706. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44707. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44708. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44709. if (!particleSystem.preventAutoStart) {
  44710. particleSystem.start();
  44711. }
  44712. return particleSystem;
  44713. };
  44714. // Statics
  44715. ParticleSystem.BLENDMODE_ONEONE = 0;
  44716. ParticleSystem.BLENDMODE_STANDARD = 1;
  44717. return ParticleSystem;
  44718. }());
  44719. BABYLON.ParticleSystem = ParticleSystem;
  44720. })(BABYLON || (BABYLON = {}));
  44721. //# sourceMappingURL=babylon.particleSystem.js.map
  44722. var BABYLON;
  44723. (function (BABYLON) {
  44724. var GPUParticleSystem = /** @class */ (function () {
  44725. function GPUParticleSystem(name, capacity, scene) {
  44726. this.name = name;
  44727. this.emitter = null;
  44728. this.renderingGroupId = 0;
  44729. this.layerMask = 0x0FFFFFFF; // TODO
  44730. this._updateVertexBuffers = {};
  44731. this._renderVertexBuffers = {};
  44732. this._currentRenderId = -1;
  44733. this._started = true;
  44734. /**
  44735. * An event triggered when the system is disposed.
  44736. * @type {BABYLON.Observable}
  44737. */
  44738. this.onDisposeObservable = new BABYLON.Observable();
  44739. this.id = name;
  44740. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44741. this._capacity = capacity;
  44742. this._engine = this._scene.getEngine();
  44743. this._scene.particleSystems.push(this);
  44744. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  44745. var updateEffectOptions = {
  44746. attributes: ["position", "age", "life", "velocity"],
  44747. uniformsNames: [],
  44748. uniformBuffersNames: [],
  44749. samplers: [],
  44750. defines: "",
  44751. fallbacks: null,
  44752. onCompiled: null,
  44753. onError: null,
  44754. indexParameters: null,
  44755. maxSimultaneousLights: 0,
  44756. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  44757. };
  44758. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  44759. }
  44760. GPUParticleSystem.prototype.isStarted = function () {
  44761. return this._started;
  44762. };
  44763. GPUParticleSystem.prototype.start = function () {
  44764. this._started = true;
  44765. };
  44766. GPUParticleSystem.prototype.stop = function () {
  44767. this._started = false;
  44768. };
  44769. GPUParticleSystem.prototype.animate = function () {
  44770. // Do nothing
  44771. };
  44772. GPUParticleSystem.prototype._initialize = function () {
  44773. if (this._renderVAO) {
  44774. return;
  44775. }
  44776. var data = new Array();
  44777. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  44778. // position
  44779. data.push(0.0);
  44780. data.push(0.0);
  44781. data.push(0.0);
  44782. var life = 1 + Math.random() * 10; // TODO: var
  44783. data.push(life + 1); // create the particle as a dead one to create a new one at start
  44784. data.push(life);
  44785. // velocity
  44786. data.push(0.0);
  44787. data.push(0.0);
  44788. data.push(0.0);
  44789. }
  44790. // Update VAO
  44791. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  44792. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  44793. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  44794. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  44795. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  44796. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  44797. this._engine.bindArrayBuffer(null);
  44798. // Render VAO
  44799. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  44800. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  44801. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  44802. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  44803. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  44804. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  44805. this._engine.bindArrayBuffer(null);
  44806. // Links
  44807. this._sourceVAO = this._updateVAO;
  44808. this._targetVAO = this._renderVAO;
  44809. this._sourceBuffer = this._updateBuffer;
  44810. this._targetBuffer = this._renderBuffer;
  44811. };
  44812. GPUParticleSystem.prototype.render = function () {
  44813. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  44814. return 0;
  44815. }
  44816. // Get everything ready to render
  44817. this._initialize();
  44818. if (this._currentRenderId === this._scene.getRenderId()) {
  44819. return 0;
  44820. }
  44821. this._currentRenderId = this._scene.getRenderId();
  44822. // Enable update effect
  44823. this._engine.enableEffect(this._updateEffect);
  44824. this._engine.setState(false);
  44825. // Bind source VAO
  44826. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  44827. // Update
  44828. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  44829. this._engine.setRasterizerState(false);
  44830. this._engine.beginTransformFeedback();
  44831. this._engine.drawPointClouds(0, this._capacity);
  44832. this._engine.endTransformFeedback();
  44833. this._engine.setRasterizerState(true);
  44834. this._engine.bindTransformFeedbackBuffer(null);
  44835. // Enable render effect
  44836. this._engine.enableEffect(this._renderEffect);
  44837. // Bind source VAO
  44838. this._engine.bindVertexArrayObject(this._targetVAO, null);
  44839. // Render
  44840. this._engine.drawPointClouds(0, this._capacity);
  44841. // Switch VAOs
  44842. var tmpVAO = this._sourceVAO;
  44843. this._sourceVAO = this._targetVAO;
  44844. this._targetVAO = tmpVAO;
  44845. // Switch buffers
  44846. var tmpBuffer = this._sourceBuffer;
  44847. this._sourceBuffer = this._targetBuffer;
  44848. this._targetBuffer = tmpBuffer;
  44849. return 0;
  44850. };
  44851. GPUParticleSystem.prototype.rebuild = function () {
  44852. };
  44853. GPUParticleSystem.prototype.dispose = function () {
  44854. var index = this._scene.particleSystems.indexOf(this);
  44855. if (index > -1) {
  44856. this._scene.particleSystems.splice(index, 1);
  44857. }
  44858. //TODO: this._dataBuffer.dispose();
  44859. // Callback
  44860. this.onDisposeObservable.notifyObservers(this);
  44861. this.onDisposeObservable.clear();
  44862. };
  44863. //TODO: Clone / Parse / serialize
  44864. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  44865. return null;
  44866. };
  44867. GPUParticleSystem.prototype.serialize = function () {
  44868. };
  44869. return GPUParticleSystem;
  44870. }());
  44871. BABYLON.GPUParticleSystem = GPUParticleSystem;
  44872. })(BABYLON || (BABYLON = {}));
  44873. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  44874. var BABYLON;
  44875. (function (BABYLON) {
  44876. var SolidParticle = /** @class */ (function () {
  44877. /**
  44878. * Creates a Solid Particle object.
  44879. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44880. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44881. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44882. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44883. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44884. * `shapeId` (integer) is the model shape identifier in the SPS.
  44885. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44886. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44887. */
  44888. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44889. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44890. this.idx = 0; // particle global index
  44891. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44892. this.position = BABYLON.Vector3.Zero(); // position
  44893. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44894. this.scaling = BABYLON.Vector3.One(); // scaling
  44895. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44896. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44897. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44898. this.alive = true; // alive
  44899. this.isVisible = true; // visibility
  44900. this._pos = 0; // index of this particle in the global "positions" array
  44901. this._ind = 0; // index of this particle in the global "indices" array
  44902. this.shapeId = 0; // model shape id
  44903. this.idxInShape = 0; // index of the particle in its shape id
  44904. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44905. this.idx = particleIndex;
  44906. this._pos = positionIndex;
  44907. this._ind = indiceIndex;
  44908. this._model = model;
  44909. this.shapeId = shapeId;
  44910. this.idxInShape = idxInShape;
  44911. this._sps = sps;
  44912. if (modelBoundingInfo) {
  44913. this._modelBoundingInfo = modelBoundingInfo;
  44914. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44915. }
  44916. }
  44917. Object.defineProperty(SolidParticle.prototype, "scale", {
  44918. /**
  44919. * legacy support, changed scale to scaling
  44920. */
  44921. get: function () {
  44922. return this.scaling;
  44923. },
  44924. set: function (scale) {
  44925. this.scaling = scale;
  44926. },
  44927. enumerable: true,
  44928. configurable: true
  44929. });
  44930. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44931. /**
  44932. * legacy support, changed quaternion to rotationQuaternion
  44933. */
  44934. get: function () {
  44935. return this.rotationQuaternion;
  44936. },
  44937. set: function (q) {
  44938. this.rotationQuaternion = q;
  44939. },
  44940. enumerable: true,
  44941. configurable: true
  44942. });
  44943. /**
  44944. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44945. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44946. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44947. */
  44948. SolidParticle.prototype.intersectsMesh = function (target) {
  44949. if (!this._boundingInfo || !target._boundingInfo) {
  44950. return false;
  44951. }
  44952. if (this._sps._bSphereOnly) {
  44953. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44954. }
  44955. return this._boundingInfo.intersects(target._boundingInfo, false);
  44956. };
  44957. return SolidParticle;
  44958. }());
  44959. BABYLON.SolidParticle = SolidParticle;
  44960. var ModelShape = /** @class */ (function () {
  44961. /**
  44962. * 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.
  44963. * SPS internal tool, don't use it manually.
  44964. */
  44965. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44966. this._indicesLength = 0; // length of the shape in the model indices array
  44967. this.shapeID = id;
  44968. this._shape = shape;
  44969. this._indicesLength = indicesLength;
  44970. this._shapeUV = shapeUV;
  44971. this._positionFunction = posFunction;
  44972. this._vertexFunction = vtxFunction;
  44973. }
  44974. return ModelShape;
  44975. }());
  44976. BABYLON.ModelShape = ModelShape;
  44977. var DepthSortedParticle = /** @class */ (function () {
  44978. function DepthSortedParticle() {
  44979. this.ind = 0; // index of the particle in the "indices" array
  44980. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44981. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44982. }
  44983. return DepthSortedParticle;
  44984. }());
  44985. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44986. })(BABYLON || (BABYLON = {}));
  44987. //# sourceMappingURL=babylon.solidParticle.js.map
  44988. var BABYLON;
  44989. (function (BABYLON) {
  44990. /**
  44991. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44992. */
  44993. var SolidParticleSystem = /** @class */ (function () {
  44994. /**
  44995. * Creates a SPS (Solid Particle System) object.
  44996. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44997. * `scene` (Scene) is the scene in which the SPS is added.
  44998. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44999. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  45000. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  45001. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  45002. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  45003. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  45004. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  45005. */
  45006. function SolidParticleSystem(name, scene, options) {
  45007. // public members
  45008. /**
  45009. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  45010. * Example : var p = SPS.particles[i];
  45011. */
  45012. this.particles = new Array();
  45013. /**
  45014. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  45015. */
  45016. this.nbParticles = 0;
  45017. /**
  45018. * If the particles must ever face the camera (default false). Useful for planar particles.
  45019. */
  45020. this.billboard = false;
  45021. /**
  45022. * Recompute normals when adding a shape
  45023. */
  45024. this.recomputeNormals = true;
  45025. /**
  45026. * This a counter ofr your own usage. It's not set by any SPS functions.
  45027. */
  45028. this.counter = 0;
  45029. /**
  45030. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  45031. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  45032. */
  45033. this.vars = {};
  45034. this._positions = new Array();
  45035. this._indices = new Array();
  45036. this._normals = new Array();
  45037. this._colors = new Array();
  45038. this._uvs = new Array();
  45039. this._index = 0; // indices index
  45040. this._updatable = true;
  45041. this._pickable = false;
  45042. this._isVisibilityBoxLocked = false;
  45043. this._alwaysVisible = false;
  45044. this._depthSort = false;
  45045. this._shapeCounter = 0;
  45046. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  45047. this._color = new BABYLON.Color4(0, 0, 0, 0);
  45048. this._computeParticleColor = true;
  45049. this._computeParticleTexture = true;
  45050. this._computeParticleRotation = true;
  45051. this._computeParticleVertex = false;
  45052. this._computeBoundingBox = false;
  45053. this._depthSortParticles = true;
  45054. this._cam_axisZ = BABYLON.Vector3.Zero();
  45055. this._cam_axisY = BABYLON.Vector3.Zero();
  45056. this._cam_axisX = BABYLON.Vector3.Zero();
  45057. this._axisZ = BABYLON.Axis.Z;
  45058. this._camDir = BABYLON.Vector3.Zero();
  45059. this._camInvertedPosition = BABYLON.Vector3.Zero();
  45060. this._rotMatrix = new BABYLON.Matrix();
  45061. this._invertMatrix = new BABYLON.Matrix();
  45062. this._rotated = BABYLON.Vector3.Zero();
  45063. this._quaternion = new BABYLON.Quaternion();
  45064. this._vertex = BABYLON.Vector3.Zero();
  45065. this._normal = BABYLON.Vector3.Zero();
  45066. this._yaw = 0.0;
  45067. this._pitch = 0.0;
  45068. this._roll = 0.0;
  45069. this._halfroll = 0.0;
  45070. this._halfpitch = 0.0;
  45071. this._halfyaw = 0.0;
  45072. this._sinRoll = 0.0;
  45073. this._cosRoll = 0.0;
  45074. this._sinPitch = 0.0;
  45075. this._cosPitch = 0.0;
  45076. this._sinYaw = 0.0;
  45077. this._cosYaw = 0.0;
  45078. this._mustUnrotateFixedNormals = false;
  45079. this._minimum = BABYLON.Tmp.Vector3[0];
  45080. this._maximum = BABYLON.Tmp.Vector3[1];
  45081. this._minBbox = BABYLON.Tmp.Vector3[4];
  45082. this._maxBbox = BABYLON.Tmp.Vector3[5];
  45083. this._particlesIntersect = false;
  45084. this._depthSortFunction = function (p1, p2) {
  45085. return (p2.sqDistance - p1.sqDistance);
  45086. };
  45087. this._needs32Bits = false;
  45088. this._bSphereOnly = false;
  45089. this._bSphereRadiusFactor = 1.0;
  45090. this.name = name;
  45091. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45092. this._camera = scene.activeCamera;
  45093. this._pickable = options ? options.isPickable : false;
  45094. this._depthSort = options ? options.enableDepthSort : false;
  45095. this._particlesIntersect = options ? options.particleIntersection : false;
  45096. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  45097. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  45098. if (options && options.updatable) {
  45099. this._updatable = options.updatable;
  45100. }
  45101. else {
  45102. this._updatable = true;
  45103. }
  45104. if (this._pickable) {
  45105. this.pickedParticles = [];
  45106. }
  45107. if (this._depthSort) {
  45108. this.depthSortedParticles = [];
  45109. }
  45110. }
  45111. /**
  45112. * Builds the SPS underlying mesh. Returns a standard Mesh.
  45113. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  45114. */
  45115. SolidParticleSystem.prototype.buildMesh = function () {
  45116. if (this.nbParticles === 0) {
  45117. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  45118. this.addShape(triangle, 1);
  45119. triangle.dispose();
  45120. }
  45121. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  45122. this._positions32 = new Float32Array(this._positions);
  45123. this._uvs32 = new Float32Array(this._uvs);
  45124. this._colors32 = new Float32Array(this._colors);
  45125. if (this.recomputeNormals) {
  45126. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  45127. }
  45128. this._normals32 = new Float32Array(this._normals);
  45129. this._fixedNormal32 = new Float32Array(this._normals);
  45130. if (this._mustUnrotateFixedNormals) {
  45131. this._unrotateFixedNormals();
  45132. }
  45133. var vertexData = new BABYLON.VertexData();
  45134. vertexData.indices = this._indices32;
  45135. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  45136. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  45137. if (this._uvs32) {
  45138. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  45139. ;
  45140. }
  45141. if (this._colors32) {
  45142. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  45143. }
  45144. var mesh = new BABYLON.Mesh(this.name, this._scene);
  45145. vertexData.applyToMesh(mesh, this._updatable);
  45146. this.mesh = mesh;
  45147. this.mesh.isPickable = this._pickable;
  45148. // free memory
  45149. if (!this._depthSort) {
  45150. this._indices = null;
  45151. }
  45152. this._positions = null;
  45153. this._normals = null;
  45154. this._uvs = null;
  45155. this._colors = null;
  45156. if (!this._updatable) {
  45157. this.particles.length = 0;
  45158. }
  45159. return mesh;
  45160. };
  45161. /**
  45162. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  45163. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  45164. * Thus the particles generated from `digest()` have their property `position` set yet.
  45165. * `mesh` ( Mesh ) is the mesh to be digested
  45166. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  45167. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  45168. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  45169. */
  45170. SolidParticleSystem.prototype.digest = function (mesh, options) {
  45171. var size = (options && options.facetNb) || 1;
  45172. var number = (options && options.number) || 0;
  45173. var delta = (options && options.delta) || 0;
  45174. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45175. var meshInd = mesh.getIndices();
  45176. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45177. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45178. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45179. var f = 0; // facet counter
  45180. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  45181. // compute size from number
  45182. if (number) {
  45183. number = (number > totalFacets) ? totalFacets : number;
  45184. size = Math.round(totalFacets / number);
  45185. delta = 0;
  45186. }
  45187. else {
  45188. size = (size > totalFacets) ? totalFacets : size;
  45189. }
  45190. var facetPos = []; // submesh positions
  45191. var facetInd = []; // submesh indices
  45192. var facetUV = []; // submesh UV
  45193. var facetCol = []; // submesh colors
  45194. var barycenter = BABYLON.Tmp.Vector3[0];
  45195. var sizeO = size;
  45196. while (f < totalFacets) {
  45197. size = sizeO + Math.floor((1 + delta) * Math.random());
  45198. if (f > totalFacets - size) {
  45199. size = totalFacets - f;
  45200. }
  45201. // reset temp arrays
  45202. facetPos.length = 0;
  45203. facetInd.length = 0;
  45204. facetUV.length = 0;
  45205. facetCol.length = 0;
  45206. // iterate over "size" facets
  45207. var fi = 0;
  45208. for (var j = f * 3; j < (f + size) * 3; j++) {
  45209. facetInd.push(fi);
  45210. var i = meshInd[j];
  45211. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  45212. if (meshUV) {
  45213. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  45214. }
  45215. if (meshCol) {
  45216. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  45217. }
  45218. fi++;
  45219. }
  45220. // create a model shape for each single particle
  45221. var idx = this.nbParticles;
  45222. var shape = this._posToShape(facetPos);
  45223. var shapeUV = this._uvsToShapeUV(facetUV);
  45224. // compute the barycenter of the shape
  45225. var v;
  45226. for (v = 0; v < shape.length; v++) {
  45227. barycenter.addInPlace(shape[v]);
  45228. }
  45229. barycenter.scaleInPlace(1 / shape.length);
  45230. // shift the shape from its barycenter to the origin
  45231. for (v = 0; v < shape.length; v++) {
  45232. shape[v].subtractInPlace(barycenter);
  45233. }
  45234. var bInfo;
  45235. if (this._particlesIntersect) {
  45236. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  45237. }
  45238. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  45239. // add the particle in the SPS
  45240. var currentPos = this._positions.length;
  45241. var currentInd = this._indices.length;
  45242. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  45243. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  45244. // initialize the particle position
  45245. this.particles[this.nbParticles].position.addInPlace(barycenter);
  45246. this._index += shape.length;
  45247. idx++;
  45248. this.nbParticles++;
  45249. this._shapeCounter++;
  45250. f += size;
  45251. }
  45252. return this;
  45253. };
  45254. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  45255. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  45256. var index = 0;
  45257. var idx = 0;
  45258. for (var p = 0; p < this.particles.length; p++) {
  45259. this._particle = this.particles[p];
  45260. this._shape = this._particle._model._shape;
  45261. if (this._particle.rotationQuaternion) {
  45262. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45263. }
  45264. else {
  45265. this._yaw = this._particle.rotation.y;
  45266. this._pitch = this._particle.rotation.x;
  45267. this._roll = this._particle.rotation.z;
  45268. this._quaternionRotationYPR();
  45269. }
  45270. this._quaternionToRotationMatrix();
  45271. this._rotMatrix.invertToRef(this._invertMatrix);
  45272. for (var pt = 0; pt < this._shape.length; pt++) {
  45273. idx = index + pt * 3;
  45274. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  45275. this._fixedNormal32[idx] = this._normal.x;
  45276. this._fixedNormal32[idx + 1] = this._normal.y;
  45277. this._fixedNormal32[idx + 2] = this._normal.z;
  45278. }
  45279. index = idx + 3;
  45280. }
  45281. };
  45282. //reset copy
  45283. SolidParticleSystem.prototype._resetCopy = function () {
  45284. this._copy.position.x = 0;
  45285. this._copy.position.y = 0;
  45286. this._copy.position.z = 0;
  45287. this._copy.rotation.x = 0;
  45288. this._copy.rotation.y = 0;
  45289. this._copy.rotation.z = 0;
  45290. this._copy.rotationQuaternion = null;
  45291. this._copy.scaling.x = 1.0;
  45292. this._copy.scaling.y = 1.0;
  45293. this._copy.scaling.z = 1.0;
  45294. this._copy.uvs.x = 0;
  45295. this._copy.uvs.y = 0;
  45296. this._copy.uvs.z = 1.0;
  45297. this._copy.uvs.w = 1.0;
  45298. this._copy.color = null;
  45299. };
  45300. // _meshBuilder : inserts the shape model in the global SPS mesh
  45301. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  45302. var i;
  45303. var u = 0;
  45304. var c = 0;
  45305. var n = 0;
  45306. this._resetCopy();
  45307. if (options && options.positionFunction) {
  45308. options.positionFunction(this._copy, idx, idxInShape);
  45309. this._mustUnrotateFixedNormals = true;
  45310. }
  45311. if (this._copy.rotationQuaternion) {
  45312. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45313. }
  45314. else {
  45315. this._yaw = this._copy.rotation.y;
  45316. this._pitch = this._copy.rotation.x;
  45317. this._roll = this._copy.rotation.z;
  45318. this._quaternionRotationYPR();
  45319. }
  45320. this._quaternionToRotationMatrix();
  45321. for (i = 0; i < shape.length; i++) {
  45322. this._vertex.x = shape[i].x;
  45323. this._vertex.y = shape[i].y;
  45324. this._vertex.z = shape[i].z;
  45325. if (options && options.vertexFunction) {
  45326. options.vertexFunction(this._copy, this._vertex, i);
  45327. }
  45328. this._vertex.x *= this._copy.scaling.x;
  45329. this._vertex.y *= this._copy.scaling.y;
  45330. this._vertex.z *= this._copy.scaling.z;
  45331. this._vertex.x += this._copy.pivot.x;
  45332. this._vertex.y += this._copy.pivot.y;
  45333. this._vertex.z += this._copy.pivot.z;
  45334. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45335. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  45336. if (meshUV) {
  45337. 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);
  45338. u += 2;
  45339. }
  45340. if (this._copy.color) {
  45341. this._color = this._copy.color;
  45342. }
  45343. else if (meshCol && meshCol[c] !== undefined) {
  45344. this._color.r = meshCol[c];
  45345. this._color.g = meshCol[c + 1];
  45346. this._color.b = meshCol[c + 2];
  45347. this._color.a = meshCol[c + 3];
  45348. }
  45349. else {
  45350. this._color.r = 1.0;
  45351. this._color.g = 1.0;
  45352. this._color.b = 1.0;
  45353. this._color.a = 1.0;
  45354. }
  45355. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45356. c += 4;
  45357. if (!this.recomputeNormals && meshNor) {
  45358. this._normal.x = meshNor[n];
  45359. this._normal.y = meshNor[n + 1];
  45360. this._normal.z = meshNor[n + 2];
  45361. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45362. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45363. n += 3;
  45364. }
  45365. }
  45366. for (i = 0; i < meshInd.length; i++) {
  45367. var current_ind = p + meshInd[i];
  45368. indices.push(current_ind);
  45369. if (current_ind > 65535) {
  45370. this._needs32Bits = true;
  45371. }
  45372. }
  45373. if (this._pickable) {
  45374. var nbfaces = meshInd.length / 3;
  45375. for (i = 0; i < nbfaces; i++) {
  45376. this.pickedParticles.push({ idx: idx, faceId: i });
  45377. }
  45378. }
  45379. if (this._depthSort) {
  45380. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45381. }
  45382. return this._copy;
  45383. };
  45384. // returns a shape array from positions array
  45385. SolidParticleSystem.prototype._posToShape = function (positions) {
  45386. var shape = [];
  45387. for (var i = 0; i < positions.length; i += 3) {
  45388. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45389. }
  45390. return shape;
  45391. };
  45392. // returns a shapeUV array from a Vector4 uvs
  45393. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45394. var shapeUV = [];
  45395. if (uvs) {
  45396. for (var i = 0; i < uvs.length; i++)
  45397. shapeUV.push(uvs[i]);
  45398. }
  45399. return shapeUV;
  45400. };
  45401. // adds a new particle object in the particles array
  45402. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45403. if (bInfo === void 0) { bInfo = null; }
  45404. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45405. this.particles.push(sp);
  45406. return sp;
  45407. };
  45408. /**
  45409. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45410. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45411. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45412. * `nb` (positive integer) the number of particles to be created from this model
  45413. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45414. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45415. */
  45416. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45417. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45418. var meshInd = mesh.getIndices();
  45419. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45420. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45421. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45422. var bbInfo;
  45423. if (this._particlesIntersect) {
  45424. bbInfo = mesh.getBoundingInfo();
  45425. }
  45426. var shape = this._posToShape(meshPos);
  45427. var shapeUV = this._uvsToShapeUV(meshUV);
  45428. var posfunc = options ? options.positionFunction : null;
  45429. var vtxfunc = options ? options.vertexFunction : null;
  45430. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45431. // particles
  45432. var sp;
  45433. var currentCopy;
  45434. var idx = this.nbParticles;
  45435. for (var i = 0; i < nb; i++) {
  45436. var currentPos = this._positions.length;
  45437. var currentInd = this._indices.length;
  45438. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45439. if (this._updatable) {
  45440. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45441. sp.position.copyFrom(currentCopy.position);
  45442. sp.rotation.copyFrom(currentCopy.rotation);
  45443. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45444. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45445. }
  45446. if (currentCopy.color && sp.color) {
  45447. sp.color.copyFrom(currentCopy.color);
  45448. }
  45449. sp.scaling.copyFrom(currentCopy.scaling);
  45450. sp.uvs.copyFrom(currentCopy.uvs);
  45451. }
  45452. this._index += shape.length;
  45453. idx++;
  45454. }
  45455. this.nbParticles += nb;
  45456. this._shapeCounter++;
  45457. return this._shapeCounter - 1;
  45458. };
  45459. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45460. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45461. this._resetCopy();
  45462. if (particle._model._positionFunction) {
  45463. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45464. }
  45465. if (this._copy.rotationQuaternion) {
  45466. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45467. }
  45468. else {
  45469. this._yaw = this._copy.rotation.y;
  45470. this._pitch = this._copy.rotation.x;
  45471. this._roll = this._copy.rotation.z;
  45472. this._quaternionRotationYPR();
  45473. }
  45474. this._quaternionToRotationMatrix();
  45475. this._shape = particle._model._shape;
  45476. for (var pt = 0; pt < this._shape.length; pt++) {
  45477. this._vertex.x = this._shape[pt].x;
  45478. this._vertex.y = this._shape[pt].y;
  45479. this._vertex.z = this._shape[pt].z;
  45480. if (particle._model._vertexFunction) {
  45481. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45482. }
  45483. this._vertex.x *= this._copy.scaling.x;
  45484. this._vertex.y *= this._copy.scaling.y;
  45485. this._vertex.z *= this._copy.scaling.z;
  45486. this._vertex.x += this._copy.pivot.x;
  45487. this._vertex.y += this._copy.pivot.y;
  45488. this._vertex.z += this._copy.pivot.z;
  45489. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45490. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45491. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45492. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45493. }
  45494. particle.position.x = 0.0;
  45495. particle.position.y = 0.0;
  45496. particle.position.z = 0.0;
  45497. particle.rotation.x = 0.0;
  45498. particle.rotation.y = 0.0;
  45499. particle.rotation.z = 0.0;
  45500. particle.rotationQuaternion = null;
  45501. particle.scaling.x = 1.0;
  45502. particle.scaling.y = 1.0;
  45503. particle.scaling.z = 1.0;
  45504. };
  45505. /**
  45506. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45507. * Returns the SPS.
  45508. */
  45509. SolidParticleSystem.prototype.rebuildMesh = function () {
  45510. for (var p = 0; p < this.particles.length; p++) {
  45511. this._rebuildParticle(this.particles[p]);
  45512. }
  45513. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45514. return this;
  45515. };
  45516. /**
  45517. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45518. * This method calls `updateParticle()` for each particle of the SPS.
  45519. * For an animated SPS, it is usually called within the render loop.
  45520. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45521. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45522. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45523. * Returns the SPS.
  45524. */
  45525. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45526. if (start === void 0) { start = 0; }
  45527. if (end === void 0) { end = this.nbParticles - 1; }
  45528. if (update === void 0) { update = true; }
  45529. if (!this._updatable) {
  45530. return this;
  45531. }
  45532. // custom beforeUpdate
  45533. this.beforeUpdateParticles(start, end, update);
  45534. this._cam_axisX.x = 1.0;
  45535. this._cam_axisX.y = 0.0;
  45536. this._cam_axisX.z = 0.0;
  45537. this._cam_axisY.x = 0.0;
  45538. this._cam_axisY.y = 1.0;
  45539. this._cam_axisY.z = 0.0;
  45540. this._cam_axisZ.x = 0.0;
  45541. this._cam_axisZ.y = 0.0;
  45542. this._cam_axisZ.z = 1.0;
  45543. // cases when the World Matrix is to be computed first
  45544. if (this.billboard || this._depthSort) {
  45545. this.mesh.computeWorldMatrix(true);
  45546. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45547. }
  45548. // if the particles will always face the camera
  45549. if (this.billboard) {
  45550. // compute the camera position and un-rotate it by the current mesh rotation
  45551. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45552. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45553. this._cam_axisZ.normalize();
  45554. // same for camera up vector extracted from the cam view matrix
  45555. var view = this._camera.getViewMatrix(true);
  45556. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45557. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45558. this._cam_axisY.normalize();
  45559. this._cam_axisX.normalize();
  45560. }
  45561. // if depthSort, compute the camera global position in the mesh local system
  45562. if (this._depthSort) {
  45563. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45564. }
  45565. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45566. var idx = 0; // current position index in the global array positions32
  45567. var index = 0; // position start index in the global array positions32 of the current particle
  45568. var colidx = 0; // current color index in the global array colors32
  45569. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45570. var uvidx = 0; // current uv index in the global array uvs32
  45571. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45572. var pt = 0; // current index in the particle model shape
  45573. if (this.mesh.isFacetDataEnabled) {
  45574. this._computeBoundingBox = true;
  45575. }
  45576. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45577. if (this._computeBoundingBox) {
  45578. if (start == 0 && end == this.nbParticles - 1) {
  45579. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45580. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45581. }
  45582. else {
  45583. if (this.mesh._boundingInfo) {
  45584. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45585. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45586. }
  45587. }
  45588. }
  45589. // particle loop
  45590. index = this.particles[start]._pos;
  45591. var vpos = (index / 3) | 0;
  45592. colorIndex = vpos * 4;
  45593. uvIndex = vpos * 2;
  45594. for (var p = start; p <= end; p++) {
  45595. this._particle = this.particles[p];
  45596. this._shape = this._particle._model._shape;
  45597. this._shapeUV = this._particle._model._shapeUV;
  45598. // call to custom user function to update the particle properties
  45599. this.updateParticle(this._particle);
  45600. // camera-particle distance for depth sorting
  45601. if (this._depthSort && this._depthSortParticles) {
  45602. var dsp = this.depthSortedParticles[p];
  45603. dsp.ind = this._particle._ind;
  45604. dsp.indicesLength = this._particle._model._indicesLength;
  45605. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45606. }
  45607. // skip the computations for inactive or already invisible particles
  45608. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45609. // increment indexes for the next particle
  45610. pt = this._shape.length;
  45611. index += pt * 3;
  45612. colorIndex += pt * 4;
  45613. uvIndex += pt * 2;
  45614. continue;
  45615. }
  45616. if (this._particle.isVisible) {
  45617. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45618. // particle rotation matrix
  45619. if (this.billboard) {
  45620. this._particle.rotation.x = 0.0;
  45621. this._particle.rotation.y = 0.0;
  45622. }
  45623. if (this._computeParticleRotation || this.billboard) {
  45624. if (this._particle.rotationQuaternion) {
  45625. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45626. }
  45627. else {
  45628. this._yaw = this._particle.rotation.y;
  45629. this._pitch = this._particle.rotation.x;
  45630. this._roll = this._particle.rotation.z;
  45631. this._quaternionRotationYPR();
  45632. }
  45633. this._quaternionToRotationMatrix();
  45634. }
  45635. // particle vertex loop
  45636. for (pt = 0; pt < this._shape.length; pt++) {
  45637. idx = index + pt * 3;
  45638. colidx = colorIndex + pt * 4;
  45639. uvidx = uvIndex + pt * 2;
  45640. this._vertex.x = this._shape[pt].x;
  45641. this._vertex.y = this._shape[pt].y;
  45642. this._vertex.z = this._shape[pt].z;
  45643. if (this._computeParticleVertex) {
  45644. this.updateParticleVertex(this._particle, this._vertex, pt);
  45645. }
  45646. // positions
  45647. this._vertex.x *= this._particle.scaling.x;
  45648. this._vertex.y *= this._particle.scaling.y;
  45649. this._vertex.z *= this._particle.scaling.z;
  45650. this._vertex.x += this._particle.pivot.x;
  45651. this._vertex.y += this._particle.pivot.y;
  45652. this._vertex.z += this._particle.pivot.z;
  45653. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45654. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45655. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45656. this._positions32[idx] = 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;
  45657. this._positions32[idx + 1] = 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;
  45658. this._positions32[idx + 2] = 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;
  45659. if (this._computeBoundingBox) {
  45660. if (this._positions32[idx] < this._minimum.x) {
  45661. this._minimum.x = this._positions32[idx];
  45662. }
  45663. if (this._positions32[idx] > this._maximum.x) {
  45664. this._maximum.x = this._positions32[idx];
  45665. }
  45666. if (this._positions32[idx + 1] < this._minimum.y) {
  45667. this._minimum.y = this._positions32[idx + 1];
  45668. }
  45669. if (this._positions32[idx + 1] > this._maximum.y) {
  45670. this._maximum.y = this._positions32[idx + 1];
  45671. }
  45672. if (this._positions32[idx + 2] < this._minimum.z) {
  45673. this._minimum.z = this._positions32[idx + 2];
  45674. }
  45675. if (this._positions32[idx + 2] > this._maximum.z) {
  45676. this._maximum.z = this._positions32[idx + 2];
  45677. }
  45678. }
  45679. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45680. if (!this._computeParticleVertex) {
  45681. this._normal.x = this._fixedNormal32[idx];
  45682. this._normal.y = this._fixedNormal32[idx + 1];
  45683. this._normal.z = this._fixedNormal32[idx + 2];
  45684. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45685. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45686. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45687. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45688. 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;
  45689. 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;
  45690. }
  45691. if (this._computeParticleColor && this._particle.color) {
  45692. this._colors32[colidx] = this._particle.color.r;
  45693. this._colors32[colidx + 1] = this._particle.color.g;
  45694. this._colors32[colidx + 2] = this._particle.color.b;
  45695. this._colors32[colidx + 3] = this._particle.color.a;
  45696. }
  45697. if (this._computeParticleTexture) {
  45698. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45699. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45700. }
  45701. }
  45702. }
  45703. else {
  45704. this._particle._stillInvisible = true; // mark the particle as invisible
  45705. for (pt = 0; pt < this._shape.length; pt++) {
  45706. idx = index + pt * 3;
  45707. colidx = colorIndex + pt * 4;
  45708. uvidx = uvIndex + pt * 2;
  45709. this._positions32[idx] = 0.0;
  45710. this._positions32[idx + 1] = 0.0;
  45711. this._positions32[idx + 2] = 0.0;
  45712. this._normals32[idx] = 0.0;
  45713. this._normals32[idx + 1] = 0.0;
  45714. this._normals32[idx + 2] = 0.0;
  45715. if (this._computeParticleColor && this._particle.color) {
  45716. this._colors32[colidx] = this._particle.color.r;
  45717. this._colors32[colidx + 1] = this._particle.color.g;
  45718. this._colors32[colidx + 2] = this._particle.color.b;
  45719. this._colors32[colidx + 3] = this._particle.color.a;
  45720. }
  45721. if (this._computeParticleTexture) {
  45722. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45723. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45724. }
  45725. }
  45726. }
  45727. // if the particle intersections must be computed : update the bbInfo
  45728. if (this._particlesIntersect) {
  45729. var bInfo = this._particle._boundingInfo;
  45730. var bBox = bInfo.boundingBox;
  45731. var bSphere = bInfo.boundingSphere;
  45732. if (!this._bSphereOnly) {
  45733. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45734. for (var b = 0; b < bBox.vectors.length; b++) {
  45735. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45736. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45737. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45738. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45739. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45740. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45741. 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;
  45742. 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;
  45743. 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;
  45744. }
  45745. bBox._update(this.mesh._worldMatrix);
  45746. }
  45747. // place and scale the particle bouding sphere in the SPS local system, then update it
  45748. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45749. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45750. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45751. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45752. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45753. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45754. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45755. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45756. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45757. 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));
  45758. bSphere._update(this.mesh._worldMatrix);
  45759. }
  45760. // increment indexes for the next particle
  45761. index = idx + 3;
  45762. colorIndex = colidx + 4;
  45763. uvIndex = uvidx + 2;
  45764. }
  45765. // if the VBO must be updated
  45766. if (update) {
  45767. if (this._computeParticleColor) {
  45768. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45769. }
  45770. if (this._computeParticleTexture) {
  45771. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45772. }
  45773. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45774. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45775. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45776. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45777. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45778. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45779. for (var i = 0; i < this._normals32.length; i++) {
  45780. this._fixedNormal32[i] = this._normals32[i];
  45781. }
  45782. }
  45783. if (!this.mesh.areNormalsFrozen) {
  45784. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45785. }
  45786. }
  45787. if (this._depthSort && this._depthSortParticles) {
  45788. this.depthSortedParticles.sort(this._depthSortFunction);
  45789. var dspl = this.depthSortedParticles.length;
  45790. var sorted = 0;
  45791. var lind = 0;
  45792. var sind = 0;
  45793. var sid = 0;
  45794. for (sorted = 0; sorted < dspl; sorted++) {
  45795. lind = this.depthSortedParticles[sorted].indicesLength;
  45796. sind = this.depthSortedParticles[sorted].ind;
  45797. for (var i = 0; i < lind; i++) {
  45798. this._indices32[sid] = this._indices[sind + i];
  45799. sid++;
  45800. }
  45801. }
  45802. this.mesh.updateIndices(this._indices32);
  45803. }
  45804. }
  45805. if (this._computeBoundingBox) {
  45806. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45807. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45808. }
  45809. this.afterUpdateParticles(start, end, update);
  45810. return this;
  45811. };
  45812. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45813. this._halfroll = this._roll * 0.5;
  45814. this._halfpitch = this._pitch * 0.5;
  45815. this._halfyaw = this._yaw * 0.5;
  45816. this._sinRoll = Math.sin(this._halfroll);
  45817. this._cosRoll = Math.cos(this._halfroll);
  45818. this._sinPitch = Math.sin(this._halfpitch);
  45819. this._cosPitch = Math.cos(this._halfpitch);
  45820. this._sinYaw = Math.sin(this._halfyaw);
  45821. this._cosYaw = Math.cos(this._halfyaw);
  45822. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45823. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45824. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45825. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45826. };
  45827. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45828. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45829. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45830. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45831. this._rotMatrix.m[3] = 0;
  45832. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45833. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45834. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45835. this._rotMatrix.m[7] = 0;
  45836. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45837. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45838. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45839. this._rotMatrix.m[11] = 0;
  45840. this._rotMatrix.m[12] = 0;
  45841. this._rotMatrix.m[13] = 0;
  45842. this._rotMatrix.m[14] = 0;
  45843. this._rotMatrix.m[15] = 1.0;
  45844. };
  45845. /**
  45846. * Disposes the SPS.
  45847. * Returns nothing.
  45848. */
  45849. SolidParticleSystem.prototype.dispose = function () {
  45850. this.mesh.dispose();
  45851. this.vars = null;
  45852. // drop references to internal big arrays for the GC
  45853. this._positions = null;
  45854. this._indices = null;
  45855. this._normals = null;
  45856. this._uvs = null;
  45857. this._colors = null;
  45858. this._indices32 = null;
  45859. this._positions32 = null;
  45860. this._normals32 = null;
  45861. this._fixedNormal32 = null;
  45862. this._uvs32 = null;
  45863. this._colors32 = null;
  45864. this.pickedParticles = null;
  45865. };
  45866. /**
  45867. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45868. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45869. * Returns the SPS.
  45870. */
  45871. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45872. if (!this._isVisibilityBoxLocked) {
  45873. this.mesh.refreshBoundingInfo();
  45874. }
  45875. return this;
  45876. };
  45877. /**
  45878. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45879. * @param size the size (float) of the visibility box
  45880. * note : this doesn't lock the SPS mesh bounding box.
  45881. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45882. */
  45883. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45884. var vis = size / 2;
  45885. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45886. };
  45887. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45888. // getter and setter
  45889. get: function () {
  45890. return this._alwaysVisible;
  45891. },
  45892. /**
  45893. * Sets the SPS as always visible or not
  45894. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45895. */
  45896. set: function (val) {
  45897. this._alwaysVisible = val;
  45898. this.mesh.alwaysSelectAsActiveMesh = val;
  45899. },
  45900. enumerable: true,
  45901. configurable: true
  45902. });
  45903. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45904. get: function () {
  45905. return this._isVisibilityBoxLocked;
  45906. },
  45907. /**
  45908. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45909. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45910. */
  45911. set: function (val) {
  45912. this._isVisibilityBoxLocked = val;
  45913. var boundingInfo = this.mesh.getBoundingInfo();
  45914. if (boundingInfo) {
  45915. boundingInfo.isLocked = val;
  45916. }
  45917. },
  45918. enumerable: true,
  45919. configurable: true
  45920. });
  45921. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45922. // getters
  45923. get: function () {
  45924. return this._computeParticleRotation;
  45925. },
  45926. // Optimizer setters
  45927. /**
  45928. * Tells to `setParticles()` to compute the particle rotations or not.
  45929. * Default value : true. The SPS is faster when it's set to false.
  45930. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45931. */
  45932. set: function (val) {
  45933. this._computeParticleRotation = val;
  45934. },
  45935. enumerable: true,
  45936. configurable: true
  45937. });
  45938. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45939. get: function () {
  45940. return this._computeParticleColor;
  45941. },
  45942. /**
  45943. * Tells to `setParticles()` to compute the particle colors or not.
  45944. * Default value : true. The SPS is faster when it's set to false.
  45945. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45946. */
  45947. set: function (val) {
  45948. this._computeParticleColor = val;
  45949. },
  45950. enumerable: true,
  45951. configurable: true
  45952. });
  45953. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45954. get: function () {
  45955. return this._computeParticleTexture;
  45956. },
  45957. /**
  45958. * Tells to `setParticles()` to compute the particle textures or not.
  45959. * Default value : true. The SPS is faster when it's set to false.
  45960. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45961. */
  45962. set: function (val) {
  45963. this._computeParticleTexture = val;
  45964. },
  45965. enumerable: true,
  45966. configurable: true
  45967. });
  45968. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45969. get: function () {
  45970. return this._computeParticleVertex;
  45971. },
  45972. /**
  45973. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45974. * Default value : false. The SPS is faster when it's set to false.
  45975. * Note : the particle custom vertex positions aren't stored values.
  45976. */
  45977. set: function (val) {
  45978. this._computeParticleVertex = val;
  45979. },
  45980. enumerable: true,
  45981. configurable: true
  45982. });
  45983. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45984. get: function () {
  45985. return this._computeBoundingBox;
  45986. },
  45987. /**
  45988. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45989. */
  45990. set: function (val) {
  45991. this._computeBoundingBox = val;
  45992. },
  45993. enumerable: true,
  45994. configurable: true
  45995. });
  45996. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45997. get: function () {
  45998. return this._depthSortParticles;
  45999. },
  46000. /**
  46001. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  46002. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  46003. * Default : `true`
  46004. */
  46005. set: function (val) {
  46006. this._depthSortParticles = val;
  46007. },
  46008. enumerable: true,
  46009. configurable: true
  46010. });
  46011. // =======================================================================
  46012. // Particle behavior logic
  46013. // these following methods may be overwritten by the user to fit his needs
  46014. /**
  46015. * This function does nothing. It may be overwritten to set all the particle first values.
  46016. * The SPS doesn't call this function, you may have to call it by your own.
  46017. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46018. */
  46019. SolidParticleSystem.prototype.initParticles = function () {
  46020. };
  46021. /**
  46022. * This function does nothing. It may be overwritten to recycle a particle.
  46023. * The SPS doesn't call this function, you may have to call it by your own.
  46024. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46025. */
  46026. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  46027. return particle;
  46028. };
  46029. /**
  46030. * Updates a particle : this function should be overwritten by the user.
  46031. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  46032. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46033. * ex : just set a particle position or velocity and recycle conditions
  46034. */
  46035. SolidParticleSystem.prototype.updateParticle = function (particle) {
  46036. return particle;
  46037. };
  46038. /**
  46039. * Updates a vertex of a particle : it can be overwritten by the user.
  46040. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  46041. * @param particle the current particle
  46042. * @param vertex the current index of the current particle
  46043. * @param pt the index of the current vertex in the particle shape
  46044. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  46045. * ex : just set a vertex particle position
  46046. */
  46047. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  46048. return vertex;
  46049. };
  46050. /**
  46051. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  46052. * This does nothing and may be overwritten by the user.
  46053. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46054. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46055. * @param update the boolean update value actually passed to setParticles()
  46056. */
  46057. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  46058. };
  46059. /**
  46060. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  46061. * This will be passed three parameters.
  46062. * This does nothing and may be overwritten by the user.
  46063. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46064. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46065. * @param update the boolean update value actually passed to setParticles()
  46066. */
  46067. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  46068. };
  46069. return SolidParticleSystem;
  46070. }());
  46071. BABYLON.SolidParticleSystem = SolidParticleSystem;
  46072. })(BABYLON || (BABYLON = {}));
  46073. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  46074. var BABYLON;
  46075. (function (BABYLON) {
  46076. var GroundMesh = /** @class */ (function (_super) {
  46077. __extends(GroundMesh, _super);
  46078. function GroundMesh(name, scene) {
  46079. var _this = _super.call(this, name, scene) || this;
  46080. _this.generateOctree = false;
  46081. return _this;
  46082. }
  46083. GroundMesh.prototype.getClassName = function () {
  46084. return "GroundMesh";
  46085. };
  46086. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  46087. get: function () {
  46088. return Math.min(this._subdivisionsX, this._subdivisionsY);
  46089. },
  46090. enumerable: true,
  46091. configurable: true
  46092. });
  46093. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  46094. get: function () {
  46095. return this._subdivisionsX;
  46096. },
  46097. enumerable: true,
  46098. configurable: true
  46099. });
  46100. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  46101. get: function () {
  46102. return this._subdivisionsY;
  46103. },
  46104. enumerable: true,
  46105. configurable: true
  46106. });
  46107. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  46108. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  46109. this._subdivisionsX = chunksCount;
  46110. this._subdivisionsY = chunksCount;
  46111. this.subdivide(chunksCount);
  46112. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  46113. };
  46114. /**
  46115. * Returns a height (y) value in the Worl system :
  46116. * the ground altitude at the coordinates (x, z) expressed in the World system.
  46117. * Returns the ground y position if (x, z) are outside the ground surface.
  46118. */
  46119. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  46120. var world = this.getWorldMatrix();
  46121. var invMat = BABYLON.Tmp.Matrix[5];
  46122. world.invertToRef(invMat);
  46123. var tmpVect = BABYLON.Tmp.Vector3[8];
  46124. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  46125. x = tmpVect.x;
  46126. z = tmpVect.z;
  46127. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46128. return this.position.y;
  46129. }
  46130. if (!this._heightQuads || this._heightQuads.length == 0) {
  46131. this._initHeightQuads();
  46132. this._computeHeightQuads();
  46133. }
  46134. var facet = this._getFacetAt(x, z);
  46135. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  46136. // return y in the World system
  46137. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  46138. return tmpVect.y;
  46139. };
  46140. /**
  46141. * Returns a normalized vector (Vector3) orthogonal to the ground
  46142. * at the ground coordinates (x, z) expressed in the World system.
  46143. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  46144. */
  46145. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  46146. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  46147. this.getNormalAtCoordinatesToRef(x, z, normal);
  46148. return normal;
  46149. };
  46150. /**
  46151. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  46152. * at the ground coordinates (x, z) expressed in the World system.
  46153. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  46154. * Returns the GroundMesh.
  46155. */
  46156. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  46157. var world = this.getWorldMatrix();
  46158. var tmpMat = BABYLON.Tmp.Matrix[5];
  46159. world.invertToRef(tmpMat);
  46160. var tmpVect = BABYLON.Tmp.Vector3[8];
  46161. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  46162. x = tmpVect.x;
  46163. z = tmpVect.z;
  46164. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46165. return this;
  46166. }
  46167. if (!this._heightQuads || this._heightQuads.length == 0) {
  46168. this._initHeightQuads();
  46169. this._computeHeightQuads();
  46170. }
  46171. var facet = this._getFacetAt(x, z);
  46172. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  46173. return this;
  46174. };
  46175. /**
  46176. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  46177. * if the ground has been updated.
  46178. * This can be used in the render loop.
  46179. * Returns the GroundMesh.
  46180. */
  46181. GroundMesh.prototype.updateCoordinateHeights = function () {
  46182. if (!this._heightQuads || this._heightQuads.length == 0) {
  46183. this._initHeightQuads();
  46184. }
  46185. this._computeHeightQuads();
  46186. return this;
  46187. };
  46188. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  46189. GroundMesh.prototype._getFacetAt = function (x, z) {
  46190. // retrieve col and row from x, z coordinates in the ground local system
  46191. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  46192. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  46193. var quad = this._heightQuads[row * this._subdivisionsX + col];
  46194. var facet;
  46195. if (z < quad.slope.x * x + quad.slope.y) {
  46196. facet = quad.facet1;
  46197. }
  46198. else {
  46199. facet = quad.facet2;
  46200. }
  46201. return facet;
  46202. };
  46203. // Creates and populates the heightMap array with "facet" elements :
  46204. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  46205. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46206. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46207. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46208. // Returns the GroundMesh.
  46209. GroundMesh.prototype._initHeightQuads = function () {
  46210. var subdivisionsX = this._subdivisionsX;
  46211. var subdivisionsY = this._subdivisionsY;
  46212. this._heightQuads = new Array();
  46213. for (var row = 0; row < subdivisionsY; row++) {
  46214. for (var col = 0; col < subdivisionsX; col++) {
  46215. 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) };
  46216. this._heightQuads[row * subdivisionsX + col] = quad;
  46217. }
  46218. }
  46219. return this;
  46220. };
  46221. // Compute each quad element values and update the the heightMap array :
  46222. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46223. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46224. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46225. // Returns the GroundMesh.
  46226. GroundMesh.prototype._computeHeightQuads = function () {
  46227. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46228. if (!positions) {
  46229. return this;
  46230. }
  46231. var v1 = BABYLON.Tmp.Vector3[3];
  46232. var v2 = BABYLON.Tmp.Vector3[2];
  46233. var v3 = BABYLON.Tmp.Vector3[1];
  46234. var v4 = BABYLON.Tmp.Vector3[0];
  46235. var v1v2 = BABYLON.Tmp.Vector3[4];
  46236. var v1v3 = BABYLON.Tmp.Vector3[5];
  46237. var v1v4 = BABYLON.Tmp.Vector3[6];
  46238. var norm1 = BABYLON.Tmp.Vector3[7];
  46239. var norm2 = BABYLON.Tmp.Vector3[8];
  46240. var i = 0;
  46241. var j = 0;
  46242. var k = 0;
  46243. var cd = 0; // 2D slope coefficient : z = cd * x + h
  46244. var h = 0;
  46245. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  46246. var d2 = 0;
  46247. var subdivisionsX = this._subdivisionsX;
  46248. var subdivisionsY = this._subdivisionsY;
  46249. for (var row = 0; row < subdivisionsY; row++) {
  46250. for (var col = 0; col < subdivisionsX; col++) {
  46251. i = col * 3;
  46252. j = row * (subdivisionsX + 1) * 3;
  46253. k = (row + 1) * (subdivisionsX + 1) * 3;
  46254. v1.x = positions[j + i];
  46255. v1.y = positions[j + i + 1];
  46256. v1.z = positions[j + i + 2];
  46257. v2.x = positions[j + i + 3];
  46258. v2.y = positions[j + i + 4];
  46259. v2.z = positions[j + i + 5];
  46260. v3.x = positions[k + i];
  46261. v3.y = positions[k + i + 1];
  46262. v3.z = positions[k + i + 2];
  46263. v4.x = positions[k + i + 3];
  46264. v4.y = positions[k + i + 4];
  46265. v4.z = positions[k + i + 5];
  46266. // 2D slope V1V4
  46267. cd = (v4.z - v1.z) / (v4.x - v1.x);
  46268. h = v1.z - cd * v1.x; // v1 belongs to the slope
  46269. // facet equations :
  46270. // we compute each facet normal vector
  46271. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  46272. // we compute the value d by applying the equation to v1 which belongs to the plane
  46273. // then we store the facet equation in a Vector4
  46274. v2.subtractToRef(v1, v1v2);
  46275. v3.subtractToRef(v1, v1v3);
  46276. v4.subtractToRef(v1, v1v4);
  46277. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  46278. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  46279. norm1.normalize();
  46280. norm2.normalize();
  46281. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  46282. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  46283. var quad = this._heightQuads[row * subdivisionsX + col];
  46284. quad.slope.copyFromFloats(cd, h);
  46285. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  46286. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  46287. }
  46288. }
  46289. return this;
  46290. };
  46291. GroundMesh.prototype.serialize = function (serializationObject) {
  46292. _super.prototype.serialize.call(this, serializationObject);
  46293. serializationObject.subdivisionsX = this._subdivisionsX;
  46294. serializationObject.subdivisionsY = this._subdivisionsY;
  46295. serializationObject.minX = this._minX;
  46296. serializationObject.maxX = this._maxX;
  46297. serializationObject.minZ = this._minZ;
  46298. serializationObject.maxZ = this._maxZ;
  46299. serializationObject.width = this._width;
  46300. serializationObject.height = this._height;
  46301. };
  46302. GroundMesh.Parse = function (parsedMesh, scene) {
  46303. var result = new GroundMesh(parsedMesh.name, scene);
  46304. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  46305. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  46306. result._minX = parsedMesh.minX;
  46307. result._maxX = parsedMesh.maxX;
  46308. result._minZ = parsedMesh.minZ;
  46309. result._maxZ = parsedMesh.maxZ;
  46310. result._width = parsedMesh.width;
  46311. result._height = parsedMesh.height;
  46312. return result;
  46313. };
  46314. return GroundMesh;
  46315. }(BABYLON.Mesh));
  46316. BABYLON.GroundMesh = GroundMesh;
  46317. })(BABYLON || (BABYLON = {}));
  46318. //# sourceMappingURL=babylon.groundMesh.js.map
  46319. var BABYLON;
  46320. (function (BABYLON) {
  46321. /**
  46322. * Creates an instance based on a source mesh.
  46323. */
  46324. var InstancedMesh = /** @class */ (function (_super) {
  46325. __extends(InstancedMesh, _super);
  46326. function InstancedMesh(name, source) {
  46327. var _this = _super.call(this, name, source.getScene()) || this;
  46328. source.instances.push(_this);
  46329. _this._sourceMesh = source;
  46330. _this.position.copyFrom(source.position);
  46331. _this.rotation.copyFrom(source.rotation);
  46332. _this.scaling.copyFrom(source.scaling);
  46333. if (source.rotationQuaternion) {
  46334. _this.rotationQuaternion = source.rotationQuaternion.clone();
  46335. }
  46336. _this.infiniteDistance = source.infiniteDistance;
  46337. _this.setPivotMatrix(source.getPivotMatrix());
  46338. _this.refreshBoundingInfo();
  46339. _this._syncSubMeshes();
  46340. return _this;
  46341. }
  46342. /**
  46343. * Returns the string "InstancedMesh".
  46344. */
  46345. InstancedMesh.prototype.getClassName = function () {
  46346. return "InstancedMesh";
  46347. };
  46348. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46349. // Methods
  46350. get: function () {
  46351. return this._sourceMesh.receiveShadows;
  46352. },
  46353. enumerable: true,
  46354. configurable: true
  46355. });
  46356. Object.defineProperty(InstancedMesh.prototype, "material", {
  46357. get: function () {
  46358. return this._sourceMesh.material;
  46359. },
  46360. enumerable: true,
  46361. configurable: true
  46362. });
  46363. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46364. get: function () {
  46365. return this._sourceMesh.visibility;
  46366. },
  46367. enumerable: true,
  46368. configurable: true
  46369. });
  46370. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46371. get: function () {
  46372. return this._sourceMesh.skeleton;
  46373. },
  46374. enumerable: true,
  46375. configurable: true
  46376. });
  46377. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46378. get: function () {
  46379. return this._sourceMesh.renderingGroupId;
  46380. },
  46381. enumerable: true,
  46382. configurable: true
  46383. });
  46384. /**
  46385. * Returns the total number of vertices (integer).
  46386. */
  46387. InstancedMesh.prototype.getTotalVertices = function () {
  46388. return this._sourceMesh.getTotalVertices();
  46389. };
  46390. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46391. get: function () {
  46392. return this._sourceMesh;
  46393. },
  46394. enumerable: true,
  46395. configurable: true
  46396. });
  46397. /**
  46398. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46399. */
  46400. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46401. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46402. };
  46403. /**
  46404. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46405. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46406. * The `data` are either a numeric array either a Float32Array.
  46407. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46408. * 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).
  46409. * Note that a new underlying VertexBuffer object is created each call.
  46410. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46411. *
  46412. * Possible `kind` values :
  46413. * - BABYLON.VertexBuffer.PositionKind
  46414. * - BABYLON.VertexBuffer.UVKind
  46415. * - BABYLON.VertexBuffer.UV2Kind
  46416. * - BABYLON.VertexBuffer.UV3Kind
  46417. * - BABYLON.VertexBuffer.UV4Kind
  46418. * - BABYLON.VertexBuffer.UV5Kind
  46419. * - BABYLON.VertexBuffer.UV6Kind
  46420. * - BABYLON.VertexBuffer.ColorKind
  46421. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46422. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46423. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46424. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46425. *
  46426. * Returns the Mesh.
  46427. */
  46428. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46429. if (this.sourceMesh) {
  46430. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46431. }
  46432. return this.sourceMesh;
  46433. };
  46434. /**
  46435. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46436. * If the mesh has no geometry, it is simply returned as it is.
  46437. * The `data` are either a numeric array either a Float32Array.
  46438. * No new underlying VertexBuffer object is created.
  46439. * 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.
  46440. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46441. *
  46442. * Possible `kind` values :
  46443. * - BABYLON.VertexBuffer.PositionKind
  46444. * - BABYLON.VertexBuffer.UVKind
  46445. * - BABYLON.VertexBuffer.UV2Kind
  46446. * - BABYLON.VertexBuffer.UV3Kind
  46447. * - BABYLON.VertexBuffer.UV4Kind
  46448. * - BABYLON.VertexBuffer.UV5Kind
  46449. * - BABYLON.VertexBuffer.UV6Kind
  46450. * - BABYLON.VertexBuffer.ColorKind
  46451. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46452. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46453. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46454. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46455. *
  46456. * Returns the Mesh.
  46457. */
  46458. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46459. if (this.sourceMesh) {
  46460. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46461. }
  46462. return this.sourceMesh;
  46463. };
  46464. /**
  46465. * Sets the mesh indices.
  46466. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46467. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46468. * This method creates a new index buffer each call.
  46469. * Returns the Mesh.
  46470. */
  46471. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46472. if (totalVertices === void 0) { totalVertices = null; }
  46473. if (this.sourceMesh) {
  46474. this.sourceMesh.setIndices(indices, totalVertices);
  46475. }
  46476. return this.sourceMesh;
  46477. };
  46478. /**
  46479. * Boolean : True if the mesh owns the requested kind of data.
  46480. */
  46481. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46482. return this._sourceMesh.isVerticesDataPresent(kind);
  46483. };
  46484. /**
  46485. * Returns an array of indices (IndicesArray).
  46486. */
  46487. InstancedMesh.prototype.getIndices = function () {
  46488. return this._sourceMesh.getIndices();
  46489. };
  46490. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46491. get: function () {
  46492. return this._sourceMesh._positions;
  46493. },
  46494. enumerable: true,
  46495. configurable: true
  46496. });
  46497. /**
  46498. * Sets a new updated BoundingInfo to the mesh.
  46499. * Returns the mesh.
  46500. */
  46501. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46502. var meshBB = this._sourceMesh.getBoundingInfo();
  46503. if (meshBB) {
  46504. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46505. }
  46506. this._updateBoundingInfo();
  46507. return this;
  46508. };
  46509. InstancedMesh.prototype._preActivate = function () {
  46510. if (this._currentLOD) {
  46511. this._currentLOD._preActivate();
  46512. }
  46513. return this;
  46514. };
  46515. InstancedMesh.prototype._activate = function (renderId) {
  46516. if (this._currentLOD) {
  46517. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46518. }
  46519. return this;
  46520. };
  46521. /**
  46522. * Returns the current associated LOD AbstractMesh.
  46523. */
  46524. InstancedMesh.prototype.getLOD = function (camera) {
  46525. if (!camera) {
  46526. return this;
  46527. }
  46528. var boundingInfo = this.getBoundingInfo();
  46529. if (!boundingInfo) {
  46530. return this;
  46531. }
  46532. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46533. if (this._currentLOD === this.sourceMesh) {
  46534. return this;
  46535. }
  46536. return this._currentLOD;
  46537. };
  46538. InstancedMesh.prototype._syncSubMeshes = function () {
  46539. this.releaseSubMeshes();
  46540. if (this._sourceMesh.subMeshes) {
  46541. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46542. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46543. }
  46544. }
  46545. return this;
  46546. };
  46547. InstancedMesh.prototype._generatePointsArray = function () {
  46548. return this._sourceMesh._generatePointsArray();
  46549. };
  46550. /**
  46551. * Creates a new InstancedMesh from the current mesh.
  46552. * - name (string) : the cloned mesh name
  46553. * - newParent (optional Node) : the optional Node to parent the clone to.
  46554. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46555. *
  46556. * Returns the clone.
  46557. */
  46558. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46559. var result = this._sourceMesh.createInstance(name);
  46560. // Deep copy
  46561. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46562. // Bounding info
  46563. this.refreshBoundingInfo();
  46564. // Parent
  46565. if (newParent) {
  46566. result.parent = newParent;
  46567. }
  46568. if (!doNotCloneChildren) {
  46569. // Children
  46570. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46571. var mesh = this.getScene().meshes[index];
  46572. if (mesh.parent === this) {
  46573. mesh.clone(mesh.name, result);
  46574. }
  46575. }
  46576. }
  46577. result.computeWorldMatrix(true);
  46578. return result;
  46579. };
  46580. /**
  46581. * Disposes the InstancedMesh.
  46582. * Returns nothing.
  46583. */
  46584. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46585. // Remove from mesh
  46586. var index = this._sourceMesh.instances.indexOf(this);
  46587. this._sourceMesh.instances.splice(index, 1);
  46588. _super.prototype.dispose.call(this, doNotRecurse);
  46589. };
  46590. return InstancedMesh;
  46591. }(BABYLON.AbstractMesh));
  46592. BABYLON.InstancedMesh = InstancedMesh;
  46593. })(BABYLON || (BABYLON = {}));
  46594. //# sourceMappingURL=babylon.instancedMesh.js.map
  46595. var BABYLON;
  46596. (function (BABYLON) {
  46597. var LinesMesh = /** @class */ (function (_super) {
  46598. __extends(LinesMesh, _super);
  46599. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46600. if (scene === void 0) { scene = null; }
  46601. if (parent === void 0) { parent = null; }
  46602. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46603. _this.useVertexColor = useVertexColor;
  46604. _this.color = new BABYLON.Color3(1, 1, 1);
  46605. _this.alpha = 1;
  46606. if (source) {
  46607. _this.color = source.color.clone();
  46608. _this.alpha = source.alpha;
  46609. _this.useVertexColor = source.useVertexColor;
  46610. }
  46611. _this._intersectionThreshold = 0.1;
  46612. var options = {
  46613. attributes: [BABYLON.VertexBuffer.PositionKind],
  46614. uniforms: ["world", "viewProjection"],
  46615. needAlphaBlending: false,
  46616. };
  46617. if (!useVertexColor) {
  46618. options.uniforms.push("color");
  46619. options.needAlphaBlending = true;
  46620. }
  46621. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46622. return _this;
  46623. }
  46624. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46625. /**
  46626. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46627. * This margin is expressed in world space coordinates, so its value may vary.
  46628. * Default value is 0.1
  46629. * @returns the intersection Threshold value.
  46630. */
  46631. get: function () {
  46632. return this._intersectionThreshold;
  46633. },
  46634. /**
  46635. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46636. * This margin is expressed in world space coordinates, so its value may vary.
  46637. * @param value the new threshold to apply
  46638. */
  46639. set: function (value) {
  46640. if (this._intersectionThreshold === value) {
  46641. return;
  46642. }
  46643. this._intersectionThreshold = value;
  46644. if (this.geometry) {
  46645. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46646. }
  46647. },
  46648. enumerable: true,
  46649. configurable: true
  46650. });
  46651. /**
  46652. * Returns the string "LineMesh"
  46653. */
  46654. LinesMesh.prototype.getClassName = function () {
  46655. return "LinesMesh";
  46656. };
  46657. Object.defineProperty(LinesMesh.prototype, "material", {
  46658. get: function () {
  46659. return this._colorShader;
  46660. },
  46661. set: function (value) {
  46662. // Do nothing
  46663. },
  46664. enumerable: true,
  46665. configurable: true
  46666. });
  46667. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46668. get: function () {
  46669. return false;
  46670. },
  46671. enumerable: true,
  46672. configurable: true
  46673. });
  46674. LinesMesh.prototype.createInstance = function (name) {
  46675. throw new Error("LinesMeshes do not support createInstance.");
  46676. };
  46677. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46678. if (!this._geometry) {
  46679. return this;
  46680. }
  46681. // VBOs
  46682. this._geometry._bind(this._colorShader.getEffect());
  46683. // Color
  46684. if (!this.useVertexColor) {
  46685. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46686. }
  46687. return this;
  46688. };
  46689. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46690. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46691. return this;
  46692. }
  46693. var engine = this.getScene().getEngine();
  46694. // Draw order
  46695. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46696. return this;
  46697. };
  46698. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46699. this._colorShader.dispose();
  46700. _super.prototype.dispose.call(this, doNotRecurse);
  46701. };
  46702. /**
  46703. * Returns a new LineMesh object cloned from the current one.
  46704. */
  46705. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46706. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46707. };
  46708. return LinesMesh;
  46709. }(BABYLON.Mesh));
  46710. BABYLON.LinesMesh = LinesMesh;
  46711. })(BABYLON || (BABYLON = {}));
  46712. //# sourceMappingURL=babylon.linesMesh.js.map
  46713. var BABYLON;
  46714. (function (BABYLON) {
  46715. var ShaderMaterial = /** @class */ (function (_super) {
  46716. __extends(ShaderMaterial, _super);
  46717. function ShaderMaterial(name, scene, shaderPath, options) {
  46718. var _this = _super.call(this, name, scene) || this;
  46719. _this._textures = {};
  46720. _this._textureArrays = {};
  46721. _this._floats = {};
  46722. _this._floatsArrays = {};
  46723. _this._colors3 = {};
  46724. _this._colors3Arrays = {};
  46725. _this._colors4 = {};
  46726. _this._vectors2 = {};
  46727. _this._vectors3 = {};
  46728. _this._vectors4 = {};
  46729. _this._matrices = {};
  46730. _this._matrices3x3 = {};
  46731. _this._matrices2x2 = {};
  46732. _this._vectors3Arrays = {};
  46733. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46734. _this._shaderPath = shaderPath;
  46735. options.needAlphaBlending = options.needAlphaBlending || false;
  46736. options.needAlphaTesting = options.needAlphaTesting || false;
  46737. options.attributes = options.attributes || ["position", "normal", "uv"];
  46738. options.uniforms = options.uniforms || ["worldViewProjection"];
  46739. options.uniformBuffers = options.uniformBuffers || [];
  46740. options.samplers = options.samplers || [];
  46741. options.defines = options.defines || [];
  46742. _this._options = options;
  46743. return _this;
  46744. }
  46745. ShaderMaterial.prototype.getClassName = function () {
  46746. return "ShaderMaterial";
  46747. };
  46748. ShaderMaterial.prototype.needAlphaBlending = function () {
  46749. return this._options.needAlphaBlending;
  46750. };
  46751. ShaderMaterial.prototype.needAlphaTesting = function () {
  46752. return this._options.needAlphaTesting;
  46753. };
  46754. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46755. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46756. this._options.uniforms.push(uniformName);
  46757. }
  46758. };
  46759. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46760. if (this._options.samplers.indexOf(name) === -1) {
  46761. this._options.samplers.push(name);
  46762. }
  46763. this._textures[name] = texture;
  46764. return this;
  46765. };
  46766. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46767. if (this._options.samplers.indexOf(name) === -1) {
  46768. this._options.samplers.push(name);
  46769. }
  46770. this._checkUniform(name);
  46771. this._textureArrays[name] = textures;
  46772. return this;
  46773. };
  46774. ShaderMaterial.prototype.setFloat = function (name, value) {
  46775. this._checkUniform(name);
  46776. this._floats[name] = value;
  46777. return this;
  46778. };
  46779. ShaderMaterial.prototype.setFloats = function (name, value) {
  46780. this._checkUniform(name);
  46781. this._floatsArrays[name] = value;
  46782. return this;
  46783. };
  46784. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46785. this._checkUniform(name);
  46786. this._colors3[name] = value;
  46787. return this;
  46788. };
  46789. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46790. this._checkUniform(name);
  46791. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46792. color.toArray(arr, arr.length);
  46793. return arr;
  46794. }, []);
  46795. return this;
  46796. };
  46797. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46798. this._checkUniform(name);
  46799. this._colors4[name] = value;
  46800. return this;
  46801. };
  46802. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46803. this._checkUniform(name);
  46804. this._vectors2[name] = value;
  46805. return this;
  46806. };
  46807. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46808. this._checkUniform(name);
  46809. this._vectors3[name] = value;
  46810. return this;
  46811. };
  46812. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46813. this._checkUniform(name);
  46814. this._vectors4[name] = value;
  46815. return this;
  46816. };
  46817. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46818. this._checkUniform(name);
  46819. this._matrices[name] = value;
  46820. return this;
  46821. };
  46822. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46823. this._checkUniform(name);
  46824. this._matrices3x3[name] = value;
  46825. return this;
  46826. };
  46827. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46828. this._checkUniform(name);
  46829. this._matrices2x2[name] = value;
  46830. return this;
  46831. };
  46832. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46833. this._checkUniform(name);
  46834. this._vectors3Arrays[name] = value;
  46835. return this;
  46836. };
  46837. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46838. if (!mesh) {
  46839. return true;
  46840. }
  46841. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46842. return false;
  46843. }
  46844. return false;
  46845. };
  46846. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46847. var scene = this.getScene();
  46848. var engine = scene.getEngine();
  46849. if (!this.checkReadyOnEveryCall) {
  46850. if (this._renderId === scene.getRenderId()) {
  46851. if (this._checkCache(scene, mesh, useInstances)) {
  46852. return true;
  46853. }
  46854. }
  46855. }
  46856. // Instances
  46857. var defines = [];
  46858. var attribs = [];
  46859. var fallbacks = new BABYLON.EffectFallbacks();
  46860. if (useInstances) {
  46861. defines.push("#define INSTANCES");
  46862. }
  46863. for (var index = 0; index < this._options.defines.length; index++) {
  46864. defines.push(this._options.defines[index]);
  46865. }
  46866. for (var index = 0; index < this._options.attributes.length; index++) {
  46867. attribs.push(this._options.attributes[index]);
  46868. }
  46869. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46870. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46871. defines.push("#define VERTEXCOLOR");
  46872. }
  46873. // Bones
  46874. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46875. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46876. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46877. if (mesh.numBoneInfluencers > 4) {
  46878. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46879. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46880. }
  46881. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46882. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46883. fallbacks.addCPUSkinningFallback(0, mesh);
  46884. if (this._options.uniforms.indexOf("mBones") === -1) {
  46885. this._options.uniforms.push("mBones");
  46886. }
  46887. }
  46888. else {
  46889. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46890. }
  46891. // Textures
  46892. for (var name in this._textures) {
  46893. if (!this._textures[name].isReady()) {
  46894. return false;
  46895. }
  46896. }
  46897. // Alpha test
  46898. if (engine.getAlphaTesting()) {
  46899. defines.push("#define ALPHATEST");
  46900. }
  46901. var previousEffect = this._effect;
  46902. var join = defines.join("\n");
  46903. this._effect = engine.createEffect(this._shaderPath, {
  46904. attributes: attribs,
  46905. uniformsNames: this._options.uniforms,
  46906. uniformBuffersNames: this._options.uniformBuffers,
  46907. samplers: this._options.samplers,
  46908. defines: join,
  46909. fallbacks: fallbacks,
  46910. onCompiled: this.onCompiled,
  46911. onError: this.onError
  46912. }, engine);
  46913. if (!this._effect.isReady()) {
  46914. return false;
  46915. }
  46916. if (previousEffect !== this._effect) {
  46917. scene.resetCachedMaterial();
  46918. }
  46919. this._renderId = scene.getRenderId();
  46920. return true;
  46921. };
  46922. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46923. var scene = this.getScene();
  46924. if (!this._effect) {
  46925. return;
  46926. }
  46927. if (this._options.uniforms.indexOf("world") !== -1) {
  46928. this._effect.setMatrix("world", world);
  46929. }
  46930. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46931. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46932. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46933. }
  46934. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46935. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46936. }
  46937. };
  46938. ShaderMaterial.prototype.bind = function (world, mesh) {
  46939. // Std values
  46940. this.bindOnlyWorldMatrix(world);
  46941. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46942. if (this._options.uniforms.indexOf("view") !== -1) {
  46943. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46944. }
  46945. if (this._options.uniforms.indexOf("projection") !== -1) {
  46946. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46947. }
  46948. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46949. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46950. }
  46951. // Bones
  46952. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46953. var name;
  46954. // Texture
  46955. for (name in this._textures) {
  46956. this._effect.setTexture(name, this._textures[name]);
  46957. }
  46958. // Texture arrays
  46959. for (name in this._textureArrays) {
  46960. this._effect.setTextureArray(name, this._textureArrays[name]);
  46961. }
  46962. // Float
  46963. for (name in this._floats) {
  46964. this._effect.setFloat(name, this._floats[name]);
  46965. }
  46966. // Float s
  46967. for (name in this._floatsArrays) {
  46968. this._effect.setArray(name, this._floatsArrays[name]);
  46969. }
  46970. // Color3
  46971. for (name in this._colors3) {
  46972. this._effect.setColor3(name, this._colors3[name]);
  46973. }
  46974. for (name in this._colors3Arrays) {
  46975. this._effect.setArray3(name, this._colors3Arrays[name]);
  46976. }
  46977. // Color4
  46978. for (name in this._colors4) {
  46979. var color = this._colors4[name];
  46980. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46981. }
  46982. // Vector2
  46983. for (name in this._vectors2) {
  46984. this._effect.setVector2(name, this._vectors2[name]);
  46985. }
  46986. // Vector3
  46987. for (name in this._vectors3) {
  46988. this._effect.setVector3(name, this._vectors3[name]);
  46989. }
  46990. // Vector4
  46991. for (name in this._vectors4) {
  46992. this._effect.setVector4(name, this._vectors4[name]);
  46993. }
  46994. // Matrix
  46995. for (name in this._matrices) {
  46996. this._effect.setMatrix(name, this._matrices[name]);
  46997. }
  46998. // Matrix 3x3
  46999. for (name in this._matrices3x3) {
  47000. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47001. }
  47002. // Matrix 2x2
  47003. for (name in this._matrices2x2) {
  47004. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47005. }
  47006. // Vector3Array
  47007. for (name in this._vectors3Arrays) {
  47008. this._effect.setArray3(name, this._vectors3Arrays[name]);
  47009. }
  47010. }
  47011. this._afterBind(mesh);
  47012. };
  47013. ShaderMaterial.prototype.getActiveTextures = function () {
  47014. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47015. for (var name in this._textures) {
  47016. activeTextures.push(this._textures[name]);
  47017. }
  47018. for (var name in this._textureArrays) {
  47019. var array = this._textureArrays[name];
  47020. for (var index = 0; index < array.length; index++) {
  47021. activeTextures.push(array[index]);
  47022. }
  47023. }
  47024. return activeTextures;
  47025. };
  47026. ShaderMaterial.prototype.hasTexture = function (texture) {
  47027. if (_super.prototype.hasTexture.call(this, texture)) {
  47028. return true;
  47029. }
  47030. for (var name in this._textures) {
  47031. if (this._textures[name] === texture) {
  47032. return true;
  47033. }
  47034. }
  47035. for (var name in this._textureArrays) {
  47036. var array = this._textureArrays[name];
  47037. for (var index = 0; index < array.length; index++) {
  47038. if (array[index] === texture) {
  47039. return true;
  47040. }
  47041. }
  47042. }
  47043. return false;
  47044. };
  47045. ShaderMaterial.prototype.clone = function (name) {
  47046. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47047. return newShaderMaterial;
  47048. };
  47049. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47050. if (forceDisposeTextures) {
  47051. var name;
  47052. for (name in this._textures) {
  47053. this._textures[name].dispose();
  47054. }
  47055. for (name in this._textureArrays) {
  47056. var array = this._textureArrays[name];
  47057. for (var index = 0; index < array.length; index++) {
  47058. array[index].dispose();
  47059. }
  47060. }
  47061. }
  47062. this._textures = {};
  47063. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47064. };
  47065. ShaderMaterial.prototype.serialize = function () {
  47066. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47067. serializationObject.customType = "BABYLON.ShaderMaterial";
  47068. serializationObject.options = this._options;
  47069. serializationObject.shaderPath = this._shaderPath;
  47070. var name;
  47071. // Texture
  47072. serializationObject.textures = {};
  47073. for (name in this._textures) {
  47074. serializationObject.textures[name] = this._textures[name].serialize();
  47075. }
  47076. // Texture arrays
  47077. serializationObject.textureArrays = {};
  47078. for (name in this._textureArrays) {
  47079. serializationObject.textureArrays[name] = [];
  47080. var array = this._textureArrays[name];
  47081. for (var index = 0; index < array.length; index++) {
  47082. serializationObject.textureArrays[name].push(array[index].serialize());
  47083. }
  47084. }
  47085. // Float
  47086. serializationObject.floats = {};
  47087. for (name in this._floats) {
  47088. serializationObject.floats[name] = this._floats[name];
  47089. }
  47090. // Float s
  47091. serializationObject.FloatArrays = {};
  47092. for (name in this._floatsArrays) {
  47093. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  47094. }
  47095. // Color3
  47096. serializationObject.colors3 = {};
  47097. for (name in this._colors3) {
  47098. serializationObject.colors3[name] = this._colors3[name].asArray();
  47099. }
  47100. // Color3 array
  47101. serializationObject.colors3Arrays = {};
  47102. for (name in this._colors3Arrays) {
  47103. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  47104. }
  47105. // Color4
  47106. serializationObject.colors4 = {};
  47107. for (name in this._colors4) {
  47108. serializationObject.colors4[name] = this._colors4[name].asArray();
  47109. }
  47110. // Vector2
  47111. serializationObject.vectors2 = {};
  47112. for (name in this._vectors2) {
  47113. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47114. }
  47115. // Vector3
  47116. serializationObject.vectors3 = {};
  47117. for (name in this._vectors3) {
  47118. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47119. }
  47120. // Vector4
  47121. serializationObject.vectors4 = {};
  47122. for (name in this._vectors4) {
  47123. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47124. }
  47125. // Matrix
  47126. serializationObject.matrices = {};
  47127. for (name in this._matrices) {
  47128. serializationObject.matrices[name] = this._matrices[name].asArray();
  47129. }
  47130. // Matrix 3x3
  47131. serializationObject.matrices3x3 = {};
  47132. for (name in this._matrices3x3) {
  47133. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47134. }
  47135. // Matrix 2x2
  47136. serializationObject.matrices2x2 = {};
  47137. for (name in this._matrices2x2) {
  47138. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47139. }
  47140. // Vector3Array
  47141. serializationObject.vectors3Arrays = {};
  47142. for (name in this._vectors3Arrays) {
  47143. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  47144. }
  47145. return serializationObject;
  47146. };
  47147. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47148. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47149. var name;
  47150. // Texture
  47151. for (name in source.textures) {
  47152. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47153. }
  47154. // Texture arrays
  47155. for (name in source.textureArrays) {
  47156. var array = source.textureArrays[name];
  47157. var textureArray = new Array();
  47158. for (var index = 0; index < array.length; index++) {
  47159. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47160. }
  47161. material.setTextureArray(name, textureArray);
  47162. }
  47163. // Float
  47164. for (name in source.floats) {
  47165. material.setFloat(name, source.floats[name]);
  47166. }
  47167. // Float s
  47168. for (name in source.floatsArrays) {
  47169. material.setFloats(name, source.floatsArrays[name]);
  47170. }
  47171. // Color3
  47172. for (name in source.colors3) {
  47173. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47174. }
  47175. // Color3 arrays
  47176. for (name in source.colors3Arrays) {
  47177. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  47178. if (i % 3 === 0) {
  47179. arr.push([num]);
  47180. }
  47181. else {
  47182. arr[arr.length - 1].push(num);
  47183. }
  47184. return arr;
  47185. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  47186. material.setColor3Array(name, colors);
  47187. }
  47188. // Color4
  47189. for (name in source.colors4) {
  47190. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47191. }
  47192. // Vector2
  47193. for (name in source.vectors2) {
  47194. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47195. }
  47196. // Vector3
  47197. for (name in source.vectors3) {
  47198. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47199. }
  47200. // Vector4
  47201. for (name in source.vectors4) {
  47202. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47203. }
  47204. // Matrix
  47205. for (name in source.matrices) {
  47206. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47207. }
  47208. // Matrix 3x3
  47209. for (name in source.matrices3x3) {
  47210. material.setMatrix3x3(name, source.matrices3x3[name]);
  47211. }
  47212. // Matrix 2x2
  47213. for (name in source.matrices2x2) {
  47214. material.setMatrix2x2(name, source.matrices2x2[name]);
  47215. }
  47216. // Vector3Array
  47217. for (name in source.vectors3Arrays) {
  47218. material.setArray3(name, source.vectors3Arrays[name]);
  47219. }
  47220. return material;
  47221. };
  47222. return ShaderMaterial;
  47223. }(BABYLON.Material));
  47224. BABYLON.ShaderMaterial = ShaderMaterial;
  47225. })(BABYLON || (BABYLON = {}));
  47226. //# sourceMappingURL=babylon.shaderMaterial.js.map
  47227. var BABYLON;
  47228. (function (BABYLON) {
  47229. var MeshBuilder = /** @class */ (function () {
  47230. function MeshBuilder() {
  47231. }
  47232. MeshBuilder.updateSideOrientation = function (orientation) {
  47233. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  47234. return BABYLON.Mesh.DOUBLESIDE;
  47235. }
  47236. if (orientation === undefined || orientation === null) {
  47237. return BABYLON.Mesh.FRONTSIDE;
  47238. }
  47239. return orientation;
  47240. };
  47241. /**
  47242. * Creates a box mesh.
  47243. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  47244. * The parameter `size` sets the size (float) of each box side (default 1).
  47245. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  47246. * 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).
  47247. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47248. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47249. * 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).
  47250. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47251. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47252. */
  47253. MeshBuilder.CreateBox = function (name, options, scene) {
  47254. if (scene === void 0) { scene = null; }
  47255. var box = new BABYLON.Mesh(name, scene);
  47256. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47257. box._originalBuilderSideOrientation = options.sideOrientation;
  47258. var vertexData = BABYLON.VertexData.CreateBox(options);
  47259. vertexData.applyToMesh(box, options.updatable);
  47260. return box;
  47261. };
  47262. /**
  47263. * Creates a sphere mesh.
  47264. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  47265. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  47266. * 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`).
  47267. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  47268. * 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
  47269. * 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).
  47270. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47271. * 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).
  47272. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47274. */
  47275. MeshBuilder.CreateSphere = function (name, options, scene) {
  47276. var sphere = new BABYLON.Mesh(name, scene);
  47277. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47278. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47279. var vertexData = BABYLON.VertexData.CreateSphere(options);
  47280. vertexData.applyToMesh(sphere, options.updatable);
  47281. return sphere;
  47282. };
  47283. /**
  47284. * Creates a plane polygonal mesh. By default, this is a disc.
  47285. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  47286. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  47287. * 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.
  47288. * 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
  47289. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47290. * 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).
  47291. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47292. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47293. */
  47294. MeshBuilder.CreateDisc = function (name, options, scene) {
  47295. if (scene === void 0) { scene = null; }
  47296. var disc = new BABYLON.Mesh(name, scene);
  47297. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47298. disc._originalBuilderSideOrientation = options.sideOrientation;
  47299. var vertexData = BABYLON.VertexData.CreateDisc(options);
  47300. vertexData.applyToMesh(disc, options.updatable);
  47301. return disc;
  47302. };
  47303. /**
  47304. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  47305. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  47306. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  47307. * 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`).
  47308. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  47309. * 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.
  47310. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47311. * 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).
  47312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47314. */
  47315. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  47316. var sphere = new BABYLON.Mesh(name, scene);
  47317. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47318. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47319. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  47320. vertexData.applyToMesh(sphere, options.updatable);
  47321. return sphere;
  47322. };
  47323. ;
  47324. /**
  47325. * Creates a ribbon mesh.
  47326. * 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.
  47327. *
  47328. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  47329. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  47330. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  47331. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  47332. * 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.
  47333. * 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.
  47334. * 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
  47335. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47336. * 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).
  47337. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47338. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47339. * 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.
  47340. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47341. * 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
  47342. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47343. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47344. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47345. */
  47346. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47347. if (scene === void 0) { scene = null; }
  47348. var pathArray = options.pathArray;
  47349. var closeArray = options.closeArray;
  47350. var closePath = options.closePath;
  47351. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47352. var instance = options.instance;
  47353. var updatable = options.updatable;
  47354. if (instance) {
  47355. // positionFunction : ribbon case
  47356. // only pathArray and sideOrientation parameters are taken into account for positions update
  47357. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47358. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47359. var positionFunction = function (positions) {
  47360. var minlg = pathArray[0].length;
  47361. var i = 0;
  47362. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47363. for (var si = 1; si <= ns; si++) {
  47364. for (var p = 0; p < pathArray.length; p++) {
  47365. var path = pathArray[p];
  47366. var l = path.length;
  47367. minlg = (minlg < l) ? minlg : l;
  47368. var j = 0;
  47369. while (j < minlg) {
  47370. positions[i] = path[j].x;
  47371. positions[i + 1] = path[j].y;
  47372. positions[i + 2] = path[j].z;
  47373. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47374. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47375. }
  47376. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47377. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47378. }
  47379. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47380. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47381. }
  47382. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47383. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47384. }
  47385. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47386. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47387. }
  47388. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47389. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47390. }
  47391. j++;
  47392. i += 3;
  47393. }
  47394. if (instance._closePath) {
  47395. positions[i] = path[0].x;
  47396. positions[i + 1] = path[0].y;
  47397. positions[i + 2] = path[0].z;
  47398. i += 3;
  47399. }
  47400. }
  47401. }
  47402. };
  47403. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47404. positionFunction(positions);
  47405. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47406. instance._boundingInfo.update(instance._worldMatrix);
  47407. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47408. if (options.colors) {
  47409. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47410. for (var c = 0; c < options.colors.length; c++) {
  47411. colors[c * 4] = options.colors[c].r;
  47412. colors[c * 4 + 1] = options.colors[c].g;
  47413. colors[c * 4 + 2] = options.colors[c].b;
  47414. colors[c * 4 + 3] = options.colors[c].a;
  47415. }
  47416. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47417. }
  47418. if (options.uvs) {
  47419. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47420. for (var i = 0; i < options.uvs.length; i++) {
  47421. uvs[i * 2] = options.uvs[i].x;
  47422. uvs[i * 2 + 1] = options.uvs[i].y;
  47423. }
  47424. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47425. }
  47426. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47427. var indices = instance.getIndices();
  47428. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47429. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47430. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47431. if (instance._closePath) {
  47432. var indexFirst = 0;
  47433. var indexLast = 0;
  47434. for (var p = 0; p < pathArray.length; p++) {
  47435. indexFirst = instance._idx[p] * 3;
  47436. if (p + 1 < pathArray.length) {
  47437. indexLast = (instance._idx[p + 1] - 1) * 3;
  47438. }
  47439. else {
  47440. indexLast = normals.length - 3;
  47441. }
  47442. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47443. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47444. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47445. normals[indexLast] = normals[indexFirst];
  47446. normals[indexLast + 1] = normals[indexFirst + 1];
  47447. normals[indexLast + 2] = normals[indexFirst + 2];
  47448. }
  47449. }
  47450. if (!(instance.areNormalsFrozen)) {
  47451. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47452. }
  47453. }
  47454. return instance;
  47455. }
  47456. else {
  47457. var ribbon = new BABYLON.Mesh(name, scene);
  47458. ribbon._originalBuilderSideOrientation = sideOrientation;
  47459. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47460. if (closePath) {
  47461. ribbon._idx = vertexData._idx;
  47462. }
  47463. ribbon._closePath = closePath;
  47464. ribbon._closeArray = closeArray;
  47465. vertexData.applyToMesh(ribbon, updatable);
  47466. return ribbon;
  47467. }
  47468. };
  47469. /**
  47470. * Creates a cylinder or a cone mesh.
  47471. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47472. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47473. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47474. * 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.
  47475. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47476. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47477. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47478. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47479. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47480. * 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).
  47481. * 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
  47482. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47483. * 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
  47484. * 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.
  47485. * If `enclose` is false, a ring surface is one element.
  47486. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47487. * 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
  47488. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47489. * 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).
  47490. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47492. */
  47493. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47494. var cylinder = new BABYLON.Mesh(name, scene);
  47495. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47496. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47497. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47498. vertexData.applyToMesh(cylinder, options.updatable);
  47499. return cylinder;
  47500. };
  47501. /**
  47502. * Creates a torus mesh.
  47503. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47504. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47505. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47506. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47507. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47508. * 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).
  47509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47511. */
  47512. MeshBuilder.CreateTorus = function (name, options, scene) {
  47513. var torus = new BABYLON.Mesh(name, scene);
  47514. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47515. torus._originalBuilderSideOrientation = options.sideOrientation;
  47516. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47517. vertexData.applyToMesh(torus, options.updatable);
  47518. return torus;
  47519. };
  47520. /**
  47521. * Creates a torus knot mesh.
  47522. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47523. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47524. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47525. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47526. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47527. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47528. * 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).
  47529. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47530. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47531. */
  47532. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47533. var torusKnot = new BABYLON.Mesh(name, scene);
  47534. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47535. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47536. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47537. vertexData.applyToMesh(torusKnot, options.updatable);
  47538. return torusKnot;
  47539. };
  47540. /**
  47541. * Creates a line system mesh.
  47542. * A line system is a pool of many lines gathered in a single mesh.
  47543. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47544. * 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.
  47545. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47546. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47547. * 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
  47548. * 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
  47549. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47551. */
  47552. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47553. var instance = options.instance;
  47554. var lines = options.lines;
  47555. if (instance) {
  47556. var positionFunction = function (positions) {
  47557. var i = 0;
  47558. for (var l = 0; l < lines.length; l++) {
  47559. var points = lines[l];
  47560. for (var p = 0; p < points.length; p++) {
  47561. positions[i] = points[p].x;
  47562. positions[i + 1] = points[p].y;
  47563. positions[i + 2] = points[p].z;
  47564. i += 3;
  47565. }
  47566. }
  47567. };
  47568. instance.updateMeshPositions(positionFunction, false);
  47569. return instance;
  47570. }
  47571. // line system creation
  47572. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47573. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47574. vertexData.applyToMesh(lineSystem, options.updatable);
  47575. return lineSystem;
  47576. };
  47577. /**
  47578. * Creates a line mesh.
  47579. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47580. * 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.
  47581. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47582. * The parameter `points` is an array successive Vector3.
  47583. * 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
  47584. * When updating an instance, remember that only point positions can change, not the number of points.
  47585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47586. */
  47587. MeshBuilder.CreateLines = function (name, options, scene) {
  47588. if (scene === void 0) { scene = null; }
  47589. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47590. return lines;
  47591. };
  47592. /**
  47593. * Creates a dashed line mesh.
  47594. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47595. * 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.
  47596. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47597. * The parameter `points` is an array successive Vector3.
  47598. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47599. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47600. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47601. * 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
  47602. * When updating an instance, remember that only point positions can change, not the number of points.
  47603. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47604. */
  47605. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47606. if (scene === void 0) { scene = null; }
  47607. var points = options.points;
  47608. var instance = options.instance;
  47609. var gapSize = options.gapSize || 1;
  47610. var dashSize = options.dashSize || 3;
  47611. if (instance) {
  47612. var positionFunction = function (positions) {
  47613. var curvect = BABYLON.Vector3.Zero();
  47614. var nbSeg = positions.length / 6;
  47615. var lg = 0;
  47616. var nb = 0;
  47617. var shft = 0;
  47618. var dashshft = 0;
  47619. var curshft = 0;
  47620. var p = 0;
  47621. var i = 0;
  47622. var j = 0;
  47623. for (i = 0; i < points.length - 1; i++) {
  47624. points[i + 1].subtractToRef(points[i], curvect);
  47625. lg += curvect.length();
  47626. }
  47627. shft = lg / nbSeg;
  47628. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47629. for (i = 0; i < points.length - 1; i++) {
  47630. points[i + 1].subtractToRef(points[i], curvect);
  47631. nb = Math.floor(curvect.length() / shft);
  47632. curvect.normalize();
  47633. j = 0;
  47634. while (j < nb && p < positions.length) {
  47635. curshft = shft * j;
  47636. positions[p] = points[i].x + curshft * curvect.x;
  47637. positions[p + 1] = points[i].y + curshft * curvect.y;
  47638. positions[p + 2] = points[i].z + curshft * curvect.z;
  47639. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47640. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47641. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47642. p += 6;
  47643. j++;
  47644. }
  47645. }
  47646. while (p < positions.length) {
  47647. positions[p] = points[i].x;
  47648. positions[p + 1] = points[i].y;
  47649. positions[p + 2] = points[i].z;
  47650. p += 3;
  47651. }
  47652. };
  47653. instance.updateMeshPositions(positionFunction, false);
  47654. return instance;
  47655. }
  47656. // dashed lines creation
  47657. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47658. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47659. vertexData.applyToMesh(dashedLines, options.updatable);
  47660. dashedLines.dashSize = dashSize;
  47661. dashedLines.gapSize = gapSize;
  47662. return dashedLines;
  47663. };
  47664. /**
  47665. * Creates an extruded shape mesh.
  47666. * 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.
  47667. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47668. *
  47669. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47670. * 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
  47671. * extruded along the Z axis.
  47672. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47673. * 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.
  47674. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47675. * 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
  47676. * 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
  47677. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47678. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47679. * 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).
  47680. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47681. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47682. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47683. */
  47684. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47685. if (scene === void 0) { scene = null; }
  47686. var path = options.path;
  47687. var shape = options.shape;
  47688. var scale = options.scale || 1;
  47689. var rotation = options.rotation || 0;
  47690. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47691. var updatable = options.updatable;
  47692. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47693. var instance = options.instance || null;
  47694. var invertUV = options.invertUV || false;
  47695. 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);
  47696. };
  47697. /**
  47698. * Creates an custom extruded shape mesh.
  47699. * 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.
  47700. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47701. *
  47702. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47703. * 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
  47704. * extruded along the Z axis.
  47705. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47706. * 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
  47707. * and the distance of this point from the begining of the path :
  47708. * ```javascript
  47709. * var rotationFunction = function(i, distance) {
  47710. * // do things
  47711. * return rotationValue; }
  47712. * ```
  47713. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47714. * 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
  47715. * and the distance of this point from the begining of the path :
  47716. * ```javascript
  47717. * var scaleFunction = function(i, distance) {
  47718. * // do things
  47719. * return scaleValue;}
  47720. * ```
  47721. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47722. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47723. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47724. * 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
  47725. * 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
  47726. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47727. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47728. * 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).
  47729. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47730. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47732. */
  47733. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47734. var path = options.path;
  47735. var shape = options.shape;
  47736. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47737. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47738. var ribbonCloseArray = options.ribbonCloseArray || false;
  47739. var ribbonClosePath = options.ribbonClosePath || false;
  47740. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47741. var updatable = options.updatable;
  47742. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47743. var instance = options.instance;
  47744. var invertUV = options.invertUV || false;
  47745. 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);
  47746. };
  47747. /**
  47748. * Creates lathe mesh.
  47749. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47750. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47751. *
  47752. * 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
  47753. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47754. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47755. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47756. * 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.
  47757. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47758. * 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
  47759. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47760. * 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).
  47761. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47762. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47763. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47764. */
  47765. MeshBuilder.CreateLathe = function (name, options, scene) {
  47766. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47767. var closed = (options.closed === undefined) ? true : options.closed;
  47768. var shape = options.shape;
  47769. var radius = options.radius || 1;
  47770. var tessellation = options.tessellation || 64;
  47771. var updatable = options.updatable;
  47772. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47773. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47774. var pi2 = Math.PI * 2;
  47775. var paths = new Array();
  47776. var invertUV = options.invertUV || false;
  47777. var i = 0;
  47778. var p = 0;
  47779. var step = pi2 / tessellation * arc;
  47780. var rotated;
  47781. var path = new Array();
  47782. ;
  47783. for (i = 0; i <= tessellation; i++) {
  47784. var path = [];
  47785. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47786. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47787. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47788. }
  47789. for (p = 0; p < shape.length; p++) {
  47790. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47791. path.push(rotated);
  47792. }
  47793. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47794. 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));
  47795. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47796. }
  47797. paths.push(path);
  47798. }
  47799. // lathe ribbon
  47800. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47801. return lathe;
  47802. };
  47803. /**
  47804. * Creates a plane mesh.
  47805. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47806. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47807. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47808. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  47809. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47810. * 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).
  47811. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47813. */
  47814. MeshBuilder.CreatePlane = function (name, options, scene) {
  47815. var plane = new BABYLON.Mesh(name, scene);
  47816. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47817. plane._originalBuilderSideOrientation = options.sideOrientation;
  47818. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47819. vertexData.applyToMesh(plane, options.updatable);
  47820. if (options.sourcePlane) {
  47821. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47822. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47823. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47824. plane.rotate(vectorProduct, product);
  47825. }
  47826. return plane;
  47827. };
  47828. /**
  47829. * Creates a ground mesh.
  47830. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47831. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47832. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47833. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47834. */
  47835. MeshBuilder.CreateGround = function (name, options, scene) {
  47836. var ground = new BABYLON.GroundMesh(name, scene);
  47837. ground._setReady(false);
  47838. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47839. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47840. ground._width = options.width || 1;
  47841. ground._height = options.height || 1;
  47842. ground._maxX = ground._width / 2;
  47843. ground._maxZ = ground._height / 2;
  47844. ground._minX = -ground._maxX;
  47845. ground._minZ = -ground._maxZ;
  47846. var vertexData = BABYLON.VertexData.CreateGround(options);
  47847. vertexData.applyToMesh(ground, options.updatable);
  47848. ground._setReady(true);
  47849. return ground;
  47850. };
  47851. /**
  47852. * Creates a tiled ground mesh.
  47853. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47854. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47855. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47856. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47857. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47858. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47859. * numbers of subdivisions on the ground width and height of each tile.
  47860. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47861. */
  47862. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47863. var tiledGround = new BABYLON.Mesh(name, scene);
  47864. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47865. vertexData.applyToMesh(tiledGround, options.updatable);
  47866. return tiledGround;
  47867. };
  47868. /**
  47869. * Creates a ground mesh from a height map.
  47870. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47871. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47872. * The parameter `url` sets the URL of the height map image resource.
  47873. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47874. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47875. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47876. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47877. * 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.
  47878. * 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).
  47879. * This function is passed the newly built mesh :
  47880. * ```javascript
  47881. * function(mesh) { // do things
  47882. * return; }
  47883. * ```
  47884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47885. */
  47886. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47887. var width = options.width || 10.0;
  47888. var height = options.height || 10.0;
  47889. var subdivisions = options.subdivisions || 1 | 0;
  47890. var minHeight = options.minHeight || 0.0;
  47891. var maxHeight = options.maxHeight || 1.0;
  47892. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47893. var updatable = options.updatable;
  47894. var onReady = options.onReady;
  47895. var ground = new BABYLON.GroundMesh(name, scene);
  47896. ground._subdivisionsX = subdivisions;
  47897. ground._subdivisionsY = subdivisions;
  47898. ground._width = width;
  47899. ground._height = height;
  47900. ground._maxX = ground._width / 2.0;
  47901. ground._maxZ = ground._height / 2.0;
  47902. ground._minX = -ground._maxX;
  47903. ground._minZ = -ground._maxZ;
  47904. ground._setReady(false);
  47905. var onload = function (img) {
  47906. // Getting height map data
  47907. var canvas = document.createElement("canvas");
  47908. var context = canvas.getContext("2d");
  47909. if (!context) {
  47910. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47911. }
  47912. var bufferWidth = img.width;
  47913. var bufferHeight = img.height;
  47914. canvas.width = bufferWidth;
  47915. canvas.height = bufferHeight;
  47916. context.drawImage(img, 0, 0);
  47917. // Create VertexData from map data
  47918. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47919. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47920. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47921. width: width, height: height,
  47922. subdivisions: subdivisions,
  47923. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47924. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47925. });
  47926. vertexData.applyToMesh(ground, updatable);
  47927. ground._setReady(true);
  47928. //execute ready callback, if set
  47929. if (onReady) {
  47930. onReady(ground);
  47931. }
  47932. };
  47933. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47934. return ground;
  47935. };
  47936. /**
  47937. * Creates a polygon mesh.
  47938. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47939. * 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.
  47940. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47941. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47942. * 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).
  47943. * Remember you can only change the shape positions, not their number when updating a polygon.
  47944. */
  47945. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47946. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47947. var shape = options.shape;
  47948. var holes = options.holes || [];
  47949. var depth = options.depth || 0;
  47950. var contours = [];
  47951. var hole = [];
  47952. for (var i = 0; i < shape.length; i++) {
  47953. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47954. }
  47955. var epsilon = 0.00000001;
  47956. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47957. contours.pop();
  47958. }
  47959. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47960. for (var hNb = 0; hNb < holes.length; hNb++) {
  47961. hole = [];
  47962. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47963. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47964. }
  47965. polygonTriangulation.addHole(hole);
  47966. }
  47967. var polygon = polygonTriangulation.build(options.updatable, depth);
  47968. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47969. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47970. vertexData.applyToMesh(polygon, options.updatable);
  47971. return polygon;
  47972. };
  47973. ;
  47974. /**
  47975. * Creates an extruded polygon mesh, with depth in the Y direction.
  47976. * 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).
  47977. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47978. */
  47979. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47980. return MeshBuilder.CreatePolygon(name, options, scene);
  47981. };
  47982. ;
  47983. /**
  47984. * Creates a tube mesh.
  47985. * 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.
  47986. *
  47987. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47988. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47989. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47990. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47991. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47992. * 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.
  47993. * It must return a radius value (positive float) :
  47994. * ```javascript
  47995. * var radiusFunction = function(i, distance) {
  47996. * // do things
  47997. * return radius; }
  47998. * ```
  47999. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  48000. * 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
  48001. * 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
  48002. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48003. * 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).
  48004. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48005. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48007. */
  48008. MeshBuilder.CreateTube = function (name, options, scene) {
  48009. var path = options.path;
  48010. var instance = options.instance;
  48011. var radius = 1.0;
  48012. if (instance) {
  48013. radius = instance.radius;
  48014. }
  48015. if (options.radius !== undefined) {
  48016. radius = options.radius;
  48017. }
  48018. ;
  48019. var tessellation = options.tessellation || 64 | 0;
  48020. var radiusFunction = options.radiusFunction || null;
  48021. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48022. var invertUV = options.invertUV || false;
  48023. var updatable = options.updatable;
  48024. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48025. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  48026. // tube geometry
  48027. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  48028. var tangents = path3D.getTangents();
  48029. var normals = path3D.getNormals();
  48030. var distances = path3D.getDistances();
  48031. var pi2 = Math.PI * 2;
  48032. var step = pi2 / tessellation * arc;
  48033. var returnRadius = function () { return radius; };
  48034. var radiusFunctionFinal = radiusFunction || returnRadius;
  48035. var circlePath;
  48036. var rad;
  48037. var normal;
  48038. var rotated;
  48039. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48040. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48041. for (var i = 0; i < path.length; i++) {
  48042. rad = radiusFunctionFinal(i, distances[i]); // current radius
  48043. circlePath = Array(); // current circle array
  48044. normal = normals[i]; // current normal
  48045. for (var t = 0; t < tessellation; t++) {
  48046. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  48047. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  48048. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  48049. rotated.scaleInPlace(rad).addInPlace(path[i]);
  48050. circlePath[t] = rotated;
  48051. }
  48052. circlePaths[index] = circlePath;
  48053. index++;
  48054. }
  48055. // cap
  48056. var capPath = function (nbPoints, pathIndex) {
  48057. var pointCap = Array();
  48058. for (var i = 0; i < nbPoints; i++) {
  48059. pointCap.push(path[pathIndex]);
  48060. }
  48061. return pointCap;
  48062. };
  48063. switch (cap) {
  48064. case BABYLON.Mesh.NO_CAP:
  48065. break;
  48066. case BABYLON.Mesh.CAP_START:
  48067. circlePaths[0] = capPath(tessellation, 0);
  48068. circlePaths[1] = circlePaths[2].slice(0);
  48069. break;
  48070. case BABYLON.Mesh.CAP_END:
  48071. circlePaths[index] = circlePaths[index - 1].slice(0);
  48072. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48073. break;
  48074. case BABYLON.Mesh.CAP_ALL:
  48075. circlePaths[0] = capPath(tessellation, 0);
  48076. circlePaths[1] = circlePaths[2].slice(0);
  48077. circlePaths[index] = circlePaths[index - 1].slice(0);
  48078. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48079. break;
  48080. default:
  48081. break;
  48082. }
  48083. return circlePaths;
  48084. };
  48085. var path3D;
  48086. var pathArray;
  48087. if (instance) {
  48088. var arc = options.arc || instance.arc;
  48089. path3D = (instance.path3D).update(path);
  48090. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  48091. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  48092. instance.path3D = path3D;
  48093. instance.pathArray = pathArray;
  48094. instance.arc = arc;
  48095. instance.radius = radius;
  48096. return instance;
  48097. }
  48098. // tube creation
  48099. path3D = new BABYLON.Path3D(path);
  48100. var newPathArray = new Array();
  48101. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48102. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  48103. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48104. tube.pathArray = pathArray;
  48105. tube.path3D = path3D;
  48106. tube.tessellation = tessellation;
  48107. tube.cap = cap;
  48108. tube.arc = options.arc;
  48109. tube.radius = radius;
  48110. return tube;
  48111. };
  48112. /**
  48113. * Creates a polyhedron mesh.
  48114. *
  48115. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  48116. * 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
  48117. * to choose the wanted type.
  48118. * The parameter `size` (positive float, default 1) sets the polygon size.
  48119. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  48120. * 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`.
  48121. * 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
  48122. * 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)`).
  48123. * 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
  48124. * 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.
  48125. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48126. * 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).
  48127. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48129. */
  48130. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  48131. var polyhedron = new BABYLON.Mesh(name, scene);
  48132. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48133. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  48134. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  48135. vertexData.applyToMesh(polyhedron, options.updatable);
  48136. return polyhedron;
  48137. };
  48138. /**
  48139. * Creates a decal mesh.
  48140. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  48141. * 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.
  48142. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  48143. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  48144. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  48145. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  48146. */
  48147. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  48148. var indices = sourceMesh.getIndices();
  48149. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48150. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48151. var position = options.position || BABYLON.Vector3.Zero();
  48152. var normal = options.normal || BABYLON.Vector3.Up();
  48153. var size = options.size || BABYLON.Vector3.One();
  48154. var angle = options.angle || 0;
  48155. // Getting correct rotation
  48156. if (!normal) {
  48157. var target = new BABYLON.Vector3(0, 0, 1);
  48158. var camera = sourceMesh.getScene().activeCamera;
  48159. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  48160. normal = camera.globalPosition.subtract(cameraWorldTarget);
  48161. }
  48162. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  48163. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  48164. var pitch = Math.atan2(normal.y, len);
  48165. // Matrix
  48166. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  48167. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  48168. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  48169. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  48170. var vertexData = new BABYLON.VertexData();
  48171. vertexData.indices = [];
  48172. vertexData.positions = [];
  48173. vertexData.normals = [];
  48174. vertexData.uvs = [];
  48175. var currentVertexDataIndex = 0;
  48176. var extractDecalVector3 = function (indexId) {
  48177. var result = new BABYLON.PositionNormalVertex();
  48178. if (!indices || !positions || !normals) {
  48179. return result;
  48180. }
  48181. var vertexId = indices[indexId];
  48182. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  48183. // Send vector to decal local world
  48184. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  48185. // Get normal
  48186. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  48187. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  48188. return result;
  48189. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  48190. var clip = function (vertices, axis) {
  48191. if (vertices.length === 0) {
  48192. return vertices;
  48193. }
  48194. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  48195. var clipVertices = function (v0, v1) {
  48196. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  48197. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  48198. };
  48199. var result = new Array();
  48200. for (var index = 0; index < vertices.length; index += 3) {
  48201. var v1Out;
  48202. var v2Out;
  48203. var v3Out;
  48204. var total = 0;
  48205. var nV1 = null;
  48206. var nV2 = null;
  48207. var nV3 = null;
  48208. var nV4 = null;
  48209. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  48210. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  48211. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  48212. v1Out = d1 > 0;
  48213. v2Out = d2 > 0;
  48214. v3Out = d3 > 0;
  48215. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  48216. switch (total) {
  48217. case 0:
  48218. result.push(vertices[index]);
  48219. result.push(vertices[index + 1]);
  48220. result.push(vertices[index + 2]);
  48221. break;
  48222. case 1:
  48223. if (v1Out) {
  48224. nV1 = vertices[index + 1];
  48225. nV2 = vertices[index + 2];
  48226. nV3 = clipVertices(vertices[index], nV1);
  48227. nV4 = clipVertices(vertices[index], nV2);
  48228. }
  48229. if (v2Out) {
  48230. nV1 = vertices[index];
  48231. nV2 = vertices[index + 2];
  48232. nV3 = clipVertices(vertices[index + 1], nV1);
  48233. nV4 = clipVertices(vertices[index + 1], nV2);
  48234. result.push(nV3);
  48235. result.push(nV2.clone());
  48236. result.push(nV1.clone());
  48237. result.push(nV2.clone());
  48238. result.push(nV3.clone());
  48239. result.push(nV4);
  48240. break;
  48241. }
  48242. if (v3Out) {
  48243. nV1 = vertices[index];
  48244. nV2 = vertices[index + 1];
  48245. nV3 = clipVertices(vertices[index + 2], nV1);
  48246. nV4 = clipVertices(vertices[index + 2], nV2);
  48247. }
  48248. if (nV1 && nV2 && nV3 && nV4) {
  48249. result.push(nV1.clone());
  48250. result.push(nV2.clone());
  48251. result.push(nV3);
  48252. result.push(nV4);
  48253. result.push(nV3.clone());
  48254. result.push(nV2.clone());
  48255. }
  48256. break;
  48257. case 2:
  48258. if (!v1Out) {
  48259. nV1 = vertices[index].clone();
  48260. nV2 = clipVertices(nV1, vertices[index + 1]);
  48261. nV3 = clipVertices(nV1, vertices[index + 2]);
  48262. result.push(nV1);
  48263. result.push(nV2);
  48264. result.push(nV3);
  48265. }
  48266. if (!v2Out) {
  48267. nV1 = vertices[index + 1].clone();
  48268. nV2 = clipVertices(nV1, vertices[index + 2]);
  48269. nV3 = clipVertices(nV1, vertices[index]);
  48270. result.push(nV1);
  48271. result.push(nV2);
  48272. result.push(nV3);
  48273. }
  48274. if (!v3Out) {
  48275. nV1 = vertices[index + 2].clone();
  48276. nV2 = clipVertices(nV1, vertices[index]);
  48277. nV3 = clipVertices(nV1, vertices[index + 1]);
  48278. result.push(nV1);
  48279. result.push(nV2);
  48280. result.push(nV3);
  48281. }
  48282. break;
  48283. case 3:
  48284. break;
  48285. }
  48286. }
  48287. return result;
  48288. };
  48289. for (var index = 0; index < indices.length; index += 3) {
  48290. var faceVertices = new Array();
  48291. faceVertices.push(extractDecalVector3(index));
  48292. faceVertices.push(extractDecalVector3(index + 1));
  48293. faceVertices.push(extractDecalVector3(index + 2));
  48294. // Clip
  48295. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  48296. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  48297. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  48298. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  48299. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  48300. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  48301. if (faceVertices.length === 0) {
  48302. continue;
  48303. }
  48304. // Add UVs and get back to world
  48305. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  48306. var vertex = faceVertices[vIndex];
  48307. //TODO check for Int32Array | Uint32Array | Uint16Array
  48308. vertexData.indices.push(currentVertexDataIndex);
  48309. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  48310. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  48311. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  48312. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  48313. currentVertexDataIndex++;
  48314. }
  48315. }
  48316. // Return mesh
  48317. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  48318. vertexData.applyToMesh(decal);
  48319. decal.position = position.clone();
  48320. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  48321. return decal;
  48322. };
  48323. // Privates
  48324. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  48325. // extrusion geometry
  48326. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  48327. var tangents = path3D.getTangents();
  48328. var normals = path3D.getNormals();
  48329. var binormals = path3D.getBinormals();
  48330. var distances = path3D.getDistances();
  48331. var angle = 0;
  48332. var returnScale = function () { return scale !== null ? scale : 1; };
  48333. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  48334. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  48335. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  48336. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48337. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48338. for (var i = 0; i < curve.length; i++) {
  48339. var shapePath = new Array();
  48340. var angleStep = rotate(i, distances[i]);
  48341. var scaleRatio = scl(i, distances[i]);
  48342. for (var p = 0; p < shape.length; p++) {
  48343. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48344. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48345. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48346. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48347. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48348. shapePath[p] = rotated;
  48349. }
  48350. shapePaths[index] = shapePath;
  48351. angle += angleStep;
  48352. index++;
  48353. }
  48354. // cap
  48355. var capPath = function (shapePath) {
  48356. var pointCap = Array();
  48357. var barycenter = BABYLON.Vector3.Zero();
  48358. var i;
  48359. for (i = 0; i < shapePath.length; i++) {
  48360. barycenter.addInPlace(shapePath[i]);
  48361. }
  48362. barycenter.scaleInPlace(1.0 / shapePath.length);
  48363. for (i = 0; i < shapePath.length; i++) {
  48364. pointCap.push(barycenter);
  48365. }
  48366. return pointCap;
  48367. };
  48368. switch (cap) {
  48369. case BABYLON.Mesh.NO_CAP:
  48370. break;
  48371. case BABYLON.Mesh.CAP_START:
  48372. shapePaths[0] = capPath(shapePaths[2]);
  48373. shapePaths[1] = shapePaths[2];
  48374. break;
  48375. case BABYLON.Mesh.CAP_END:
  48376. shapePaths[index] = shapePaths[index - 1];
  48377. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48378. break;
  48379. case BABYLON.Mesh.CAP_ALL:
  48380. shapePaths[0] = capPath(shapePaths[2]);
  48381. shapePaths[1] = shapePaths[2];
  48382. shapePaths[index] = shapePaths[index - 1];
  48383. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48384. break;
  48385. default:
  48386. break;
  48387. }
  48388. return shapePaths;
  48389. };
  48390. var path3D;
  48391. var pathArray;
  48392. if (instance) {
  48393. path3D = (instance.path3D).update(curve);
  48394. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48395. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48396. return instance;
  48397. }
  48398. // extruded shape creation
  48399. path3D = new BABYLON.Path3D(curve);
  48400. var newShapePaths = new Array();
  48401. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48402. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48403. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48404. extrudedGeneric.pathArray = pathArray;
  48405. extrudedGeneric.path3D = path3D;
  48406. extrudedGeneric.cap = cap;
  48407. return extrudedGeneric;
  48408. };
  48409. return MeshBuilder;
  48410. }());
  48411. BABYLON.MeshBuilder = MeshBuilder;
  48412. })(BABYLON || (BABYLON = {}));
  48413. //# sourceMappingURL=babylon.meshBuilder.js.map
  48414. var BABYLON;
  48415. (function (BABYLON) {
  48416. var AudioEngine = /** @class */ (function () {
  48417. function AudioEngine() {
  48418. this._audioContext = null;
  48419. this._audioContextInitialized = false;
  48420. this.canUseWebAudio = false;
  48421. this.WarnedWebAudioUnsupported = false;
  48422. this.unlocked = false;
  48423. this.isMP3supported = false;
  48424. this.isOGGsupported = false;
  48425. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48426. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48427. this.canUseWebAudio = true;
  48428. }
  48429. var audioElem = document.createElement('audio');
  48430. try {
  48431. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48432. this.isMP3supported = true;
  48433. }
  48434. }
  48435. catch (e) {
  48436. // protect error during capability check.
  48437. }
  48438. try {
  48439. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48440. this.isOGGsupported = true;
  48441. }
  48442. }
  48443. catch (e) {
  48444. // protect error during capability check.
  48445. }
  48446. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48447. this._unlockiOSaudio();
  48448. }
  48449. else {
  48450. this.unlocked = true;
  48451. }
  48452. }
  48453. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48454. get: function () {
  48455. if (!this._audioContextInitialized) {
  48456. this._initializeAudioContext();
  48457. }
  48458. return this._audioContext;
  48459. },
  48460. enumerable: true,
  48461. configurable: true
  48462. });
  48463. AudioEngine.prototype._unlockiOSaudio = function () {
  48464. var _this = this;
  48465. var unlockaudio = function () {
  48466. if (!_this.audioContext) {
  48467. return;
  48468. }
  48469. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48470. var source = _this.audioContext.createBufferSource();
  48471. source.buffer = buffer;
  48472. source.connect(_this.audioContext.destination);
  48473. source.start(0);
  48474. setTimeout(function () {
  48475. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48476. _this.unlocked = true;
  48477. window.removeEventListener('touchend', unlockaudio, false);
  48478. if (_this.onAudioUnlocked) {
  48479. _this.onAudioUnlocked();
  48480. }
  48481. }
  48482. }, 0);
  48483. };
  48484. window.addEventListener('touchend', unlockaudio, false);
  48485. };
  48486. AudioEngine.prototype._initializeAudioContext = function () {
  48487. try {
  48488. if (this.canUseWebAudio) {
  48489. this._audioContext = new AudioContext();
  48490. // create a global volume gain node
  48491. this.masterGain = this._audioContext.createGain();
  48492. this.masterGain.gain.value = 1;
  48493. this.masterGain.connect(this._audioContext.destination);
  48494. this._audioContextInitialized = true;
  48495. }
  48496. }
  48497. catch (e) {
  48498. this.canUseWebAudio = false;
  48499. BABYLON.Tools.Error("Web Audio: " + e.message);
  48500. }
  48501. };
  48502. AudioEngine.prototype.dispose = function () {
  48503. if (this.canUseWebAudio && this._audioContextInitialized) {
  48504. if (this._connectedAnalyser && this._audioContext) {
  48505. this._connectedAnalyser.stopDebugCanvas();
  48506. this._connectedAnalyser.dispose();
  48507. this.masterGain.disconnect();
  48508. this.masterGain.connect(this._audioContext.destination);
  48509. this._connectedAnalyser = null;
  48510. }
  48511. this.masterGain.gain.value = 1;
  48512. }
  48513. this.WarnedWebAudioUnsupported = false;
  48514. };
  48515. AudioEngine.prototype.getGlobalVolume = function () {
  48516. if (this.canUseWebAudio && this._audioContextInitialized) {
  48517. return this.masterGain.gain.value;
  48518. }
  48519. else {
  48520. return -1;
  48521. }
  48522. };
  48523. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48524. if (this.canUseWebAudio && this._audioContextInitialized) {
  48525. this.masterGain.gain.value = newVolume;
  48526. }
  48527. };
  48528. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48529. if (this._connectedAnalyser) {
  48530. this._connectedAnalyser.stopDebugCanvas();
  48531. }
  48532. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48533. this._connectedAnalyser = analyser;
  48534. this.masterGain.disconnect();
  48535. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48536. }
  48537. };
  48538. return AudioEngine;
  48539. }());
  48540. BABYLON.AudioEngine = AudioEngine;
  48541. })(BABYLON || (BABYLON = {}));
  48542. //# sourceMappingURL=babylon.audioEngine.js.map
  48543. var BABYLON;
  48544. (function (BABYLON) {
  48545. var Sound = /** @class */ (function () {
  48546. /**
  48547. * Create a sound and attach it to a scene
  48548. * @param name Name of your sound
  48549. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48550. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48551. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48552. */
  48553. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48554. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48555. var _this = this;
  48556. this.autoplay = false;
  48557. this.loop = false;
  48558. this.useCustomAttenuation = false;
  48559. this.spatialSound = false;
  48560. this.refDistance = 1;
  48561. this.rolloffFactor = 1;
  48562. this.maxDistance = 100;
  48563. this.distanceModel = "linear";
  48564. this._panningModel = "equalpower";
  48565. this._playbackRate = 1;
  48566. this._streaming = false;
  48567. this._startTime = 0;
  48568. this._startOffset = 0;
  48569. this._position = BABYLON.Vector3.Zero();
  48570. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48571. this._volume = 1;
  48572. this._isLoaded = false;
  48573. this._isReadyToPlay = false;
  48574. this.isPlaying = false;
  48575. this.isPaused = false;
  48576. this._isDirectional = false;
  48577. // Used if you'd like to create a directional sound.
  48578. // If not set, the sound will be omnidirectional
  48579. this._coneInnerAngle = 360;
  48580. this._coneOuterAngle = 360;
  48581. this._coneOuterGain = 0;
  48582. this._isOutputConnected = false;
  48583. this._urlType = "Unknown";
  48584. this.name = name;
  48585. this._scene = scene;
  48586. this._readyToPlayCallback = readyToPlayCallback;
  48587. // Default custom attenuation function is a linear attenuation
  48588. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48589. if (currentDistance < maxDistance) {
  48590. return currentVolume * (1 - currentDistance / maxDistance);
  48591. }
  48592. else {
  48593. return 0;
  48594. }
  48595. };
  48596. if (options) {
  48597. this.autoplay = options.autoplay || false;
  48598. this.loop = options.loop || false;
  48599. // if volume === 0, we need another way to check this option
  48600. if (options.volume !== undefined) {
  48601. this._volume = options.volume;
  48602. }
  48603. this.spatialSound = options.spatialSound || false;
  48604. this.maxDistance = options.maxDistance || 100;
  48605. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48606. this.rolloffFactor = options.rolloffFactor || 1;
  48607. this.refDistance = options.refDistance || 1;
  48608. this.distanceModel = options.distanceModel || "linear";
  48609. this._playbackRate = options.playbackRate || 1;
  48610. this._streaming = options.streaming || false;
  48611. }
  48612. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48613. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48614. this._soundGain.gain.value = this._volume;
  48615. this._inputAudioNode = this._soundGain;
  48616. this._ouputAudioNode = this._soundGain;
  48617. if (this.spatialSound) {
  48618. this._createSpatialParameters();
  48619. }
  48620. this._scene.mainSoundTrack.AddSound(this);
  48621. var validParameter = true;
  48622. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48623. if (urlOrArrayBuffer) {
  48624. if (typeof (urlOrArrayBuffer) === "string")
  48625. this._urlType = "String";
  48626. if (Array.isArray(urlOrArrayBuffer))
  48627. this._urlType = "Array";
  48628. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48629. this._urlType = "ArrayBuffer";
  48630. var urls = [];
  48631. var codecSupportedFound = false;
  48632. switch (this._urlType) {
  48633. case "ArrayBuffer":
  48634. if (urlOrArrayBuffer.byteLength > 0) {
  48635. codecSupportedFound = true;
  48636. this._soundLoaded(urlOrArrayBuffer);
  48637. }
  48638. break;
  48639. case "String":
  48640. urls.push(urlOrArrayBuffer);
  48641. case "Array":
  48642. if (urls.length === 0)
  48643. urls = urlOrArrayBuffer;
  48644. // If we found a supported format, we load it immediately and stop the loop
  48645. for (var i = 0; i < urls.length; i++) {
  48646. var url = urls[i];
  48647. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48648. codecSupportedFound = true;
  48649. }
  48650. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48651. codecSupportedFound = true;
  48652. }
  48653. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48654. codecSupportedFound = true;
  48655. }
  48656. if (url.indexOf("blob:") !== -1) {
  48657. codecSupportedFound = true;
  48658. }
  48659. if (codecSupportedFound) {
  48660. // Loading sound using XHR2
  48661. if (!this._streaming) {
  48662. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48663. }
  48664. else {
  48665. this._htmlAudioElement = new Audio(url);
  48666. this._htmlAudioElement.controls = false;
  48667. this._htmlAudioElement.loop = this.loop;
  48668. this._htmlAudioElement.crossOrigin = "anonymous";
  48669. this._htmlAudioElement.preload = "auto";
  48670. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48671. _this._isReadyToPlay = true;
  48672. if (_this.autoplay) {
  48673. _this.play();
  48674. }
  48675. if (_this._readyToPlayCallback) {
  48676. _this._readyToPlayCallback();
  48677. }
  48678. });
  48679. document.body.appendChild(this._htmlAudioElement);
  48680. }
  48681. break;
  48682. }
  48683. }
  48684. break;
  48685. default:
  48686. validParameter = false;
  48687. break;
  48688. }
  48689. if (!validParameter) {
  48690. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48691. }
  48692. else {
  48693. if (!codecSupportedFound) {
  48694. this._isReadyToPlay = true;
  48695. // Simulating a ready to play event to avoid breaking code path
  48696. if (this._readyToPlayCallback) {
  48697. window.setTimeout(function () {
  48698. if (_this._readyToPlayCallback) {
  48699. _this._readyToPlayCallback();
  48700. }
  48701. }, 1000);
  48702. }
  48703. }
  48704. }
  48705. }
  48706. }
  48707. else {
  48708. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48709. this._scene.mainSoundTrack.AddSound(this);
  48710. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48711. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48712. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48713. }
  48714. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48715. if (this._readyToPlayCallback) {
  48716. window.setTimeout(function () {
  48717. if (_this._readyToPlayCallback) {
  48718. _this._readyToPlayCallback();
  48719. }
  48720. }, 1000);
  48721. }
  48722. }
  48723. }
  48724. Sound.prototype.dispose = function () {
  48725. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48726. if (this.isPlaying) {
  48727. this.stop();
  48728. }
  48729. this._isReadyToPlay = false;
  48730. if (this.soundTrackId === -1) {
  48731. this._scene.mainSoundTrack.RemoveSound(this);
  48732. }
  48733. else {
  48734. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48735. }
  48736. if (this._soundGain) {
  48737. this._soundGain.disconnect();
  48738. this._soundGain = null;
  48739. }
  48740. if (this._soundPanner) {
  48741. this._soundPanner.disconnect();
  48742. this._soundPanner = null;
  48743. }
  48744. if (this._soundSource) {
  48745. this._soundSource.disconnect();
  48746. this._soundSource = null;
  48747. }
  48748. this._audioBuffer = null;
  48749. if (this._htmlAudioElement) {
  48750. this._htmlAudioElement.pause();
  48751. this._htmlAudioElement.src = "";
  48752. document.body.removeChild(this._htmlAudioElement);
  48753. }
  48754. if (this._connectedMesh && this._registerFunc) {
  48755. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48756. this._connectedMesh = null;
  48757. }
  48758. }
  48759. };
  48760. Sound.prototype.isReady = function () {
  48761. return this._isReadyToPlay;
  48762. };
  48763. Sound.prototype._soundLoaded = function (audioData) {
  48764. var _this = this;
  48765. this._isLoaded = true;
  48766. if (!BABYLON.Engine.audioEngine.audioContext) {
  48767. return;
  48768. }
  48769. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48770. _this._audioBuffer = buffer;
  48771. _this._isReadyToPlay = true;
  48772. if (_this.autoplay) {
  48773. _this.play();
  48774. }
  48775. if (_this._readyToPlayCallback) {
  48776. _this._readyToPlayCallback();
  48777. }
  48778. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48779. };
  48780. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48781. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48782. this._audioBuffer = audioBuffer;
  48783. this._isReadyToPlay = true;
  48784. }
  48785. };
  48786. Sound.prototype.updateOptions = function (options) {
  48787. if (options) {
  48788. this.loop = options.loop || this.loop;
  48789. this.maxDistance = options.maxDistance || this.maxDistance;
  48790. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48791. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48792. this.refDistance = options.refDistance || this.refDistance;
  48793. this.distanceModel = options.distanceModel || this.distanceModel;
  48794. this._playbackRate = options.playbackRate || this._playbackRate;
  48795. this._updateSpatialParameters();
  48796. if (this.isPlaying) {
  48797. if (this._streaming) {
  48798. this._htmlAudioElement.playbackRate = this._playbackRate;
  48799. }
  48800. else {
  48801. if (this._soundSource) {
  48802. this._soundSource.playbackRate.value = this._playbackRate;
  48803. }
  48804. }
  48805. }
  48806. }
  48807. };
  48808. Sound.prototype._createSpatialParameters = function () {
  48809. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48810. if (this._scene.headphone) {
  48811. this._panningModel = "HRTF";
  48812. }
  48813. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48814. this._updateSpatialParameters();
  48815. this._soundPanner.connect(this._ouputAudioNode);
  48816. this._inputAudioNode = this._soundPanner;
  48817. }
  48818. };
  48819. Sound.prototype._updateSpatialParameters = function () {
  48820. if (this.spatialSound && this._soundPanner) {
  48821. if (this.useCustomAttenuation) {
  48822. // Tricks to disable in a way embedded Web Audio attenuation
  48823. this._soundPanner.distanceModel = "linear";
  48824. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48825. this._soundPanner.refDistance = 1;
  48826. this._soundPanner.rolloffFactor = 1;
  48827. this._soundPanner.panningModel = this._panningModel;
  48828. }
  48829. else {
  48830. this._soundPanner.distanceModel = this.distanceModel;
  48831. this._soundPanner.maxDistance = this.maxDistance;
  48832. this._soundPanner.refDistance = this.refDistance;
  48833. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48834. this._soundPanner.panningModel = this._panningModel;
  48835. }
  48836. }
  48837. };
  48838. Sound.prototype.switchPanningModelToHRTF = function () {
  48839. this._panningModel = "HRTF";
  48840. this._switchPanningModel();
  48841. };
  48842. Sound.prototype.switchPanningModelToEqualPower = function () {
  48843. this._panningModel = "equalpower";
  48844. this._switchPanningModel();
  48845. };
  48846. Sound.prototype._switchPanningModel = function () {
  48847. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48848. this._soundPanner.panningModel = this._panningModel;
  48849. }
  48850. };
  48851. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48852. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48853. if (this._isOutputConnected) {
  48854. this._ouputAudioNode.disconnect();
  48855. }
  48856. this._ouputAudioNode.connect(soundTrackAudioNode);
  48857. this._isOutputConnected = true;
  48858. }
  48859. };
  48860. /**
  48861. * Transform this sound into a directional source
  48862. * @param coneInnerAngle Size of the inner cone in degree
  48863. * @param coneOuterAngle Size of the outer cone in degree
  48864. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48865. */
  48866. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48867. if (coneOuterAngle < coneInnerAngle) {
  48868. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48869. return;
  48870. }
  48871. this._coneInnerAngle = coneInnerAngle;
  48872. this._coneOuterAngle = coneOuterAngle;
  48873. this._coneOuterGain = coneOuterGain;
  48874. this._isDirectional = true;
  48875. if (this.isPlaying && this.loop) {
  48876. this.stop();
  48877. this.play();
  48878. }
  48879. };
  48880. Sound.prototype.setPosition = function (newPosition) {
  48881. this._position = newPosition;
  48882. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48883. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48884. }
  48885. };
  48886. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48887. this._localDirection = newLocalDirection;
  48888. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48889. this._updateDirection();
  48890. }
  48891. };
  48892. Sound.prototype._updateDirection = function () {
  48893. if (!this._connectedMesh || !this._soundPanner) {
  48894. return;
  48895. }
  48896. var mat = this._connectedMesh.getWorldMatrix();
  48897. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48898. direction.normalize();
  48899. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48900. };
  48901. Sound.prototype.updateDistanceFromListener = function () {
  48902. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48903. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48904. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48905. }
  48906. };
  48907. Sound.prototype.setAttenuationFunction = function (callback) {
  48908. this._customAttenuationFunction = callback;
  48909. };
  48910. /**
  48911. * Play the sound
  48912. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48913. * @param offset (optional) Start the sound setting it at a specific time
  48914. */
  48915. Sound.prototype.play = function (time, offset) {
  48916. var _this = this;
  48917. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48918. try {
  48919. if (this._startOffset < 0) {
  48920. time = -this._startOffset;
  48921. this._startOffset = 0;
  48922. }
  48923. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48924. if (!this._soundSource || !this._streamingSource) {
  48925. if (this.spatialSound && this._soundPanner) {
  48926. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48927. if (this._isDirectional) {
  48928. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48929. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48930. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48931. if (this._connectedMesh) {
  48932. this._updateDirection();
  48933. }
  48934. else {
  48935. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48936. }
  48937. }
  48938. }
  48939. }
  48940. if (this._streaming) {
  48941. if (!this._streamingSource) {
  48942. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48943. this._htmlAudioElement.onended = function () { _this._onended(); };
  48944. this._htmlAudioElement.playbackRate = this._playbackRate;
  48945. }
  48946. this._streamingSource.disconnect();
  48947. this._streamingSource.connect(this._inputAudioNode);
  48948. this._htmlAudioElement.play();
  48949. }
  48950. else {
  48951. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48952. this._soundSource.buffer = this._audioBuffer;
  48953. this._soundSource.connect(this._inputAudioNode);
  48954. this._soundSource.loop = this.loop;
  48955. this._soundSource.playbackRate.value = this._playbackRate;
  48956. this._soundSource.onended = function () { _this._onended(); };
  48957. if (this._soundSource.buffer) {
  48958. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48959. }
  48960. }
  48961. this._startTime = startTime;
  48962. this.isPlaying = true;
  48963. this.isPaused = false;
  48964. }
  48965. catch (ex) {
  48966. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48967. }
  48968. }
  48969. };
  48970. Sound.prototype._onended = function () {
  48971. this.isPlaying = false;
  48972. if (this.onended) {
  48973. this.onended();
  48974. }
  48975. };
  48976. /**
  48977. * Stop the sound
  48978. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48979. */
  48980. Sound.prototype.stop = function (time) {
  48981. if (this.isPlaying) {
  48982. if (this._streaming) {
  48983. this._htmlAudioElement.pause();
  48984. // Test needed for Firefox or it will generate an Invalid State Error
  48985. if (this._htmlAudioElement.currentTime > 0) {
  48986. this._htmlAudioElement.currentTime = 0;
  48987. }
  48988. }
  48989. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48990. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48991. this._soundSource.stop(stopTime);
  48992. this._soundSource.onended = function () { };
  48993. if (!this.isPaused) {
  48994. this._startOffset = 0;
  48995. }
  48996. }
  48997. this.isPlaying = false;
  48998. }
  48999. };
  49000. Sound.prototype.pause = function () {
  49001. if (this.isPlaying) {
  49002. this.isPaused = true;
  49003. if (this._streaming) {
  49004. this._htmlAudioElement.pause();
  49005. }
  49006. else if (BABYLON.Engine.audioEngine.audioContext) {
  49007. this.stop(0);
  49008. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  49009. }
  49010. }
  49011. };
  49012. Sound.prototype.setVolume = function (newVolume, time) {
  49013. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  49014. if (time && BABYLON.Engine.audioEngine.audioContext) {
  49015. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  49016. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  49017. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  49018. }
  49019. else {
  49020. this._soundGain.gain.value = newVolume;
  49021. }
  49022. }
  49023. this._volume = newVolume;
  49024. };
  49025. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  49026. this._playbackRate = newPlaybackRate;
  49027. if (this.isPlaying) {
  49028. if (this._streaming) {
  49029. this._htmlAudioElement.playbackRate = this._playbackRate;
  49030. }
  49031. else if (this._soundSource) {
  49032. this._soundSource.playbackRate.value = this._playbackRate;
  49033. }
  49034. }
  49035. };
  49036. Sound.prototype.getVolume = function () {
  49037. return this._volume;
  49038. };
  49039. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  49040. var _this = this;
  49041. if (this._connectedMesh && this._registerFunc) {
  49042. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49043. this._registerFunc = null;
  49044. }
  49045. this._connectedMesh = meshToConnectTo;
  49046. if (!this.spatialSound) {
  49047. this.spatialSound = true;
  49048. this._createSpatialParameters();
  49049. if (this.isPlaying && this.loop) {
  49050. this.stop();
  49051. this.play();
  49052. }
  49053. }
  49054. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  49055. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  49056. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  49057. };
  49058. Sound.prototype.detachFromMesh = function () {
  49059. if (this._connectedMesh && this._registerFunc) {
  49060. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49061. this._registerFunc = null;
  49062. this._connectedMesh = null;
  49063. }
  49064. };
  49065. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  49066. var boundingInfo = connectedMesh.getBoundingInfo();
  49067. if (!boundingInfo) {
  49068. return;
  49069. }
  49070. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  49071. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  49072. this._updateDirection();
  49073. }
  49074. };
  49075. Sound.prototype.clone = function () {
  49076. var _this = this;
  49077. if (!this._streaming) {
  49078. var setBufferAndRun = function () {
  49079. if (_this._isReadyToPlay) {
  49080. clonedSound._audioBuffer = _this.getAudioBuffer();
  49081. clonedSound._isReadyToPlay = true;
  49082. if (clonedSound.autoplay) {
  49083. clonedSound.play();
  49084. }
  49085. }
  49086. else {
  49087. window.setTimeout(setBufferAndRun, 300);
  49088. }
  49089. };
  49090. var currentOptions = {
  49091. autoplay: this.autoplay, loop: this.loop,
  49092. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  49093. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  49094. refDistance: this.refDistance, distanceModel: this.distanceModel
  49095. };
  49096. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  49097. if (this.useCustomAttenuation) {
  49098. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  49099. }
  49100. clonedSound.setPosition(this._position);
  49101. clonedSound.setPlaybackRate(this._playbackRate);
  49102. setBufferAndRun();
  49103. return clonedSound;
  49104. }
  49105. else {
  49106. return null;
  49107. }
  49108. };
  49109. Sound.prototype.getAudioBuffer = function () {
  49110. return this._audioBuffer;
  49111. };
  49112. Sound.prototype.serialize = function () {
  49113. var serializationObject = {
  49114. name: this.name,
  49115. url: this.name,
  49116. autoplay: this.autoplay,
  49117. loop: this.loop,
  49118. volume: this._volume,
  49119. spatialSound: this.spatialSound,
  49120. maxDistance: this.maxDistance,
  49121. rolloffFactor: this.rolloffFactor,
  49122. refDistance: this.refDistance,
  49123. distanceModel: this.distanceModel,
  49124. playbackRate: this._playbackRate,
  49125. panningModel: this._panningModel,
  49126. soundTrackId: this.soundTrackId
  49127. };
  49128. if (this.spatialSound) {
  49129. if (this._connectedMesh)
  49130. serializationObject.connectedMeshId = this._connectedMesh.id;
  49131. serializationObject.position = this._position.asArray();
  49132. serializationObject.refDistance = this.refDistance;
  49133. serializationObject.distanceModel = this.distanceModel;
  49134. serializationObject.isDirectional = this._isDirectional;
  49135. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  49136. serializationObject.coneInnerAngle = this._coneInnerAngle;
  49137. serializationObject.coneOuterAngle = this._coneOuterAngle;
  49138. serializationObject.coneOuterGain = this._coneOuterGain;
  49139. }
  49140. return serializationObject;
  49141. };
  49142. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  49143. var soundName = parsedSound.name;
  49144. var soundUrl;
  49145. if (parsedSound.url) {
  49146. soundUrl = rootUrl + parsedSound.url;
  49147. }
  49148. else {
  49149. soundUrl = rootUrl + soundName;
  49150. }
  49151. var options = {
  49152. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  49153. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  49154. rolloffFactor: parsedSound.rolloffFactor,
  49155. refDistance: parsedSound.refDistance,
  49156. distanceModel: parsedSound.distanceModel,
  49157. playbackRate: parsedSound.playbackRate
  49158. };
  49159. var newSound;
  49160. if (!sourceSound) {
  49161. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  49162. scene._addPendingData(newSound);
  49163. }
  49164. else {
  49165. var setBufferAndRun = function () {
  49166. if (sourceSound._isReadyToPlay) {
  49167. newSound._audioBuffer = sourceSound.getAudioBuffer();
  49168. newSound._isReadyToPlay = true;
  49169. if (newSound.autoplay) {
  49170. newSound.play();
  49171. }
  49172. }
  49173. else {
  49174. window.setTimeout(setBufferAndRun, 300);
  49175. }
  49176. };
  49177. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  49178. setBufferAndRun();
  49179. }
  49180. if (parsedSound.position) {
  49181. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  49182. newSound.setPosition(soundPosition);
  49183. }
  49184. if (parsedSound.isDirectional) {
  49185. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  49186. if (parsedSound.localDirectionToMesh) {
  49187. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  49188. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  49189. }
  49190. }
  49191. if (parsedSound.connectedMeshId) {
  49192. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  49193. if (connectedMesh) {
  49194. newSound.attachToMesh(connectedMesh);
  49195. }
  49196. }
  49197. return newSound;
  49198. };
  49199. return Sound;
  49200. }());
  49201. BABYLON.Sound = Sound;
  49202. })(BABYLON || (BABYLON = {}));
  49203. //# sourceMappingURL=babylon.sound.js.map
  49204. var BABYLON;
  49205. (function (BABYLON) {
  49206. var SoundTrack = /** @class */ (function () {
  49207. function SoundTrack(scene, options) {
  49208. this.id = -1;
  49209. this._isMainTrack = false;
  49210. this._isInitialized = false;
  49211. this._scene = scene;
  49212. this.soundCollection = new Array();
  49213. this._options = options;
  49214. if (!this._isMainTrack) {
  49215. this._scene.soundTracks.push(this);
  49216. this.id = this._scene.soundTracks.length - 1;
  49217. }
  49218. }
  49219. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  49220. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49221. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  49222. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  49223. if (this._options) {
  49224. if (this._options.volume) {
  49225. this._outputAudioNode.gain.value = this._options.volume;
  49226. }
  49227. if (this._options.mainTrack) {
  49228. this._isMainTrack = this._options.mainTrack;
  49229. }
  49230. }
  49231. this._isInitialized = true;
  49232. }
  49233. };
  49234. SoundTrack.prototype.dispose = function () {
  49235. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49236. if (this._connectedAnalyser) {
  49237. this._connectedAnalyser.stopDebugCanvas();
  49238. }
  49239. while (this.soundCollection.length) {
  49240. this.soundCollection[0].dispose();
  49241. }
  49242. if (this._outputAudioNode) {
  49243. this._outputAudioNode.disconnect();
  49244. }
  49245. this._outputAudioNode = null;
  49246. }
  49247. };
  49248. SoundTrack.prototype.AddSound = function (sound) {
  49249. if (!this._isInitialized) {
  49250. this._initializeSoundTrackAudioGraph();
  49251. }
  49252. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49253. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  49254. }
  49255. if (sound.soundTrackId) {
  49256. if (sound.soundTrackId === -1) {
  49257. this._scene.mainSoundTrack.RemoveSound(sound);
  49258. }
  49259. else {
  49260. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  49261. }
  49262. }
  49263. this.soundCollection.push(sound);
  49264. sound.soundTrackId = this.id;
  49265. };
  49266. SoundTrack.prototype.RemoveSound = function (sound) {
  49267. var index = this.soundCollection.indexOf(sound);
  49268. if (index !== -1) {
  49269. this.soundCollection.splice(index, 1);
  49270. }
  49271. };
  49272. SoundTrack.prototype.setVolume = function (newVolume) {
  49273. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49274. this._outputAudioNode.gain.value = newVolume;
  49275. }
  49276. };
  49277. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  49278. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49279. for (var i = 0; i < this.soundCollection.length; i++) {
  49280. this.soundCollection[i].switchPanningModelToHRTF();
  49281. }
  49282. }
  49283. };
  49284. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  49285. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49286. for (var i = 0; i < this.soundCollection.length; i++) {
  49287. this.soundCollection[i].switchPanningModelToEqualPower();
  49288. }
  49289. }
  49290. };
  49291. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  49292. if (this._connectedAnalyser) {
  49293. this._connectedAnalyser.stopDebugCanvas();
  49294. }
  49295. this._connectedAnalyser = analyser;
  49296. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49297. this._outputAudioNode.disconnect();
  49298. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  49299. }
  49300. };
  49301. return SoundTrack;
  49302. }());
  49303. BABYLON.SoundTrack = SoundTrack;
  49304. })(BABYLON || (BABYLON = {}));
  49305. //# sourceMappingURL=babylon.soundtrack.js.map
  49306. var BABYLON;
  49307. (function (BABYLON) {
  49308. var Analyser = /** @class */ (function () {
  49309. function Analyser(scene) {
  49310. this.SMOOTHING = 0.75;
  49311. this.FFT_SIZE = 512;
  49312. this.BARGRAPHAMPLITUDE = 256;
  49313. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49314. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49315. this._scene = scene;
  49316. this._audioEngine = BABYLON.Engine.audioEngine;
  49317. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  49318. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49319. this._webAudioAnalyser.minDecibels = -140;
  49320. this._webAudioAnalyser.maxDecibels = 0;
  49321. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49322. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49323. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49324. }
  49325. }
  49326. Analyser.prototype.getFrequencyBinCount = function () {
  49327. if (this._audioEngine.canUseWebAudio) {
  49328. return this._webAudioAnalyser.frequencyBinCount;
  49329. }
  49330. else {
  49331. return 0;
  49332. }
  49333. };
  49334. Analyser.prototype.getByteFrequencyData = function () {
  49335. if (this._audioEngine.canUseWebAudio) {
  49336. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49337. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49338. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49339. }
  49340. return this._byteFreqs;
  49341. };
  49342. Analyser.prototype.getByteTimeDomainData = function () {
  49343. if (this._audioEngine.canUseWebAudio) {
  49344. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49345. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49346. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49347. }
  49348. return this._byteTime;
  49349. };
  49350. Analyser.prototype.getFloatFrequencyData = function () {
  49351. if (this._audioEngine.canUseWebAudio) {
  49352. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49353. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49354. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49355. }
  49356. return this._floatFreqs;
  49357. };
  49358. Analyser.prototype.drawDebugCanvas = function () {
  49359. var _this = this;
  49360. if (this._audioEngine.canUseWebAudio) {
  49361. if (!this._debugCanvas) {
  49362. this._debugCanvas = document.createElement("canvas");
  49363. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49364. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49365. this._debugCanvas.style.position = "absolute";
  49366. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49367. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49368. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49369. document.body.appendChild(this._debugCanvas);
  49370. this._registerFunc = function () {
  49371. _this.drawDebugCanvas();
  49372. };
  49373. this._scene.registerBeforeRender(this._registerFunc);
  49374. }
  49375. if (this._registerFunc && this._debugCanvasContext) {
  49376. var workingArray = this.getByteFrequencyData();
  49377. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49378. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49379. // Draw the frequency domain chart.
  49380. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49381. var value = workingArray[i];
  49382. var percent = value / this.BARGRAPHAMPLITUDE;
  49383. var height = this.DEBUGCANVASSIZE.height * percent;
  49384. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49385. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49386. var hue = i / this.getFrequencyBinCount() * 360;
  49387. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49388. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49389. }
  49390. }
  49391. }
  49392. };
  49393. Analyser.prototype.stopDebugCanvas = function () {
  49394. if (this._debugCanvas) {
  49395. if (this._registerFunc) {
  49396. this._scene.unregisterBeforeRender(this._registerFunc);
  49397. this._registerFunc = null;
  49398. }
  49399. document.body.removeChild(this._debugCanvas);
  49400. this._debugCanvas = null;
  49401. this._debugCanvasContext = null;
  49402. }
  49403. };
  49404. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49405. if (this._audioEngine.canUseWebAudio) {
  49406. inputAudioNode.connect(this._webAudioAnalyser);
  49407. this._webAudioAnalyser.connect(outputAudioNode);
  49408. }
  49409. };
  49410. Analyser.prototype.dispose = function () {
  49411. if (this._audioEngine.canUseWebAudio) {
  49412. this._webAudioAnalyser.disconnect();
  49413. }
  49414. };
  49415. return Analyser;
  49416. }());
  49417. BABYLON.Analyser = Analyser;
  49418. })(BABYLON || (BABYLON = {}));
  49419. //# sourceMappingURL=babylon.analyser.js.map
  49420. var BABYLON;
  49421. (function (BABYLON) {
  49422. var CubeTexture = /** @class */ (function (_super) {
  49423. __extends(CubeTexture, _super);
  49424. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49425. if (extensions === void 0) { extensions = null; }
  49426. if (noMipmap === void 0) { noMipmap = false; }
  49427. if (files === void 0) { files = null; }
  49428. if (onLoad === void 0) { onLoad = null; }
  49429. if (onError === void 0) { onError = null; }
  49430. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49431. if (prefiltered === void 0) { prefiltered = false; }
  49432. if (forcedExtension === void 0) { forcedExtension = null; }
  49433. var _this = _super.call(this, scene) || this;
  49434. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49435. _this.name = rootUrl;
  49436. _this.url = rootUrl;
  49437. _this._noMipmap = noMipmap;
  49438. _this.hasAlpha = false;
  49439. _this._format = format;
  49440. _this._prefiltered = prefiltered;
  49441. _this.isCube = true;
  49442. _this._textureMatrix = BABYLON.Matrix.Identity();
  49443. if (prefiltered) {
  49444. _this.gammaSpace = false;
  49445. }
  49446. if (!rootUrl && !files) {
  49447. return _this;
  49448. }
  49449. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49450. if (!files) {
  49451. if (!extensions) {
  49452. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49453. }
  49454. files = [];
  49455. for (var index = 0; index < extensions.length; index++) {
  49456. files.push(rootUrl + extensions[index]);
  49457. }
  49458. _this._extensions = extensions;
  49459. }
  49460. _this._files = files;
  49461. if (!_this._texture) {
  49462. if (!scene.useDelayedTextureLoading) {
  49463. if (prefiltered) {
  49464. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49465. }
  49466. else {
  49467. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49468. }
  49469. }
  49470. else {
  49471. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49472. }
  49473. }
  49474. else if (onLoad) {
  49475. if (_this._texture.isReady) {
  49476. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49477. }
  49478. else {
  49479. _this._texture.onLoadedObservable.add(onLoad);
  49480. }
  49481. }
  49482. return _this;
  49483. }
  49484. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  49485. return new CubeTexture("", scene, null, noMipmap, files);
  49486. };
  49487. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  49488. if (forcedExtension === void 0) { forcedExtension = null; }
  49489. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  49490. };
  49491. // Methods
  49492. CubeTexture.prototype.delayLoad = function () {
  49493. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49494. return;
  49495. }
  49496. var scene = this.getScene();
  49497. if (!scene) {
  49498. return;
  49499. }
  49500. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49501. this._texture = this._getFromCache(this.url, this._noMipmap);
  49502. if (!this._texture) {
  49503. if (this._prefiltered) {
  49504. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49505. }
  49506. else {
  49507. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49508. }
  49509. }
  49510. };
  49511. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49512. return this._textureMatrix;
  49513. };
  49514. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49515. this._textureMatrix = value;
  49516. };
  49517. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49518. var texture = BABYLON.SerializationHelper.Parse(function () {
  49519. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49520. }, parsedTexture, scene);
  49521. // Animations
  49522. if (parsedTexture.animations) {
  49523. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49524. var parsedAnimation = parsedTexture.animations[animationIndex];
  49525. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49526. }
  49527. }
  49528. return texture;
  49529. };
  49530. CubeTexture.prototype.clone = function () {
  49531. var _this = this;
  49532. return BABYLON.SerializationHelper.Clone(function () {
  49533. var scene = _this.getScene();
  49534. if (!scene) {
  49535. return _this;
  49536. }
  49537. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49538. }, this);
  49539. };
  49540. return CubeTexture;
  49541. }(BABYLON.BaseTexture));
  49542. BABYLON.CubeTexture = CubeTexture;
  49543. })(BABYLON || (BABYLON = {}));
  49544. //# sourceMappingURL=babylon.cubeTexture.js.map
  49545. var BABYLON;
  49546. (function (BABYLON) {
  49547. var RenderTargetTexture = /** @class */ (function (_super) {
  49548. __extends(RenderTargetTexture, _super);
  49549. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49550. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49551. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49552. if (isCube === void 0) { isCube = false; }
  49553. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49554. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49555. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49556. if (isMulti === void 0) { isMulti = false; }
  49557. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49558. _this.isCube = isCube;
  49559. /**
  49560. * Use this list to define the list of mesh you want to render.
  49561. */
  49562. _this.renderList = new Array();
  49563. _this.renderParticles = true;
  49564. _this.renderSprites = false;
  49565. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49566. _this.ignoreCameraViewport = false;
  49567. // Events
  49568. /**
  49569. * An event triggered when the texture is unbind.
  49570. * @type {BABYLON.Observable}
  49571. */
  49572. _this.onBeforeBindObservable = new BABYLON.Observable();
  49573. /**
  49574. * An event triggered when the texture is unbind.
  49575. * @type {BABYLON.Observable}
  49576. */
  49577. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49578. /**
  49579. * An event triggered before rendering the texture
  49580. * @type {BABYLON.Observable}
  49581. */
  49582. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49583. /**
  49584. * An event triggered after rendering the texture
  49585. * @type {BABYLON.Observable}
  49586. */
  49587. _this.onAfterRenderObservable = new BABYLON.Observable();
  49588. /**
  49589. * An event triggered after the texture clear
  49590. * @type {BABYLON.Observable}
  49591. */
  49592. _this.onClearObservable = new BABYLON.Observable();
  49593. _this._currentRefreshId = -1;
  49594. _this._refreshRate = 1;
  49595. _this._samples = 1;
  49596. scene = _this.getScene();
  49597. if (!scene) {
  49598. return _this;
  49599. }
  49600. _this._engine = scene.getEngine();
  49601. _this.name = name;
  49602. _this.isRenderTarget = true;
  49603. _this._initialSizeParameter = size;
  49604. _this._processSizeParameter(size);
  49605. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  49606. });
  49607. _this._generateMipMaps = generateMipMaps ? true : false;
  49608. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49609. // Rendering groups
  49610. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49611. if (isMulti) {
  49612. return _this;
  49613. }
  49614. _this._renderTargetOptions = {
  49615. generateMipMaps: generateMipMaps,
  49616. type: type,
  49617. samplingMode: samplingMode,
  49618. generateDepthBuffer: generateDepthBuffer,
  49619. generateStencilBuffer: generateStencilBuffer
  49620. };
  49621. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49622. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49623. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49624. }
  49625. if (isCube) {
  49626. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  49627. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49628. _this._textureMatrix = BABYLON.Matrix.Identity();
  49629. }
  49630. else {
  49631. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  49632. }
  49633. return _this;
  49634. }
  49635. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49636. get: function () {
  49637. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49638. },
  49639. enumerable: true,
  49640. configurable: true
  49641. });
  49642. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49643. get: function () {
  49644. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49645. },
  49646. enumerable: true,
  49647. configurable: true
  49648. });
  49649. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49650. get: function () {
  49651. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49652. },
  49653. enumerable: true,
  49654. configurable: true
  49655. });
  49656. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49657. set: function (callback) {
  49658. if (this._onAfterUnbindObserver) {
  49659. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49660. }
  49661. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49662. },
  49663. enumerable: true,
  49664. configurable: true
  49665. });
  49666. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49667. set: function (callback) {
  49668. if (this._onBeforeRenderObserver) {
  49669. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49670. }
  49671. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49672. },
  49673. enumerable: true,
  49674. configurable: true
  49675. });
  49676. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49677. set: function (callback) {
  49678. if (this._onAfterRenderObserver) {
  49679. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49680. }
  49681. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49682. },
  49683. enumerable: true,
  49684. configurable: true
  49685. });
  49686. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49687. set: function (callback) {
  49688. if (this._onClearObserver) {
  49689. this.onClearObservable.remove(this._onClearObserver);
  49690. }
  49691. this._onClearObserver = this.onClearObservable.add(callback);
  49692. },
  49693. enumerable: true,
  49694. configurable: true
  49695. });
  49696. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49697. get: function () {
  49698. return this._renderTargetOptions;
  49699. },
  49700. enumerable: true,
  49701. configurable: true
  49702. });
  49703. RenderTargetTexture.prototype._onRatioRescale = function () {
  49704. if (this._sizeRatio) {
  49705. this.resize(this._initialSizeParameter);
  49706. }
  49707. };
  49708. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  49709. if (size.ratio) {
  49710. this._sizeRatio = size.ratio;
  49711. this._size = {
  49712. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  49713. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  49714. };
  49715. }
  49716. else {
  49717. this._size = size;
  49718. }
  49719. };
  49720. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49721. get: function () {
  49722. return this._samples;
  49723. },
  49724. set: function (value) {
  49725. if (this._samples === value) {
  49726. return;
  49727. }
  49728. var scene = this.getScene();
  49729. if (!scene) {
  49730. return;
  49731. }
  49732. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49733. },
  49734. enumerable: true,
  49735. configurable: true
  49736. });
  49737. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49738. this._currentRefreshId = -1;
  49739. };
  49740. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49741. get: function () {
  49742. return this._refreshRate;
  49743. },
  49744. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49745. set: function (value) {
  49746. this._refreshRate = value;
  49747. this.resetRefreshCounter();
  49748. },
  49749. enumerable: true,
  49750. configurable: true
  49751. });
  49752. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49753. if (!this._postProcessManager) {
  49754. var scene = this.getScene();
  49755. if (!scene) {
  49756. return;
  49757. }
  49758. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49759. this._postProcesses = new Array();
  49760. }
  49761. this._postProcesses.push(postProcess);
  49762. this._postProcesses[0].autoClear = false;
  49763. };
  49764. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49765. if (!this._postProcesses) {
  49766. return;
  49767. }
  49768. if (dispose) {
  49769. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49770. var postProcess = _a[_i];
  49771. postProcess.dispose();
  49772. }
  49773. }
  49774. this._postProcesses = [];
  49775. };
  49776. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49777. if (!this._postProcesses) {
  49778. return;
  49779. }
  49780. var index = this._postProcesses.indexOf(postProcess);
  49781. if (index === -1) {
  49782. return;
  49783. }
  49784. this._postProcesses.splice(index, 1);
  49785. if (this._postProcesses.length > 0) {
  49786. this._postProcesses[0].autoClear = false;
  49787. }
  49788. };
  49789. RenderTargetTexture.prototype._shouldRender = function () {
  49790. if (this._currentRefreshId === -1) {
  49791. this._currentRefreshId = 1;
  49792. return true;
  49793. }
  49794. if (this.refreshRate === this._currentRefreshId) {
  49795. this._currentRefreshId = 1;
  49796. return true;
  49797. }
  49798. this._currentRefreshId++;
  49799. return false;
  49800. };
  49801. RenderTargetTexture.prototype.getRenderSize = function () {
  49802. if (this._size.width) {
  49803. return this._size.width;
  49804. }
  49805. return this._size;
  49806. };
  49807. RenderTargetTexture.prototype.getRenderWidth = function () {
  49808. if (this._size.width) {
  49809. return this._size.width;
  49810. }
  49811. return this._size;
  49812. };
  49813. RenderTargetTexture.prototype.getRenderHeight = function () {
  49814. if (this._size.width) {
  49815. return this._size.height;
  49816. }
  49817. return this._size;
  49818. };
  49819. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49820. get: function () {
  49821. return true;
  49822. },
  49823. enumerable: true,
  49824. configurable: true
  49825. });
  49826. RenderTargetTexture.prototype.scale = function (ratio) {
  49827. var newSize = this.getRenderSize() * ratio;
  49828. this.resize(newSize);
  49829. };
  49830. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49831. if (this.isCube) {
  49832. return this._textureMatrix;
  49833. }
  49834. return _super.prototype.getReflectionTextureMatrix.call(this);
  49835. };
  49836. RenderTargetTexture.prototype.resize = function (size) {
  49837. this.releaseInternalTexture();
  49838. var scene = this.getScene();
  49839. if (!scene) {
  49840. return;
  49841. }
  49842. this._processSizeParameter(size);
  49843. if (this.isCube) {
  49844. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  49845. }
  49846. else {
  49847. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  49848. }
  49849. };
  49850. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49851. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49852. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49853. var scene = this.getScene();
  49854. if (!scene) {
  49855. return;
  49856. }
  49857. var engine = scene.getEngine();
  49858. if (this.useCameraPostProcesses !== undefined) {
  49859. useCameraPostProcess = this.useCameraPostProcesses;
  49860. }
  49861. if (this._waitingRenderList) {
  49862. this.renderList = [];
  49863. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49864. var id = this._waitingRenderList[index];
  49865. var mesh_1 = scene.getMeshByID(id);
  49866. if (mesh_1) {
  49867. this.renderList.push(mesh_1);
  49868. }
  49869. }
  49870. delete this._waitingRenderList;
  49871. }
  49872. // Is predicate defined?
  49873. if (this.renderListPredicate) {
  49874. if (this.renderList) {
  49875. this.renderList.splice(0); // Clear previous renderList
  49876. }
  49877. else {
  49878. this.renderList = [];
  49879. }
  49880. var scene = this.getScene();
  49881. if (!scene) {
  49882. return;
  49883. }
  49884. var sceneMeshes = scene.meshes;
  49885. for (var index = 0; index < sceneMeshes.length; index++) {
  49886. var mesh = sceneMeshes[index];
  49887. if (this.renderListPredicate(mesh)) {
  49888. this.renderList.push(mesh);
  49889. }
  49890. }
  49891. }
  49892. this.onBeforeBindObservable.notifyObservers(this);
  49893. // Set custom projection.
  49894. // Needs to be before binding to prevent changing the aspect ratio.
  49895. var camera;
  49896. if (this.activeCamera) {
  49897. camera = this.activeCamera;
  49898. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  49899. if (this.activeCamera !== scene.activeCamera) {
  49900. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49901. }
  49902. }
  49903. else {
  49904. camera = scene.activeCamera;
  49905. if (camera) {
  49906. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  49907. }
  49908. }
  49909. // Prepare renderingManager
  49910. this._renderingManager.reset();
  49911. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49912. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49913. var sceneRenderId = scene.getRenderId();
  49914. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49915. var mesh = currentRenderList[meshIndex];
  49916. if (mesh) {
  49917. if (!mesh.isReady()) {
  49918. // Reset _currentRefreshId
  49919. this.resetRefreshCounter();
  49920. continue;
  49921. }
  49922. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49923. var isMasked = void 0;
  49924. if (!this.renderList && camera) {
  49925. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49926. }
  49927. else {
  49928. isMasked = false;
  49929. }
  49930. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49931. mesh._activate(sceneRenderId);
  49932. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49933. var subMesh = mesh.subMeshes[subIndex];
  49934. scene._activeIndices.addCount(subMesh.indexCount, false);
  49935. this._renderingManager.dispatch(subMesh);
  49936. }
  49937. }
  49938. }
  49939. }
  49940. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49941. var particleSystem = scene.particleSystems[particleIndex];
  49942. var emitter = particleSystem.emitter;
  49943. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49944. continue;
  49945. }
  49946. if (currentRenderList.indexOf(emitter) >= 0) {
  49947. this._renderingManager.dispatchParticles(particleSystem);
  49948. }
  49949. }
  49950. if (this.isCube) {
  49951. for (var face = 0; face < 6; face++) {
  49952. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49953. scene.incrementRenderId();
  49954. scene.resetCachedMaterial();
  49955. }
  49956. }
  49957. else {
  49958. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49959. }
  49960. this.onAfterUnbindObservable.notifyObservers(this);
  49961. if (scene.activeCamera) {
  49962. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49963. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49964. }
  49965. engine.setViewport(scene.activeCamera.viewport);
  49966. }
  49967. scene.resetCachedMaterial();
  49968. };
  49969. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  49970. var minimum = 128;
  49971. var x = renderDimension * scale;
  49972. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  49973. // Ensure we don't exceed the render dimension (while staying POT)
  49974. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  49975. };
  49976. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49977. var _this = this;
  49978. var scene = this.getScene();
  49979. if (!scene) {
  49980. return;
  49981. }
  49982. var engine = scene.getEngine();
  49983. if (!this._texture) {
  49984. return;
  49985. }
  49986. // Bind
  49987. if (this._postProcessManager) {
  49988. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49989. }
  49990. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49991. if (this._texture) {
  49992. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49993. }
  49994. }
  49995. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49996. // Clear
  49997. if (this.onClearObservable.hasObservers()) {
  49998. this.onClearObservable.notifyObservers(engine);
  49999. }
  50000. else {
  50001. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  50002. }
  50003. if (!this._doNotChangeAspectRatio) {
  50004. scene.updateTransformMatrix(true);
  50005. }
  50006. // Render
  50007. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  50008. if (this._postProcessManager) {
  50009. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  50010. }
  50011. else if (useCameraPostProcess) {
  50012. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  50013. }
  50014. if (!this._doNotChangeAspectRatio) {
  50015. scene.updateTransformMatrix(true);
  50016. }
  50017. // Dump ?
  50018. if (dumpForDebug) {
  50019. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  50020. }
  50021. // Unbind
  50022. if (!this.isCube || faceIndex === 5) {
  50023. if (this.isCube) {
  50024. if (faceIndex === 5) {
  50025. engine.generateMipMapsForCubemap(this._texture);
  50026. }
  50027. }
  50028. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  50029. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  50030. });
  50031. }
  50032. else {
  50033. this.onAfterRenderObservable.notifyObservers(faceIndex);
  50034. }
  50035. };
  50036. /**
  50037. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  50038. * This allowed control for front to back rendering or reversly depending of the special needs.
  50039. *
  50040. * @param renderingGroupId The rendering group id corresponding to its index
  50041. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  50042. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  50043. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  50044. */
  50045. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  50046. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  50047. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  50048. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  50049. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  50050. };
  50051. /**
  50052. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  50053. *
  50054. * @param renderingGroupId The rendering group id corresponding to its index
  50055. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  50056. */
  50057. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  50058. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  50059. };
  50060. RenderTargetTexture.prototype.clone = function () {
  50061. var textureSize = this.getSize();
  50062. 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);
  50063. // Base texture
  50064. newTexture.hasAlpha = this.hasAlpha;
  50065. newTexture.level = this.level;
  50066. // RenderTarget Texture
  50067. newTexture.coordinatesMode = this.coordinatesMode;
  50068. if (this.renderList) {
  50069. newTexture.renderList = this.renderList.slice(0);
  50070. }
  50071. return newTexture;
  50072. };
  50073. RenderTargetTexture.prototype.serialize = function () {
  50074. if (!this.name) {
  50075. return null;
  50076. }
  50077. var serializationObject = _super.prototype.serialize.call(this);
  50078. serializationObject.renderTargetSize = this.getRenderSize();
  50079. serializationObject.renderList = [];
  50080. if (this.renderList) {
  50081. for (var index = 0; index < this.renderList.length; index++) {
  50082. serializationObject.renderList.push(this.renderList[index].id);
  50083. }
  50084. }
  50085. return serializationObject;
  50086. };
  50087. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  50088. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  50089. var objBuffer = this.getInternalTexture();
  50090. var scene = this.getScene();
  50091. if (objBuffer && scene) {
  50092. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  50093. }
  50094. };
  50095. RenderTargetTexture.prototype.dispose = function () {
  50096. if (this._postProcessManager) {
  50097. this._postProcessManager.dispose();
  50098. this._postProcessManager = null;
  50099. }
  50100. this.clearPostProcesses(true);
  50101. if (this._resizeObserver) {
  50102. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  50103. this._resizeObserver = null;
  50104. }
  50105. this.renderList = null;
  50106. // Remove from custom render targets
  50107. var scene = this.getScene();
  50108. if (!scene) {
  50109. return;
  50110. }
  50111. var index = scene.customRenderTargets.indexOf(this);
  50112. if (index >= 0) {
  50113. scene.customRenderTargets.splice(index, 1);
  50114. }
  50115. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  50116. var camera = _a[_i];
  50117. index = camera.customRenderTargets.indexOf(this);
  50118. if (index >= 0) {
  50119. camera.customRenderTargets.splice(index, 1);
  50120. }
  50121. }
  50122. _super.prototype.dispose.call(this);
  50123. };
  50124. RenderTargetTexture.prototype._rebuild = function () {
  50125. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50126. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50127. }
  50128. if (this._postProcessManager) {
  50129. this._postProcessManager._rebuild();
  50130. }
  50131. };
  50132. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  50133. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  50134. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  50135. return RenderTargetTexture;
  50136. }(BABYLON.Texture));
  50137. BABYLON.RenderTargetTexture = RenderTargetTexture;
  50138. })(BABYLON || (BABYLON = {}));
  50139. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  50140. var BABYLON;
  50141. (function (BABYLON) {
  50142. ;
  50143. var MultiRenderTarget = /** @class */ (function (_super) {
  50144. __extends(MultiRenderTarget, _super);
  50145. function MultiRenderTarget(name, size, count, scene, options) {
  50146. var _this = this;
  50147. options = options || {};
  50148. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  50149. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  50150. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  50151. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  50152. _this._engine = scene.getEngine();
  50153. if (!_this.isSupported) {
  50154. _this.dispose();
  50155. return;
  50156. }
  50157. var types = [];
  50158. var samplingModes = [];
  50159. for (var i = 0; i < count; i++) {
  50160. if (options.types && options.types[i]) {
  50161. types.push(options.types[i]);
  50162. }
  50163. else {
  50164. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  50165. }
  50166. if (options.samplingModes && options.samplingModes[i]) {
  50167. samplingModes.push(options.samplingModes[i]);
  50168. }
  50169. else {
  50170. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50171. }
  50172. }
  50173. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  50174. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  50175. _this._count = count;
  50176. _this._size = size;
  50177. _this._multiRenderTargetOptions = {
  50178. samplingModes: samplingModes,
  50179. generateMipMaps: generateMipMaps,
  50180. generateDepthBuffer: generateDepthBuffer,
  50181. generateStencilBuffer: generateStencilBuffer,
  50182. generateDepthTexture: generateDepthTexture,
  50183. types: types,
  50184. textureCount: count
  50185. };
  50186. _this._createInternalTextures();
  50187. _this._createTextures();
  50188. return _this;
  50189. }
  50190. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  50191. get: function () {
  50192. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  50193. },
  50194. enumerable: true,
  50195. configurable: true
  50196. });
  50197. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  50198. get: function () {
  50199. return this._textures;
  50200. },
  50201. enumerable: true,
  50202. configurable: true
  50203. });
  50204. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  50205. get: function () {
  50206. return this._textures[this._textures.length - 1];
  50207. },
  50208. enumerable: true,
  50209. configurable: true
  50210. });
  50211. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  50212. set: function (wrap) {
  50213. if (this._textures) {
  50214. for (var i = 0; i < this._textures.length; i++) {
  50215. this._textures[i].wrapU = wrap;
  50216. }
  50217. }
  50218. },
  50219. enumerable: true,
  50220. configurable: true
  50221. });
  50222. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  50223. set: function (wrap) {
  50224. if (this._textures) {
  50225. for (var i = 0; i < this._textures.length; i++) {
  50226. this._textures[i].wrapV = wrap;
  50227. }
  50228. }
  50229. },
  50230. enumerable: true,
  50231. configurable: true
  50232. });
  50233. MultiRenderTarget.prototype._rebuild = function () {
  50234. this.releaseInternalTextures();
  50235. this._createInternalTextures();
  50236. for (var i = 0; i < this._internalTextures.length; i++) {
  50237. var texture = this._textures[i];
  50238. texture._texture = this._internalTextures[i];
  50239. }
  50240. // Keeps references to frame buffer and stencil/depth buffer
  50241. this._texture = this._internalTextures[0];
  50242. };
  50243. MultiRenderTarget.prototype._createInternalTextures = function () {
  50244. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  50245. };
  50246. MultiRenderTarget.prototype._createTextures = function () {
  50247. this._textures = [];
  50248. for (var i = 0; i < this._internalTextures.length; i++) {
  50249. var texture = new BABYLON.Texture(null, this.getScene());
  50250. texture._texture = this._internalTextures[i];
  50251. this._textures.push(texture);
  50252. }
  50253. // Keeps references to frame buffer and stencil/depth buffer
  50254. this._texture = this._internalTextures[0];
  50255. };
  50256. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  50257. get: function () {
  50258. return this._samples;
  50259. },
  50260. set: function (value) {
  50261. if (this._samples === value) {
  50262. return;
  50263. }
  50264. for (var i = 0; i < this._internalTextures.length; i++) {
  50265. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  50266. }
  50267. },
  50268. enumerable: true,
  50269. configurable: true
  50270. });
  50271. MultiRenderTarget.prototype.resize = function (size) {
  50272. this.releaseInternalTextures();
  50273. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  50274. this._createInternalTextures();
  50275. };
  50276. MultiRenderTarget.prototype.dispose = function () {
  50277. this.releaseInternalTextures();
  50278. _super.prototype.dispose.call(this);
  50279. };
  50280. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  50281. if (!this._internalTextures) {
  50282. return;
  50283. }
  50284. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  50285. if (this._internalTextures[i] !== undefined) {
  50286. this._internalTextures[i].dispose();
  50287. this._internalTextures.splice(i, 1);
  50288. }
  50289. }
  50290. };
  50291. return MultiRenderTarget;
  50292. }(BABYLON.RenderTargetTexture));
  50293. BABYLON.MultiRenderTarget = MultiRenderTarget;
  50294. })(BABYLON || (BABYLON = {}));
  50295. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  50296. var BABYLON;
  50297. (function (BABYLON) {
  50298. var MirrorTexture = /** @class */ (function (_super) {
  50299. __extends(MirrorTexture, _super);
  50300. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  50301. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50302. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50303. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50304. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  50305. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  50306. _this._transformMatrix = BABYLON.Matrix.Zero();
  50307. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  50308. _this._adaptiveBlurKernel = 0;
  50309. _this._blurKernelX = 0;
  50310. _this._blurKernelY = 0;
  50311. _this._blurRatio = 1.0;
  50312. _this.ignoreCameraViewport = true;
  50313. _this.onBeforeRenderObservable.add(function () {
  50314. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  50315. _this._savedViewMatrix = scene.getViewMatrix();
  50316. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  50317. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  50318. scene.clipPlane = _this.mirrorPlane;
  50319. scene.getEngine().cullBackFaces = false;
  50320. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  50321. });
  50322. _this.onAfterRenderObservable.add(function () {
  50323. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  50324. scene.getEngine().cullBackFaces = true;
  50325. scene._mirroredCameraPosition = null;
  50326. delete scene.clipPlane;
  50327. });
  50328. return _this;
  50329. }
  50330. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  50331. get: function () {
  50332. return this._blurRatio;
  50333. },
  50334. set: function (value) {
  50335. if (this._blurRatio === value) {
  50336. return;
  50337. }
  50338. this._blurRatio = value;
  50339. this._preparePostProcesses();
  50340. },
  50341. enumerable: true,
  50342. configurable: true
  50343. });
  50344. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  50345. set: function (value) {
  50346. this._adaptiveBlurKernel = value;
  50347. this._autoComputeBlurKernel();
  50348. },
  50349. enumerable: true,
  50350. configurable: true
  50351. });
  50352. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  50353. set: function (value) {
  50354. this.blurKernelX = value;
  50355. this.blurKernelY = value;
  50356. },
  50357. enumerable: true,
  50358. configurable: true
  50359. });
  50360. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  50361. get: function () {
  50362. return this._blurKernelX;
  50363. },
  50364. set: function (value) {
  50365. if (this._blurKernelX === value) {
  50366. return;
  50367. }
  50368. this._blurKernelX = value;
  50369. this._preparePostProcesses();
  50370. },
  50371. enumerable: true,
  50372. configurable: true
  50373. });
  50374. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  50375. get: function () {
  50376. return this._blurKernelY;
  50377. },
  50378. set: function (value) {
  50379. if (this._blurKernelY === value) {
  50380. return;
  50381. }
  50382. this._blurKernelY = value;
  50383. this._preparePostProcesses();
  50384. },
  50385. enumerable: true,
  50386. configurable: true
  50387. });
  50388. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  50389. var engine = this.getScene().getEngine();
  50390. var dw = this.getRenderWidth() / engine.getRenderWidth();
  50391. var dh = this.getRenderHeight() / engine.getRenderHeight();
  50392. this.blurKernelX = this._adaptiveBlurKernel * dw;
  50393. this.blurKernelY = this._adaptiveBlurKernel * dh;
  50394. };
  50395. MirrorTexture.prototype._onRatioRescale = function () {
  50396. if (this._sizeRatio) {
  50397. this.resize(this._initialSizeParameter);
  50398. if (!this._adaptiveBlurKernel) {
  50399. this._preparePostProcesses();
  50400. }
  50401. }
  50402. if (this._adaptiveBlurKernel) {
  50403. this._autoComputeBlurKernel();
  50404. }
  50405. };
  50406. MirrorTexture.prototype._preparePostProcesses = function () {
  50407. this.clearPostProcesses(true);
  50408. if (this._blurKernelX && this._blurKernelY) {
  50409. var engine = this.getScene().getEngine();
  50410. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50411. 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);
  50412. this._blurX.autoClear = false;
  50413. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  50414. this._blurX.outputTexture = this._texture;
  50415. }
  50416. else {
  50417. this._blurX.alwaysForcePOT = true;
  50418. }
  50419. 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);
  50420. this._blurY.autoClear = false;
  50421. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50422. this.addPostProcess(this._blurX);
  50423. this.addPostProcess(this._blurY);
  50424. }
  50425. else {
  50426. if (this._blurY) {
  50427. this.removePostProcess(this._blurY);
  50428. this._blurY.dispose();
  50429. this._blurY = null;
  50430. }
  50431. if (this._blurX) {
  50432. this.removePostProcess(this._blurX);
  50433. this._blurX.dispose();
  50434. this._blurX = null;
  50435. }
  50436. }
  50437. };
  50438. MirrorTexture.prototype.clone = function () {
  50439. var scene = this.getScene();
  50440. if (!scene) {
  50441. return this;
  50442. }
  50443. var textureSize = this.getSize();
  50444. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  50445. // Base texture
  50446. newTexture.hasAlpha = this.hasAlpha;
  50447. newTexture.level = this.level;
  50448. // Mirror Texture
  50449. newTexture.mirrorPlane = this.mirrorPlane.clone();
  50450. if (this.renderList) {
  50451. newTexture.renderList = this.renderList.slice(0);
  50452. }
  50453. return newTexture;
  50454. };
  50455. MirrorTexture.prototype.serialize = function () {
  50456. if (!this.name) {
  50457. return null;
  50458. }
  50459. var serializationObject = _super.prototype.serialize.call(this);
  50460. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  50461. return serializationObject;
  50462. };
  50463. return MirrorTexture;
  50464. }(BABYLON.RenderTargetTexture));
  50465. BABYLON.MirrorTexture = MirrorTexture;
  50466. })(BABYLON || (BABYLON = {}));
  50467. //# sourceMappingURL=babylon.mirrorTexture.js.map
  50468. var BABYLON;
  50469. (function (BABYLON) {
  50470. /**
  50471. * Creates a refraction texture used by refraction channel of the standard material.
  50472. * @param name the texture name
  50473. * @param size size of the underlying texture
  50474. * @param scene root scene
  50475. */
  50476. var RefractionTexture = /** @class */ (function (_super) {
  50477. __extends(RefractionTexture, _super);
  50478. function RefractionTexture(name, size, scene, generateMipMaps) {
  50479. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  50480. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  50481. _this.depth = 2.0;
  50482. _this.onBeforeRenderObservable.add(function () {
  50483. scene.clipPlane = _this.refractionPlane;
  50484. });
  50485. _this.onAfterRenderObservable.add(function () {
  50486. delete scene.clipPlane;
  50487. });
  50488. return _this;
  50489. }
  50490. RefractionTexture.prototype.clone = function () {
  50491. var scene = this.getScene();
  50492. if (!scene) {
  50493. return this;
  50494. }
  50495. var textureSize = this.getSize();
  50496. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  50497. // Base texture
  50498. newTexture.hasAlpha = this.hasAlpha;
  50499. newTexture.level = this.level;
  50500. // Refraction Texture
  50501. newTexture.refractionPlane = this.refractionPlane.clone();
  50502. if (this.renderList) {
  50503. newTexture.renderList = this.renderList.slice(0);
  50504. }
  50505. newTexture.depth = this.depth;
  50506. return newTexture;
  50507. };
  50508. RefractionTexture.prototype.serialize = function () {
  50509. if (!this.name) {
  50510. return null;
  50511. }
  50512. var serializationObject = _super.prototype.serialize.call(this);
  50513. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  50514. serializationObject.depth = this.depth;
  50515. return serializationObject;
  50516. };
  50517. return RefractionTexture;
  50518. }(BABYLON.RenderTargetTexture));
  50519. BABYLON.RefractionTexture = RefractionTexture;
  50520. })(BABYLON || (BABYLON = {}));
  50521. //# sourceMappingURL=babylon.refractionTexture.js.map
  50522. var BABYLON;
  50523. (function (BABYLON) {
  50524. var DynamicTexture = /** @class */ (function (_super) {
  50525. __extends(DynamicTexture, _super);
  50526. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  50527. if (scene === void 0) { scene = null; }
  50528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50529. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50530. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  50531. _this.name = name;
  50532. _this._engine = _this.getScene().getEngine();
  50533. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50534. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50535. _this._generateMipMaps = generateMipMaps;
  50536. if (options.getContext) {
  50537. _this._canvas = options;
  50538. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50539. }
  50540. else {
  50541. _this._canvas = document.createElement("canvas");
  50542. if (options.width) {
  50543. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50544. }
  50545. else {
  50546. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  50547. }
  50548. }
  50549. var textureSize = _this.getSize();
  50550. _this._canvas.width = textureSize.width;
  50551. _this._canvas.height = textureSize.height;
  50552. _this._context = _this._canvas.getContext("2d");
  50553. return _this;
  50554. }
  50555. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  50556. get: function () {
  50557. return true;
  50558. },
  50559. enumerable: true,
  50560. configurable: true
  50561. });
  50562. DynamicTexture.prototype._recreate = function (textureSize) {
  50563. this._canvas.width = textureSize.width;
  50564. this._canvas.height = textureSize.height;
  50565. this.releaseInternalTexture();
  50566. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  50567. };
  50568. DynamicTexture.prototype.scale = function (ratio) {
  50569. var textureSize = this.getSize();
  50570. textureSize.width *= ratio;
  50571. textureSize.height *= ratio;
  50572. this._recreate(textureSize);
  50573. };
  50574. DynamicTexture.prototype.scaleTo = function (width, height) {
  50575. var textureSize = this.getSize();
  50576. textureSize.width = width;
  50577. textureSize.height = height;
  50578. this._recreate(textureSize);
  50579. };
  50580. DynamicTexture.prototype.getContext = function () {
  50581. return this._context;
  50582. };
  50583. DynamicTexture.prototype.clear = function () {
  50584. var size = this.getSize();
  50585. this._context.fillRect(0, 0, size.width, size.height);
  50586. };
  50587. DynamicTexture.prototype.update = function (invertY) {
  50588. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50589. };
  50590. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50591. if (update === void 0) { update = true; }
  50592. var size = this.getSize();
  50593. if (clearColor) {
  50594. this._context.fillStyle = clearColor;
  50595. this._context.fillRect(0, 0, size.width, size.height);
  50596. }
  50597. this._context.font = font;
  50598. if (x === null || x === undefined) {
  50599. var textSize = this._context.measureText(text);
  50600. x = (size.width - textSize.width) / 2;
  50601. }
  50602. if (y === null || y === undefined) {
  50603. var fontSize = parseInt((font.replace(/\D/g, '')));
  50604. ;
  50605. y = (size.height / 2) + (fontSize / 3.65);
  50606. }
  50607. this._context.fillStyle = color;
  50608. this._context.fillText(text, x, y);
  50609. if (update) {
  50610. this.update(invertY);
  50611. }
  50612. };
  50613. DynamicTexture.prototype.clone = function () {
  50614. var scene = this.getScene();
  50615. if (!scene) {
  50616. return this;
  50617. }
  50618. var textureSize = this.getSize();
  50619. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50620. // Base texture
  50621. newTexture.hasAlpha = this.hasAlpha;
  50622. newTexture.level = this.level;
  50623. // Dynamic Texture
  50624. newTexture.wrapU = this.wrapU;
  50625. newTexture.wrapV = this.wrapV;
  50626. return newTexture;
  50627. };
  50628. DynamicTexture.prototype._rebuild = function () {
  50629. this.update();
  50630. };
  50631. return DynamicTexture;
  50632. }(BABYLON.Texture));
  50633. BABYLON.DynamicTexture = DynamicTexture;
  50634. })(BABYLON || (BABYLON = {}));
  50635. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50636. var BABYLON;
  50637. (function (BABYLON) {
  50638. var VideoTexture = /** @class */ (function (_super) {
  50639. __extends(VideoTexture, _super);
  50640. /**
  50641. * Creates a video texture.
  50642. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50643. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50644. * @param {BABYLON.Scene} scene is obviously the current scene.
  50645. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50646. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50647. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50648. */
  50649. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50650. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50651. if (invertY === void 0) { invertY = false; }
  50652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50653. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50654. _this._autoLaunch = true;
  50655. var urls = null;
  50656. _this.name = name;
  50657. if (urlsOrVideo instanceof HTMLVideoElement) {
  50658. _this.video = urlsOrVideo;
  50659. }
  50660. else {
  50661. urls = urlsOrVideo;
  50662. _this.video = document.createElement("video");
  50663. _this.video.autoplay = false;
  50664. _this.video.loop = true;
  50665. }
  50666. _this._engine = _this.getScene().getEngine();
  50667. _this._generateMipMaps = generateMipMaps;
  50668. _this._samplingMode = samplingMode;
  50669. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50670. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50671. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50672. }
  50673. else {
  50674. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50675. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50676. _this._generateMipMaps = false;
  50677. }
  50678. if (urls) {
  50679. _this.video.addEventListener("canplay", function () {
  50680. _this._createTexture();
  50681. });
  50682. urls.forEach(function (url) {
  50683. var source = document.createElement("source");
  50684. source.src = url;
  50685. _this.video.appendChild(source);
  50686. });
  50687. }
  50688. else {
  50689. _this._createTexture();
  50690. }
  50691. _this._lastUpdate = BABYLON.Tools.Now;
  50692. return _this;
  50693. }
  50694. VideoTexture.prototype.__setTextureReady = function () {
  50695. if (this._texture) {
  50696. this._texture.isReady = true;
  50697. }
  50698. };
  50699. VideoTexture.prototype._createTexture = function () {
  50700. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  50701. if (this._autoLaunch) {
  50702. this._autoLaunch = false;
  50703. this.video.play();
  50704. }
  50705. this._setTextureReady = this.__setTextureReady.bind(this);
  50706. this.video.addEventListener("playing", this._setTextureReady);
  50707. };
  50708. VideoTexture.prototype._rebuild = function () {
  50709. this.update();
  50710. };
  50711. VideoTexture.prototype.update = function () {
  50712. var now = BABYLON.Tools.Now;
  50713. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  50714. return false;
  50715. }
  50716. this._lastUpdate = now;
  50717. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  50718. return true;
  50719. };
  50720. VideoTexture.prototype.dispose = function () {
  50721. _super.prototype.dispose.call(this);
  50722. this.video.removeEventListener("playing", this._setTextureReady);
  50723. };
  50724. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  50725. var video = document.createElement("video");
  50726. var constraintsDeviceId;
  50727. if (constraints && constraints.deviceId) {
  50728. constraintsDeviceId = {
  50729. exact: constraints.deviceId
  50730. };
  50731. }
  50732. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  50733. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50734. if (navigator.getUserMedia) {
  50735. navigator.getUserMedia({
  50736. video: {
  50737. deviceId: constraintsDeviceId,
  50738. width: {
  50739. min: (constraints && constraints.minWidth) || 256,
  50740. max: (constraints && constraints.maxWidth) || 640
  50741. },
  50742. height: {
  50743. min: (constraints && constraints.minHeight) || 256,
  50744. max: (constraints && constraints.maxHeight) || 480
  50745. }
  50746. }
  50747. }, function (stream) {
  50748. if (video.mozSrcObject !== undefined) {
  50749. video.mozSrcObject = stream;
  50750. }
  50751. else {
  50752. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50753. }
  50754. video.play();
  50755. if (onReady) {
  50756. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50757. }
  50758. }, function (e) {
  50759. BABYLON.Tools.Error(e.name);
  50760. });
  50761. }
  50762. };
  50763. return VideoTexture;
  50764. }(BABYLON.Texture));
  50765. BABYLON.VideoTexture = VideoTexture;
  50766. })(BABYLON || (BABYLON = {}));
  50767. //# sourceMappingURL=babylon.videoTexture.js.map
  50768. var BABYLON;
  50769. (function (BABYLON) {
  50770. var RawTexture = /** @class */ (function (_super) {
  50771. __extends(RawTexture, _super);
  50772. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50773. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50774. if (invertY === void 0) { invertY = false; }
  50775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50776. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50777. _this.format = format;
  50778. _this._engine = scene.getEngine();
  50779. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50780. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50781. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50782. return _this;
  50783. }
  50784. RawTexture.prototype.update = function (data) {
  50785. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50786. };
  50787. // Statics
  50788. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50789. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50790. if (invertY === void 0) { invertY = false; }
  50791. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50792. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50793. };
  50794. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50795. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50796. if (invertY === void 0) { invertY = false; }
  50797. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50798. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50799. };
  50800. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50801. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50802. if (invertY === void 0) { invertY = false; }
  50803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50804. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50805. };
  50806. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50807. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50808. if (invertY === void 0) { invertY = false; }
  50809. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50810. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50811. };
  50812. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50813. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50814. if (invertY === void 0) { invertY = false; }
  50815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50816. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50817. };
  50818. return RawTexture;
  50819. }(BABYLON.Texture));
  50820. BABYLON.RawTexture = RawTexture;
  50821. })(BABYLON || (BABYLON = {}));
  50822. //# sourceMappingURL=babylon.rawTexture.js.map
  50823. var BABYLON;
  50824. (function (BABYLON) {
  50825. var PostProcess = /** @class */ (function () {
  50826. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50827. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50828. if (defines === void 0) { defines = null; }
  50829. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50830. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50831. if (blockCompilation === void 0) { blockCompilation = false; }
  50832. this.name = name;
  50833. this.width = -1;
  50834. this.height = -1;
  50835. this.autoClear = true;
  50836. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50837. /*
  50838. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50839. Can only be used on a single postprocess or on the last one of a chain.
  50840. */
  50841. this.enablePixelPerfectMode = false;
  50842. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50843. this.alwaysForcePOT = false;
  50844. this.samples = 1;
  50845. this.adaptScaleToCurrentViewport = false;
  50846. this._reusable = false;
  50847. this._textures = new BABYLON.SmartArray(2);
  50848. this._currentRenderTextureInd = 0;
  50849. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50850. this._texelSize = BABYLON.Vector2.Zero();
  50851. // Events
  50852. /**
  50853. * An event triggered when the postprocess is activated.
  50854. * @type {BABYLON.Observable}
  50855. */
  50856. this.onActivateObservable = new BABYLON.Observable();
  50857. /**
  50858. * An event triggered when the postprocess changes its size.
  50859. * @type {BABYLON.Observable}
  50860. */
  50861. this.onSizeChangedObservable = new BABYLON.Observable();
  50862. /**
  50863. * An event triggered when the postprocess applies its effect.
  50864. * @type {BABYLON.Observable}
  50865. */
  50866. this.onApplyObservable = new BABYLON.Observable();
  50867. /**
  50868. * An event triggered before rendering the postprocess
  50869. * @type {BABYLON.Observable}
  50870. */
  50871. this.onBeforeRenderObservable = new BABYLON.Observable();
  50872. /**
  50873. * An event triggered after rendering the postprocess
  50874. * @type {BABYLON.Observable}
  50875. */
  50876. this.onAfterRenderObservable = new BABYLON.Observable();
  50877. if (camera != null) {
  50878. this._camera = camera;
  50879. this._scene = camera.getScene();
  50880. camera.attachPostProcess(this);
  50881. this._engine = this._scene.getEngine();
  50882. this._scene.postProcesses.push(this);
  50883. }
  50884. else if (engine) {
  50885. this._engine = engine;
  50886. this._engine.postProcesses.push(this);
  50887. }
  50888. this._options = options;
  50889. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50890. this._reusable = reusable || false;
  50891. this._textureType = textureType;
  50892. this._samplers = samplers || [];
  50893. this._samplers.push("textureSampler");
  50894. this._fragmentUrl = fragmentUrl;
  50895. this._vertexUrl = vertexUrl;
  50896. this._parameters = parameters || [];
  50897. this._parameters.push("scale");
  50898. this._indexParameters = indexParameters;
  50899. if (!blockCompilation) {
  50900. this.updateEffect(defines);
  50901. }
  50902. }
  50903. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50904. set: function (callback) {
  50905. if (this._onActivateObserver) {
  50906. this.onActivateObservable.remove(this._onActivateObserver);
  50907. }
  50908. if (callback) {
  50909. this._onActivateObserver = this.onActivateObservable.add(callback);
  50910. }
  50911. },
  50912. enumerable: true,
  50913. configurable: true
  50914. });
  50915. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50916. set: function (callback) {
  50917. if (this._onSizeChangedObserver) {
  50918. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50919. }
  50920. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50921. },
  50922. enumerable: true,
  50923. configurable: true
  50924. });
  50925. Object.defineProperty(PostProcess.prototype, "onApply", {
  50926. set: function (callback) {
  50927. if (this._onApplyObserver) {
  50928. this.onApplyObservable.remove(this._onApplyObserver);
  50929. }
  50930. this._onApplyObserver = this.onApplyObservable.add(callback);
  50931. },
  50932. enumerable: true,
  50933. configurable: true
  50934. });
  50935. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50936. set: function (callback) {
  50937. if (this._onBeforeRenderObserver) {
  50938. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50939. }
  50940. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50941. },
  50942. enumerable: true,
  50943. configurable: true
  50944. });
  50945. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50946. set: function (callback) {
  50947. if (this._onAfterRenderObserver) {
  50948. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50949. }
  50950. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50951. },
  50952. enumerable: true,
  50953. configurable: true
  50954. });
  50955. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50956. get: function () {
  50957. return this._textures.data[this._currentRenderTextureInd];
  50958. },
  50959. set: function (value) {
  50960. this._forcedOutputTexture = value;
  50961. },
  50962. enumerable: true,
  50963. configurable: true
  50964. });
  50965. PostProcess.prototype.getCamera = function () {
  50966. return this._camera;
  50967. };
  50968. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50969. get: function () {
  50970. if (this._shareOutputWithPostProcess) {
  50971. return this._shareOutputWithPostProcess.texelSize;
  50972. }
  50973. if (this._forcedOutputTexture) {
  50974. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50975. }
  50976. return this._texelSize;
  50977. },
  50978. enumerable: true,
  50979. configurable: true
  50980. });
  50981. PostProcess.prototype.getEngine = function () {
  50982. return this._engine;
  50983. };
  50984. PostProcess.prototype.getEffect = function () {
  50985. return this._effect;
  50986. };
  50987. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50988. this._disposeTextures();
  50989. this._shareOutputWithPostProcess = postProcess;
  50990. return this;
  50991. };
  50992. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50993. if (defines === void 0) { defines = null; }
  50994. if (uniforms === void 0) { uniforms = null; }
  50995. if (samplers === void 0) { samplers = null; }
  50996. 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);
  50997. };
  50998. PostProcess.prototype.isReusable = function () {
  50999. return this._reusable;
  51000. };
  51001. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  51002. PostProcess.prototype.markTextureDirty = function () {
  51003. this.width = -1;
  51004. };
  51005. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  51006. var _this = this;
  51007. if (sourceTexture === void 0) { sourceTexture = null; }
  51008. camera = camera || this._camera;
  51009. var scene = camera.getScene();
  51010. var engine = scene.getEngine();
  51011. var maxSize = engine.getCaps().maxTextureSize;
  51012. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  51013. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  51014. var desiredWidth = (this._options.width || requiredWidth);
  51015. var desiredHeight = this._options.height || requiredHeight;
  51016. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  51017. if (this.adaptScaleToCurrentViewport) {
  51018. var currentViewport = engine.currentViewport;
  51019. if (currentViewport) {
  51020. desiredWidth *= currentViewport.width;
  51021. desiredHeight *= currentViewport.height;
  51022. }
  51023. }
  51024. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  51025. if (!this._options.width) {
  51026. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  51027. }
  51028. if (!this._options.height) {
  51029. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  51030. }
  51031. }
  51032. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  51033. if (this._textures.length > 0) {
  51034. for (var i = 0; i < this._textures.length; i++) {
  51035. this._engine._releaseTexture(this._textures.data[i]);
  51036. }
  51037. this._textures.reset();
  51038. }
  51039. this.width = desiredWidth;
  51040. this.height = desiredHeight;
  51041. var textureSize = { width: this.width, height: this.height };
  51042. var textureOptions = {
  51043. generateMipMaps: false,
  51044. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  51045. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  51046. samplingMode: this.renderTargetSamplingMode,
  51047. type: this._textureType
  51048. };
  51049. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51050. if (this._reusable) {
  51051. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51052. }
  51053. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  51054. this.onSizeChangedObservable.notifyObservers(this);
  51055. }
  51056. this._textures.forEach(function (texture) {
  51057. if (texture.samples !== _this.samples) {
  51058. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  51059. }
  51060. });
  51061. }
  51062. var target;
  51063. if (this._shareOutputWithPostProcess) {
  51064. target = this._shareOutputWithPostProcess.outputTexture;
  51065. }
  51066. else if (this._forcedOutputTexture) {
  51067. target = this._forcedOutputTexture;
  51068. this.width = this._forcedOutputTexture.width;
  51069. this.height = this._forcedOutputTexture.height;
  51070. }
  51071. else {
  51072. target = this.outputTexture;
  51073. }
  51074. if (this.enablePixelPerfectMode) {
  51075. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  51076. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  51077. }
  51078. else {
  51079. this._scaleRatio.copyFromFloats(1, 1);
  51080. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  51081. }
  51082. this.onActivateObservable.notifyObservers(camera);
  51083. // Clear
  51084. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  51085. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  51086. }
  51087. if (this._reusable) {
  51088. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  51089. }
  51090. };
  51091. Object.defineProperty(PostProcess.prototype, "isSupported", {
  51092. get: function () {
  51093. return this._effect.isSupported;
  51094. },
  51095. enumerable: true,
  51096. configurable: true
  51097. });
  51098. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  51099. get: function () {
  51100. if (this._shareOutputWithPostProcess) {
  51101. return this._shareOutputWithPostProcess.aspectRatio;
  51102. }
  51103. if (this._forcedOutputTexture) {
  51104. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  51105. }
  51106. return this.width / this.height;
  51107. },
  51108. enumerable: true,
  51109. configurable: true
  51110. });
  51111. PostProcess.prototype.apply = function () {
  51112. // Check
  51113. if (!this._effect || !this._effect.isReady())
  51114. return null;
  51115. // States
  51116. this._engine.enableEffect(this._effect);
  51117. this._engine.setState(false);
  51118. this._engine.setDepthBuffer(false);
  51119. this._engine.setDepthWrite(false);
  51120. // Alpha
  51121. this._engine.setAlphaMode(this.alphaMode);
  51122. if (this.alphaConstants) {
  51123. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  51124. }
  51125. // Texture
  51126. var source;
  51127. if (this._shareOutputWithPostProcess) {
  51128. source = this._shareOutputWithPostProcess.outputTexture;
  51129. }
  51130. else if (this._forcedOutputTexture) {
  51131. source = this._forcedOutputTexture;
  51132. }
  51133. else {
  51134. source = this.outputTexture;
  51135. }
  51136. this._effect._bindTexture("textureSampler", source);
  51137. // Parameters
  51138. this._effect.setVector2("scale", this._scaleRatio);
  51139. this.onApplyObservable.notifyObservers(this._effect);
  51140. return this._effect;
  51141. };
  51142. PostProcess.prototype._disposeTextures = function () {
  51143. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  51144. return;
  51145. }
  51146. if (this._textures.length > 0) {
  51147. for (var i = 0; i < this._textures.length; i++) {
  51148. this._engine._releaseTexture(this._textures.data[i]);
  51149. }
  51150. }
  51151. this._textures.dispose();
  51152. };
  51153. PostProcess.prototype.dispose = function (camera) {
  51154. camera = camera || this._camera;
  51155. this._disposeTextures();
  51156. if (this._scene) {
  51157. var index_1 = this._scene.postProcesses.indexOf(this);
  51158. if (index_1 !== -1) {
  51159. this._scene.postProcesses.splice(index_1, 1);
  51160. }
  51161. }
  51162. else {
  51163. var index_2 = this._engine.postProcesses.indexOf(this);
  51164. if (index_2 !== -1) {
  51165. this._engine.postProcesses.splice(index_2, 1);
  51166. }
  51167. }
  51168. if (!camera) {
  51169. return;
  51170. }
  51171. camera.detachPostProcess(this);
  51172. var index = camera._postProcesses.indexOf(this);
  51173. if (index === 0 && camera._postProcesses.length > 0) {
  51174. this._camera._postProcesses[0].markTextureDirty();
  51175. }
  51176. this.onActivateObservable.clear();
  51177. this.onAfterRenderObservable.clear();
  51178. this.onApplyObservable.clear();
  51179. this.onBeforeRenderObservable.clear();
  51180. this.onSizeChangedObservable.clear();
  51181. };
  51182. return PostProcess;
  51183. }());
  51184. BABYLON.PostProcess = PostProcess;
  51185. })(BABYLON || (BABYLON = {}));
  51186. //# sourceMappingURL=babylon.postProcess.js.map
  51187. var BABYLON;
  51188. (function (BABYLON) {
  51189. var PassPostProcess = /** @class */ (function (_super) {
  51190. __extends(PassPostProcess, _super);
  51191. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51192. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51193. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  51194. }
  51195. return PassPostProcess;
  51196. }(BABYLON.PostProcess));
  51197. BABYLON.PassPostProcess = PassPostProcess;
  51198. })(BABYLON || (BABYLON = {}));
  51199. //# sourceMappingURL=babylon.passPostProcess.js.map
  51200. var BABYLON;
  51201. (function (BABYLON) {
  51202. var ShadowGenerator = /** @class */ (function () {
  51203. /**
  51204. * Creates a ShadowGenerator object.
  51205. * A ShadowGenerator is the required tool to use the shadows.
  51206. * Each light casting shadows needs to use its own ShadowGenerator.
  51207. * Required parameters :
  51208. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  51209. * - `light`: the light object generating the shadows.
  51210. * - `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.
  51211. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  51212. */
  51213. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  51214. // Members
  51215. this._bias = 0.00005;
  51216. this._blurBoxOffset = 1;
  51217. this._blurScale = 2;
  51218. this._blurKernel = 1;
  51219. this._useKernelBlur = false;
  51220. this._filter = ShadowGenerator.FILTER_NONE;
  51221. this._darkness = 0;
  51222. this._transparencyShadow = false;
  51223. /**
  51224. * Controls the extent to which the shadows fade out at the edge of the frustum
  51225. * Used only by directionals and spots
  51226. */
  51227. this.frustumEdgeFalloff = 0;
  51228. this.forceBackFacesOnly = false;
  51229. this._lightDirection = BABYLON.Vector3.Zero();
  51230. this._viewMatrix = BABYLON.Matrix.Zero();
  51231. this._projectionMatrix = BABYLON.Matrix.Zero();
  51232. this._transformMatrix = BABYLON.Matrix.Zero();
  51233. this._currentFaceIndex = 0;
  51234. this._currentFaceIndexCache = 0;
  51235. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  51236. this._mapSize = mapSize;
  51237. this._light = light;
  51238. this._scene = light.getScene();
  51239. light._shadowGenerator = this;
  51240. // Texture type fallback from float to int if not supported.
  51241. var caps = this._scene.getEngine().getCaps();
  51242. if (!useFullFloatFirst) {
  51243. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51244. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51245. }
  51246. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51247. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51248. }
  51249. else {
  51250. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51251. }
  51252. }
  51253. else {
  51254. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51255. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51256. }
  51257. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51258. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51259. }
  51260. else {
  51261. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51262. }
  51263. }
  51264. this._initializeGenerator();
  51265. }
  51266. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  51267. // Static
  51268. get: function () {
  51269. return ShadowGenerator._FILTER_NONE;
  51270. },
  51271. enumerable: true,
  51272. configurable: true
  51273. });
  51274. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  51275. get: function () {
  51276. return ShadowGenerator._FILTER_POISSONSAMPLING;
  51277. },
  51278. enumerable: true,
  51279. configurable: true
  51280. });
  51281. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  51282. get: function () {
  51283. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  51284. },
  51285. enumerable: true,
  51286. configurable: true
  51287. });
  51288. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  51289. get: function () {
  51290. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  51291. },
  51292. enumerable: true,
  51293. configurable: true
  51294. });
  51295. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  51296. get: function () {
  51297. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51298. },
  51299. enumerable: true,
  51300. configurable: true
  51301. });
  51302. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  51303. get: function () {
  51304. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51305. },
  51306. enumerable: true,
  51307. configurable: true
  51308. });
  51309. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  51310. get: function () {
  51311. return this._bias;
  51312. },
  51313. set: function (bias) {
  51314. this._bias = bias;
  51315. },
  51316. enumerable: true,
  51317. configurable: true
  51318. });
  51319. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  51320. get: function () {
  51321. return this._blurBoxOffset;
  51322. },
  51323. set: function (value) {
  51324. if (this._blurBoxOffset === value) {
  51325. return;
  51326. }
  51327. this._blurBoxOffset = value;
  51328. this._disposeBlurPostProcesses();
  51329. },
  51330. enumerable: true,
  51331. configurable: true
  51332. });
  51333. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  51334. get: function () {
  51335. return this._blurScale;
  51336. },
  51337. set: function (value) {
  51338. if (this._blurScale === value) {
  51339. return;
  51340. }
  51341. this._blurScale = value;
  51342. this._disposeBlurPostProcesses();
  51343. },
  51344. enumerable: true,
  51345. configurable: true
  51346. });
  51347. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  51348. get: function () {
  51349. return this._blurKernel;
  51350. },
  51351. set: function (value) {
  51352. if (this._blurKernel === value) {
  51353. return;
  51354. }
  51355. this._blurKernel = value;
  51356. this._disposeBlurPostProcesses();
  51357. },
  51358. enumerable: true,
  51359. configurable: true
  51360. });
  51361. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  51362. get: function () {
  51363. return this._useKernelBlur;
  51364. },
  51365. set: function (value) {
  51366. if (this._useKernelBlur === value) {
  51367. return;
  51368. }
  51369. this._useKernelBlur = value;
  51370. this._disposeBlurPostProcesses();
  51371. },
  51372. enumerable: true,
  51373. configurable: true
  51374. });
  51375. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  51376. get: function () {
  51377. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  51378. },
  51379. set: function (value) {
  51380. this._depthScale = value;
  51381. },
  51382. enumerable: true,
  51383. configurable: true
  51384. });
  51385. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  51386. get: function () {
  51387. return this._filter;
  51388. },
  51389. set: function (value) {
  51390. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  51391. if (this._light.needCube()) {
  51392. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51393. this.useExponentialShadowMap = true;
  51394. return;
  51395. }
  51396. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51397. this.useCloseExponentialShadowMap = true;
  51398. return;
  51399. }
  51400. }
  51401. if (this._filter === value) {
  51402. return;
  51403. }
  51404. this._filter = value;
  51405. this._disposeBlurPostProcesses();
  51406. this._applyFilterValues();
  51407. this._light._markMeshesAsLightDirty();
  51408. },
  51409. enumerable: true,
  51410. configurable: true
  51411. });
  51412. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  51413. get: function () {
  51414. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  51415. },
  51416. set: function (value) {
  51417. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  51418. return;
  51419. }
  51420. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  51421. },
  51422. enumerable: true,
  51423. configurable: true
  51424. });
  51425. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  51426. get: function () {
  51427. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51428. return this.useExponentialShadowMap;
  51429. },
  51430. set: function (value) {
  51431. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51432. this.useExponentialShadowMap = value;
  51433. },
  51434. enumerable: true,
  51435. configurable: true
  51436. });
  51437. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  51438. get: function () {
  51439. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51440. return this.useBlurExponentialShadowMap;
  51441. },
  51442. set: function (value) {
  51443. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51444. this.useBlurExponentialShadowMap = value;
  51445. },
  51446. enumerable: true,
  51447. configurable: true
  51448. });
  51449. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  51450. get: function () {
  51451. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  51452. },
  51453. set: function (value) {
  51454. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  51455. return;
  51456. }
  51457. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51458. },
  51459. enumerable: true,
  51460. configurable: true
  51461. });
  51462. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  51463. get: function () {
  51464. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  51465. },
  51466. set: function (value) {
  51467. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51468. return;
  51469. }
  51470. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51471. },
  51472. enumerable: true,
  51473. configurable: true
  51474. });
  51475. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  51476. get: function () {
  51477. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51478. },
  51479. set: function (value) {
  51480. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  51481. return;
  51482. }
  51483. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51484. },
  51485. enumerable: true,
  51486. configurable: true
  51487. });
  51488. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  51489. get: function () {
  51490. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51491. },
  51492. set: function (value) {
  51493. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51494. return;
  51495. }
  51496. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51497. },
  51498. enumerable: true,
  51499. configurable: true
  51500. });
  51501. /**
  51502. * Returns the darkness value (float).
  51503. */
  51504. ShadowGenerator.prototype.getDarkness = function () {
  51505. return this._darkness;
  51506. };
  51507. /**
  51508. * Sets the ShadowGenerator darkness value (float <= 1.0).
  51509. * Returns the ShadowGenerator.
  51510. */
  51511. ShadowGenerator.prototype.setDarkness = function (darkness) {
  51512. if (darkness >= 1.0)
  51513. this._darkness = 1.0;
  51514. else if (darkness <= 0.0)
  51515. this._darkness = 0.0;
  51516. else
  51517. this._darkness = darkness;
  51518. return this;
  51519. };
  51520. /**
  51521. * Sets the ability to have transparent shadow (boolean).
  51522. * Returns the ShadowGenerator.
  51523. */
  51524. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  51525. this._transparencyShadow = hasShadow;
  51526. return this;
  51527. };
  51528. /**
  51529. * Returns a RenderTargetTexture object : the shadow map texture.
  51530. */
  51531. ShadowGenerator.prototype.getShadowMap = function () {
  51532. return this._shadowMap;
  51533. };
  51534. /**
  51535. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  51536. */
  51537. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  51538. if (this._shadowMap2) {
  51539. return this._shadowMap2;
  51540. }
  51541. return this._shadowMap;
  51542. };
  51543. /**
  51544. * Helper function to add a mesh and its descendants to the list of shadow casters
  51545. * @param mesh Mesh to add
  51546. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  51547. */
  51548. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  51549. if (includeDescendants === void 0) { includeDescendants = true; }
  51550. if (!this._shadowMap) {
  51551. return this;
  51552. }
  51553. if (!this._shadowMap.renderList) {
  51554. this._shadowMap.renderList = [];
  51555. }
  51556. this._shadowMap.renderList.push(mesh);
  51557. if (includeDescendants) {
  51558. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  51559. }
  51560. return this;
  51561. var _a;
  51562. };
  51563. /**
  51564. * Helper function to remove a mesh and its descendants from the list of shadow casters
  51565. * @param mesh Mesh to remove
  51566. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  51567. */
  51568. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  51569. if (includeDescendants === void 0) { includeDescendants = true; }
  51570. if (!this._shadowMap || !this._shadowMap.renderList) {
  51571. return this;
  51572. }
  51573. var index = this._shadowMap.renderList.indexOf(mesh);
  51574. if (index !== -1) {
  51575. this._shadowMap.renderList.splice(index, 1);
  51576. }
  51577. if (includeDescendants) {
  51578. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  51579. var child = _a[_i];
  51580. this.removeShadowCaster(child);
  51581. }
  51582. }
  51583. return this;
  51584. };
  51585. /**
  51586. * Returns the associated light object.
  51587. */
  51588. ShadowGenerator.prototype.getLight = function () {
  51589. return this._light;
  51590. };
  51591. ShadowGenerator.prototype._initializeGenerator = function () {
  51592. this._light._markMeshesAsLightDirty();
  51593. this._initializeShadowMap();
  51594. };
  51595. ShadowGenerator.prototype._initializeShadowMap = function () {
  51596. var _this = this;
  51597. // Render target
  51598. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51599. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51600. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51601. this._shadowMap.anisotropicFilteringLevel = 1;
  51602. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51603. this._shadowMap.renderParticles = false;
  51604. this._shadowMap.ignoreCameraViewport = true;
  51605. // Record Face Index before render.
  51606. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51607. _this._currentFaceIndex = faceIndex;
  51608. });
  51609. // Custom render function.
  51610. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51611. // Blur if required afer render.
  51612. this._shadowMap.onAfterUnbindObservable.add(function () {
  51613. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51614. return;
  51615. }
  51616. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51617. _this._initializeBlurRTTAndPostProcesses();
  51618. }
  51619. var shadowMap = _this.getShadowMapForRendering();
  51620. if (shadowMap) {
  51621. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51622. }
  51623. });
  51624. // Clear according to the chosen filter.
  51625. this._shadowMap.onClearObservable.add(function (engine) {
  51626. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51627. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51628. }
  51629. else {
  51630. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51631. }
  51632. });
  51633. };
  51634. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51635. var _this = this;
  51636. var engine = this._scene.getEngine();
  51637. var targetSize = this._mapSize / this.blurScale;
  51638. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51639. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51640. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51641. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51642. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51643. }
  51644. if (this.useKernelBlur) {
  51645. 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);
  51646. this._kernelBlurXPostprocess.width = targetSize;
  51647. this._kernelBlurXPostprocess.height = targetSize;
  51648. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51649. effect.setTexture("textureSampler", _this._shadowMap);
  51650. });
  51651. 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);
  51652. this._kernelBlurXPostprocess.autoClear = false;
  51653. this._kernelBlurYPostprocess.autoClear = false;
  51654. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51655. this._kernelBlurXPostprocess.packedFloat = true;
  51656. this._kernelBlurYPostprocess.packedFloat = true;
  51657. }
  51658. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51659. }
  51660. else {
  51661. 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);
  51662. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51663. effect.setFloat2("screenSize", targetSize, targetSize);
  51664. effect.setTexture("textureSampler", _this._shadowMap);
  51665. });
  51666. this._boxBlurPostprocess.autoClear = false;
  51667. this._blurPostProcesses = [this._boxBlurPostprocess];
  51668. }
  51669. };
  51670. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51671. var index;
  51672. var engine = this._scene.getEngine();
  51673. if (depthOnlySubMeshes.length) {
  51674. engine.setColorWrite(false);
  51675. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51676. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  51677. }
  51678. engine.setColorWrite(true);
  51679. }
  51680. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51681. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  51682. }
  51683. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51684. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  51685. }
  51686. if (this._transparencyShadow) {
  51687. for (index = 0; index < transparentSubMeshes.length; index++) {
  51688. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  51689. }
  51690. }
  51691. };
  51692. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  51693. var _this = this;
  51694. var mesh = subMesh.getRenderingMesh();
  51695. var scene = this._scene;
  51696. var engine = scene.getEngine();
  51697. var material = subMesh.getMaterial();
  51698. if (!material) {
  51699. return;
  51700. }
  51701. // Culling
  51702. engine.setState(material.backFaceCulling);
  51703. // Managing instances
  51704. var batch = mesh._getInstancesRenderList(subMesh._id);
  51705. if (batch.mustReturn) {
  51706. return;
  51707. }
  51708. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51709. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  51710. engine.enableEffect(this._effect);
  51711. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51712. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  51713. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  51714. this._effect.setVector3("lightPosition", this.getLight().position);
  51715. if (scene.activeCamera) {
  51716. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  51717. }
  51718. // Alpha test
  51719. if (material && material.needAlphaTesting()) {
  51720. var alphaTexture = material.getAlphaTestTexture();
  51721. if (alphaTexture) {
  51722. this._effect.setTexture("diffuseSampler", alphaTexture);
  51723. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  51724. }
  51725. }
  51726. // Bones
  51727. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51728. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  51729. }
  51730. if (this.forceBackFacesOnly) {
  51731. engine.setState(true, 0, false, true);
  51732. }
  51733. // Draw
  51734. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51735. if (this.forceBackFacesOnly) {
  51736. engine.setState(true, 0, false, false);
  51737. }
  51738. }
  51739. else {
  51740. // Need to reset refresh rate of the shadowMap
  51741. if (this._shadowMap) {
  51742. this._shadowMap.resetRefreshCounter();
  51743. }
  51744. }
  51745. };
  51746. ShadowGenerator.prototype._applyFilterValues = function () {
  51747. if (!this._shadowMap) {
  51748. return;
  51749. }
  51750. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51751. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51752. }
  51753. else {
  51754. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51755. }
  51756. };
  51757. /**
  51758. * Force shader compilation including textures ready check
  51759. */
  51760. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51761. var _this = this;
  51762. var shadowMap = this.getShadowMap();
  51763. if (!shadowMap) {
  51764. return;
  51765. }
  51766. var subMeshes = new Array();
  51767. var currentIndex = 0;
  51768. var renderList = shadowMap.renderList;
  51769. if (!renderList) {
  51770. return;
  51771. }
  51772. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51773. var mesh = renderList_1[_i];
  51774. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51775. }
  51776. var checkReady = function () {
  51777. if (!_this._scene || !_this._scene.getEngine()) {
  51778. return;
  51779. }
  51780. while (_this.isReady(subMeshes[currentIndex], options ? options.useInstances : false)) {
  51781. currentIndex++;
  51782. if (currentIndex >= subMeshes.length) {
  51783. if (onCompiled) {
  51784. onCompiled(_this);
  51785. }
  51786. return;
  51787. }
  51788. }
  51789. setTimeout(checkReady, 16);
  51790. };
  51791. if (subMeshes.length > 0) {
  51792. checkReady();
  51793. }
  51794. };
  51795. /**
  51796. * Boolean : true when the ShadowGenerator is finally computed.
  51797. */
  51798. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51799. var defines = [];
  51800. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51801. defines.push("#define FLOAT");
  51802. }
  51803. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51804. defines.push("#define ESM");
  51805. }
  51806. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51807. var mesh = subMesh.getMesh();
  51808. var material = subMesh.getMaterial();
  51809. // Alpha test
  51810. if (material && material.needAlphaTesting()) {
  51811. var alphaTexture = material.getAlphaTestTexture();
  51812. if (alphaTexture) {
  51813. defines.push("#define ALPHATEST");
  51814. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51815. attribs.push(BABYLON.VertexBuffer.UVKind);
  51816. defines.push("#define UV1");
  51817. }
  51818. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51819. if (alphaTexture.coordinatesIndex === 1) {
  51820. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51821. defines.push("#define UV2");
  51822. }
  51823. }
  51824. }
  51825. }
  51826. // Bones
  51827. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51828. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51829. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51830. if (mesh.numBoneInfluencers > 4) {
  51831. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51832. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51833. }
  51834. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51835. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51836. }
  51837. else {
  51838. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51839. }
  51840. // Instances
  51841. if (useInstances) {
  51842. defines.push("#define INSTANCES");
  51843. attribs.push("world0");
  51844. attribs.push("world1");
  51845. attribs.push("world2");
  51846. attribs.push("world3");
  51847. }
  51848. // Get correct effect
  51849. var join = defines.join("\n");
  51850. if (this._cachedDefines !== join) {
  51851. this._cachedDefines = join;
  51852. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51853. }
  51854. return this._effect.isReady();
  51855. };
  51856. /**
  51857. * This creates the defines related to the standard BJS materials.
  51858. */
  51859. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51860. var scene = this._scene;
  51861. var light = this._light;
  51862. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51863. return;
  51864. }
  51865. defines["SHADOW" + lightIndex] = true;
  51866. if (this.usePoissonSampling) {
  51867. defines["SHADOWPCF" + lightIndex] = true;
  51868. }
  51869. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51870. defines["SHADOWESM" + lightIndex] = true;
  51871. }
  51872. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51873. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51874. }
  51875. if (light.needCube()) {
  51876. defines["SHADOWCUBE" + lightIndex] = true;
  51877. }
  51878. };
  51879. /**
  51880. * This binds shadow lights related to the standard BJS materials.
  51881. * It implies the unifroms available on the materials are the standard BJS ones.
  51882. */
  51883. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51884. var light = this._light;
  51885. var scene = this._scene;
  51886. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51887. return;
  51888. }
  51889. var camera = scene.activeCamera;
  51890. if (!camera) {
  51891. return;
  51892. }
  51893. var shadowMap = this.getShadowMap();
  51894. if (!shadowMap) {
  51895. return;
  51896. }
  51897. if (!light.needCube()) {
  51898. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51899. }
  51900. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51901. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51902. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51903. };
  51904. // Methods
  51905. /**
  51906. * Returns a Matrix object : the updated transformation matrix.
  51907. */
  51908. ShadowGenerator.prototype.getTransformMatrix = function () {
  51909. var scene = this._scene;
  51910. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51911. return this._transformMatrix;
  51912. }
  51913. this._currentRenderID = scene.getRenderId();
  51914. this._currentFaceIndexCache = this._currentFaceIndex;
  51915. var lightPosition = this._light.position;
  51916. if (this._light.computeTransformedInformation()) {
  51917. lightPosition = this._light.transformedPosition;
  51918. }
  51919. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51920. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51921. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51922. }
  51923. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51924. this._cachedPosition = lightPosition.clone();
  51925. this._cachedDirection = this._lightDirection.clone();
  51926. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51927. var shadowMap = this.getShadowMap();
  51928. if (shadowMap) {
  51929. var renderList = shadowMap.renderList;
  51930. if (renderList) {
  51931. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51932. }
  51933. }
  51934. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51935. }
  51936. return this._transformMatrix;
  51937. };
  51938. ShadowGenerator.prototype.recreateShadowMap = function () {
  51939. var shadowMap = this._shadowMap;
  51940. if (!shadowMap) {
  51941. return;
  51942. }
  51943. // Track render list.
  51944. var renderList = shadowMap.renderList;
  51945. // Clean up existing data.
  51946. this._disposeRTTandPostProcesses();
  51947. // Reinitializes.
  51948. this._initializeGenerator();
  51949. // Reaffect the filter to ensure a correct fallback if necessary.
  51950. this.filter = this.filter;
  51951. // Reaffect the filter.
  51952. this._applyFilterValues();
  51953. // Reaffect Render List.
  51954. this._shadowMap.renderList = renderList;
  51955. };
  51956. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51957. if (this._shadowMap2) {
  51958. this._shadowMap2.dispose();
  51959. this._shadowMap2 = null;
  51960. }
  51961. if (this._downSamplePostprocess) {
  51962. this._downSamplePostprocess.dispose();
  51963. this._downSamplePostprocess = null;
  51964. }
  51965. if (this._boxBlurPostprocess) {
  51966. this._boxBlurPostprocess.dispose();
  51967. this._boxBlurPostprocess = null;
  51968. }
  51969. if (this._kernelBlurXPostprocess) {
  51970. this._kernelBlurXPostprocess.dispose();
  51971. this._kernelBlurXPostprocess = null;
  51972. }
  51973. if (this._kernelBlurYPostprocess) {
  51974. this._kernelBlurYPostprocess.dispose();
  51975. this._kernelBlurYPostprocess = null;
  51976. }
  51977. this._blurPostProcesses = [];
  51978. };
  51979. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51980. if (this._shadowMap) {
  51981. this._shadowMap.dispose();
  51982. this._shadowMap = null;
  51983. }
  51984. this._disposeBlurPostProcesses();
  51985. };
  51986. /**
  51987. * Disposes the ShadowGenerator.
  51988. * Returns nothing.
  51989. */
  51990. ShadowGenerator.prototype.dispose = function () {
  51991. this._disposeRTTandPostProcesses();
  51992. if (this._light) {
  51993. this._light._shadowGenerator = null;
  51994. this._light._markMeshesAsLightDirty();
  51995. }
  51996. };
  51997. /**
  51998. * Serializes the ShadowGenerator and returns a serializationObject.
  51999. */
  52000. ShadowGenerator.prototype.serialize = function () {
  52001. var serializationObject = {};
  52002. var shadowMap = this.getShadowMap();
  52003. if (!shadowMap) {
  52004. return serializationObject;
  52005. }
  52006. serializationObject.lightId = this._light.id;
  52007. serializationObject.mapSize = shadowMap.getRenderSize();
  52008. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  52009. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  52010. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52011. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52012. serializationObject.usePoissonSampling = this.usePoissonSampling;
  52013. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  52014. serializationObject.depthScale = this.depthScale;
  52015. serializationObject.darkness = this.getDarkness();
  52016. serializationObject.blurBoxOffset = this.blurBoxOffset;
  52017. serializationObject.blurKernel = this.blurKernel;
  52018. serializationObject.blurScale = this.blurScale;
  52019. serializationObject.useKernelBlur = this.useKernelBlur;
  52020. serializationObject.transparencyShadow = this._transparencyShadow;
  52021. serializationObject.renderList = [];
  52022. if (shadowMap.renderList) {
  52023. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  52024. var mesh = shadowMap.renderList[meshIndex];
  52025. serializationObject.renderList.push(mesh.id);
  52026. }
  52027. }
  52028. return serializationObject;
  52029. };
  52030. /**
  52031. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  52032. */
  52033. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  52034. //casting to point light, as light is missing the position attr and typescript complains.
  52035. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  52036. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  52037. var shadowMap = shadowGenerator.getShadowMap();
  52038. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  52039. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  52040. meshes.forEach(function (mesh) {
  52041. if (!shadowMap) {
  52042. return;
  52043. }
  52044. if (!shadowMap.renderList) {
  52045. shadowMap.renderList = [];
  52046. }
  52047. shadowMap.renderList.push(mesh);
  52048. });
  52049. }
  52050. if (parsedShadowGenerator.usePoissonSampling) {
  52051. shadowGenerator.usePoissonSampling = true;
  52052. }
  52053. else if (parsedShadowGenerator.useExponentialShadowMap) {
  52054. shadowGenerator.useExponentialShadowMap = true;
  52055. }
  52056. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  52057. shadowGenerator.useBlurExponentialShadowMap = true;
  52058. }
  52059. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  52060. shadowGenerator.useCloseExponentialShadowMap = true;
  52061. }
  52062. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  52063. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  52064. }
  52065. else if (parsedShadowGenerator.useVarianceShadowMap) {
  52066. shadowGenerator.useExponentialShadowMap = true;
  52067. }
  52068. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  52069. shadowGenerator.useBlurExponentialShadowMap = true;
  52070. }
  52071. if (parsedShadowGenerator.depthScale) {
  52072. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  52073. }
  52074. if (parsedShadowGenerator.blurScale) {
  52075. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  52076. }
  52077. if (parsedShadowGenerator.blurBoxOffset) {
  52078. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  52079. }
  52080. if (parsedShadowGenerator.useKernelBlur) {
  52081. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  52082. }
  52083. if (parsedShadowGenerator.blurKernel) {
  52084. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  52085. }
  52086. if (parsedShadowGenerator.bias !== undefined) {
  52087. shadowGenerator.bias = parsedShadowGenerator.bias;
  52088. }
  52089. if (parsedShadowGenerator.darkness) {
  52090. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  52091. }
  52092. if (parsedShadowGenerator.transparencyShadow) {
  52093. shadowGenerator.setTransparencyShadow(true);
  52094. }
  52095. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  52096. return shadowGenerator;
  52097. };
  52098. ShadowGenerator._FILTER_NONE = 0;
  52099. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  52100. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  52101. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  52102. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  52103. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  52104. return ShadowGenerator;
  52105. }());
  52106. BABYLON.ShadowGenerator = ShadowGenerator;
  52107. })(BABYLON || (BABYLON = {}));
  52108. //# sourceMappingURL=babylon.shadowGenerator.js.map
  52109. var BABYLON;
  52110. (function (BABYLON) {
  52111. var DefaultLoadingScreen = /** @class */ (function () {
  52112. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  52113. if (_loadingText === void 0) { _loadingText = ""; }
  52114. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  52115. var _this = this;
  52116. this._renderingCanvas = _renderingCanvas;
  52117. this._loadingText = _loadingText;
  52118. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  52119. // Resize
  52120. this._resizeLoadingUI = function () {
  52121. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  52122. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  52123. if (!_this._loadingDiv) {
  52124. return;
  52125. }
  52126. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  52127. _this._loadingDiv.style.left = canvasRect.left + "px";
  52128. _this._loadingDiv.style.top = canvasRect.top + "px";
  52129. _this._loadingDiv.style.width = canvasRect.width + "px";
  52130. _this._loadingDiv.style.height = canvasRect.height + "px";
  52131. };
  52132. }
  52133. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  52134. if (this._loadingDiv) {
  52135. // Do not add a loading screen if there is already one
  52136. return;
  52137. }
  52138. this._loadingDiv = document.createElement("div");
  52139. this._loadingDiv.id = "babylonjsLoadingDiv";
  52140. this._loadingDiv.style.opacity = "0";
  52141. this._loadingDiv.style.transition = "opacity 1.5s ease";
  52142. this._loadingDiv.style.pointerEvents = "none";
  52143. // Loading text
  52144. this._loadingTextDiv = document.createElement("div");
  52145. this._loadingTextDiv.style.position = "absolute";
  52146. this._loadingTextDiv.style.left = "0";
  52147. this._loadingTextDiv.style.top = "50%";
  52148. this._loadingTextDiv.style.marginTop = "80px";
  52149. this._loadingTextDiv.style.width = "100%";
  52150. this._loadingTextDiv.style.height = "20px";
  52151. this._loadingTextDiv.style.fontFamily = "Arial";
  52152. this._loadingTextDiv.style.fontSize = "14px";
  52153. this._loadingTextDiv.style.color = "white";
  52154. this._loadingTextDiv.style.textAlign = "center";
  52155. this._loadingTextDiv.innerHTML = "Loading";
  52156. this._loadingDiv.appendChild(this._loadingTextDiv);
  52157. //set the predefined text
  52158. this._loadingTextDiv.innerHTML = this._loadingText;
  52159. // Generating keyframes
  52160. var style = document.createElement('style');
  52161. style.type = 'text/css';
  52162. 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 }";
  52163. style.innerHTML = keyFrames;
  52164. document.getElementsByTagName('head')[0].appendChild(style);
  52165. // Loading img
  52166. var imgBack = new Image();
  52167. 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";
  52168. imgBack.style.position = "absolute";
  52169. imgBack.style.left = "50%";
  52170. imgBack.style.top = "50%";
  52171. imgBack.style.marginLeft = "-60px";
  52172. imgBack.style.marginTop = "-60px";
  52173. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  52174. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  52175. imgBack.style.transformOrigin = "50% 50%";
  52176. imgBack.style.webkitTransformOrigin = "50% 50%";
  52177. this._loadingDiv.appendChild(imgBack);
  52178. this._resizeLoadingUI();
  52179. window.addEventListener("resize", this._resizeLoadingUI);
  52180. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52181. document.body.appendChild(this._loadingDiv);
  52182. this._loadingDiv.style.opacity = "1";
  52183. };
  52184. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  52185. var _this = this;
  52186. if (!this._loadingDiv) {
  52187. return;
  52188. }
  52189. var onTransitionEnd = function () {
  52190. if (!_this._loadingDiv) {
  52191. return;
  52192. }
  52193. document.body.removeChild(_this._loadingDiv);
  52194. window.removeEventListener("resize", _this._resizeLoadingUI);
  52195. _this._loadingDiv = null;
  52196. };
  52197. this._loadingDiv.style.opacity = "0";
  52198. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  52199. };
  52200. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  52201. set: function (text) {
  52202. this._loadingText = text;
  52203. if (this._loadingTextDiv) {
  52204. this._loadingTextDiv.innerHTML = this._loadingText;
  52205. }
  52206. },
  52207. enumerable: true,
  52208. configurable: true
  52209. });
  52210. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  52211. get: function () {
  52212. return this._loadingDivBackgroundColor;
  52213. },
  52214. set: function (color) {
  52215. this._loadingDivBackgroundColor = color;
  52216. if (!this._loadingDiv) {
  52217. return;
  52218. }
  52219. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52220. },
  52221. enumerable: true,
  52222. configurable: true
  52223. });
  52224. return DefaultLoadingScreen;
  52225. }());
  52226. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  52227. })(BABYLON || (BABYLON = {}));
  52228. //# sourceMappingURL=babylon.loadingScreen.js.map
  52229. var BABYLON;
  52230. (function (BABYLON) {
  52231. var SceneLoader = /** @class */ (function () {
  52232. function SceneLoader() {
  52233. }
  52234. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  52235. get: function () {
  52236. return 0;
  52237. },
  52238. enumerable: true,
  52239. configurable: true
  52240. });
  52241. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  52242. get: function () {
  52243. return 1;
  52244. },
  52245. enumerable: true,
  52246. configurable: true
  52247. });
  52248. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  52249. get: function () {
  52250. return 2;
  52251. },
  52252. enumerable: true,
  52253. configurable: true
  52254. });
  52255. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  52256. get: function () {
  52257. return 3;
  52258. },
  52259. enumerable: true,
  52260. configurable: true
  52261. });
  52262. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  52263. get: function () {
  52264. return SceneLoader._ForceFullSceneLoadingForIncremental;
  52265. },
  52266. set: function (value) {
  52267. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  52268. },
  52269. enumerable: true,
  52270. configurable: true
  52271. });
  52272. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  52273. get: function () {
  52274. return SceneLoader._ShowLoadingScreen;
  52275. },
  52276. set: function (value) {
  52277. SceneLoader._ShowLoadingScreen = value;
  52278. },
  52279. enumerable: true,
  52280. configurable: true
  52281. });
  52282. Object.defineProperty(SceneLoader, "loggingLevel", {
  52283. get: function () {
  52284. return SceneLoader._loggingLevel;
  52285. },
  52286. set: function (value) {
  52287. SceneLoader._loggingLevel = value;
  52288. },
  52289. enumerable: true,
  52290. configurable: true
  52291. });
  52292. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  52293. get: function () {
  52294. return SceneLoader._CleanBoneMatrixWeights;
  52295. },
  52296. set: function (value) {
  52297. SceneLoader._CleanBoneMatrixWeights = value;
  52298. },
  52299. enumerable: true,
  52300. configurable: true
  52301. });
  52302. SceneLoader._getDefaultPlugin = function () {
  52303. return SceneLoader._registeredPlugins[".babylon"];
  52304. };
  52305. SceneLoader._getPluginForExtension = function (extension) {
  52306. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  52307. if (registeredPlugin) {
  52308. return registeredPlugin;
  52309. }
  52310. return SceneLoader._getDefaultPlugin();
  52311. };
  52312. SceneLoader._getPluginForDirectLoad = function (data) {
  52313. for (var extension in SceneLoader._registeredPlugins) {
  52314. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  52315. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  52316. return SceneLoader._registeredPlugins[extension];
  52317. }
  52318. }
  52319. return SceneLoader._getDefaultPlugin();
  52320. };
  52321. SceneLoader._getPluginForFilename = function (sceneFilename) {
  52322. if (sceneFilename.name) {
  52323. sceneFilename = sceneFilename.name;
  52324. }
  52325. var dotPosition = sceneFilename.lastIndexOf(".");
  52326. var queryStringPosition = sceneFilename.indexOf("?");
  52327. if (queryStringPosition === -1) {
  52328. queryStringPosition = sceneFilename.length;
  52329. }
  52330. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  52331. return SceneLoader._getPluginForExtension(extension);
  52332. };
  52333. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  52334. SceneLoader._getDirectLoad = function (sceneFilename) {
  52335. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  52336. return sceneFilename.substr(5);
  52337. }
  52338. return null;
  52339. };
  52340. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52341. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  52342. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  52343. var plugin = registeredPlugin.plugin;
  52344. var useArrayBuffer = registeredPlugin.isBinary;
  52345. var database;
  52346. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  52347. var dataCallback = function (data) {
  52348. if (scene.isDisposed) {
  52349. onError("Scene has been disposed");
  52350. return;
  52351. }
  52352. scene.database = database;
  52353. try {
  52354. onSuccess(plugin, data);
  52355. }
  52356. catch (e) {
  52357. onError(null, e);
  52358. }
  52359. };
  52360. var manifestChecked = function (success) {
  52361. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  52362. if (request) {
  52363. onError(request.status + " " + request.statusText);
  52364. }
  52365. });
  52366. };
  52367. if (directLoad) {
  52368. dataCallback(directLoad);
  52369. return registeredPlugin.plugin;
  52370. }
  52371. if (rootUrl.indexOf("file:") === -1) {
  52372. if (scene.getEngine().enableOfflineSupport) {
  52373. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  52374. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  52375. }
  52376. else {
  52377. manifestChecked(true);
  52378. }
  52379. }
  52380. else {
  52381. var fileOrString = sceneFilename;
  52382. if (fileOrString.name) {
  52383. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  52384. }
  52385. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  52386. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  52387. }
  52388. else {
  52389. onError("Unable to find file named " + sceneFilename);
  52390. }
  52391. }
  52392. return registeredPlugin.plugin;
  52393. };
  52394. // Public functions
  52395. SceneLoader.GetPluginForExtension = function (extension) {
  52396. return SceneLoader._getPluginForExtension(extension).plugin;
  52397. };
  52398. SceneLoader.RegisterPlugin = function (plugin) {
  52399. if (typeof plugin.extensions === "string") {
  52400. var extension = plugin.extensions;
  52401. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52402. plugin: plugin,
  52403. isBinary: false
  52404. };
  52405. }
  52406. else {
  52407. var extensions = plugin.extensions;
  52408. Object.keys(extensions).forEach(function (extension) {
  52409. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52410. plugin: plugin,
  52411. isBinary: extensions[extension].isBinary
  52412. };
  52413. });
  52414. }
  52415. };
  52416. /**
  52417. * Import meshes into a scene
  52418. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  52419. * @param rootUrl a string that defines the root url for scene and resources
  52420. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52421. * @param scene the instance of BABYLON.Scene to append to
  52422. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  52423. * @param onProgress a callback with a progress event for each file being loaded
  52424. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52425. */
  52426. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52427. if (onSuccess === void 0) { onSuccess = null; }
  52428. if (onProgress === void 0) { onProgress = null; }
  52429. if (onError === void 0) { onError = null; }
  52430. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52431. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52432. return null;
  52433. }
  52434. var loadingToken = {};
  52435. scene._addPendingData(loadingToken);
  52436. var errorHandler = function (message, exception) {
  52437. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52438. if (onError) {
  52439. onError(scene, errorMessage, exception);
  52440. }
  52441. else {
  52442. BABYLON.Tools.Error(errorMessage);
  52443. // should the exception be thrown?
  52444. }
  52445. scene._removePendingData(loadingToken);
  52446. };
  52447. var progressHandler = function (event) {
  52448. if (onProgress) {
  52449. onProgress(event);
  52450. }
  52451. };
  52452. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52453. if (plugin.importMesh) {
  52454. var syncedPlugin = plugin;
  52455. var meshes = new Array();
  52456. var particleSystems = new Array();
  52457. var skeletons = new Array();
  52458. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  52459. return;
  52460. }
  52461. if (onSuccess) {
  52462. // wrap onSuccess with try-catch to know if something went wrong.
  52463. try {
  52464. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52465. onSuccess(meshes, particleSystems, skeletons);
  52466. scene._removePendingData(loadingToken);
  52467. }
  52468. catch (e) {
  52469. var message = 'Error in onSuccess callback.';
  52470. errorHandler(message, e);
  52471. }
  52472. }
  52473. }
  52474. else {
  52475. var asyncedPlugin = plugin;
  52476. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  52477. if (onSuccess) {
  52478. try {
  52479. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52480. onSuccess(meshes, particleSystems, skeletons);
  52481. scene._removePendingData(loadingToken);
  52482. }
  52483. catch (e) {
  52484. var message = 'Error in onSuccess callback.';
  52485. errorHandler(message, e);
  52486. }
  52487. }
  52488. }, progressHandler, errorHandler);
  52489. }
  52490. }, progressHandler, errorHandler, pluginExtension);
  52491. };
  52492. /**
  52493. * Load a scene
  52494. * @param rootUrl a string that defines the root url for scene and resources
  52495. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52496. * @param engine is the instance of BABYLON.Engine to use to create the scene
  52497. * @param onSuccess a callback with the scene when import succeeds
  52498. * @param onProgress a callback with a progress event for each file being loaded
  52499. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52500. */
  52501. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  52502. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  52503. };
  52504. /**
  52505. * Append a scene
  52506. * @param rootUrl a string that defines the root url for scene and resources
  52507. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52508. * @param scene is the instance of BABYLON.Scene to append to
  52509. * @param onSuccess a callback with the scene when import succeeds
  52510. * @param onProgress a callback with a progress event for each file being loaded
  52511. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52512. */
  52513. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52514. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52515. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52516. return null;
  52517. }
  52518. if (SceneLoader.ShowLoadingScreen) {
  52519. scene.getEngine().displayLoadingUI();
  52520. }
  52521. var loadingToken = {};
  52522. scene._addPendingData(loadingToken);
  52523. var errorHandler = function (message, exception) {
  52524. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52525. if (onError) {
  52526. onError(scene, errorMessage, exception);
  52527. }
  52528. else {
  52529. BABYLON.Tools.Error(errorMessage);
  52530. // should the exception be thrown?
  52531. }
  52532. scene._removePendingData(loadingToken);
  52533. scene.getEngine().hideLoadingUI();
  52534. };
  52535. var progressHandler = function (event) {
  52536. if (onProgress) {
  52537. onProgress(event);
  52538. }
  52539. };
  52540. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52541. if (plugin.load) {
  52542. var syncedPlugin = plugin;
  52543. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  52544. return;
  52545. }
  52546. if (onSuccess) {
  52547. try {
  52548. onSuccess(scene);
  52549. }
  52550. catch (e) {
  52551. errorHandler("Error in onSuccess callback", e);
  52552. }
  52553. }
  52554. scene.loadingPluginName = plugin.name;
  52555. scene._removePendingData(loadingToken);
  52556. }
  52557. else {
  52558. var asyncedPlugin = plugin;
  52559. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  52560. if (onSuccess) {
  52561. onSuccess(scene);
  52562. }
  52563. scene.loadingPluginName = plugin.name;
  52564. scene._removePendingData(loadingToken);
  52565. }, progressHandler, errorHandler);
  52566. }
  52567. if (SceneLoader.ShowLoadingScreen) {
  52568. scene.executeWhenReady(function () {
  52569. scene.getEngine().hideLoadingUI();
  52570. });
  52571. }
  52572. }, progressHandler, errorHandler, pluginExtension);
  52573. };
  52574. // Flags
  52575. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  52576. SceneLoader._ShowLoadingScreen = true;
  52577. SceneLoader._CleanBoneMatrixWeights = false;
  52578. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52579. // Members
  52580. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52581. SceneLoader._registeredPlugins = {};
  52582. return SceneLoader;
  52583. }());
  52584. BABYLON.SceneLoader = SceneLoader;
  52585. ;
  52586. })(BABYLON || (BABYLON = {}));
  52587. //# sourceMappingURL=babylon.sceneLoader.js.map
  52588. var BABYLON;
  52589. (function (BABYLON) {
  52590. var Internals;
  52591. (function (Internals) {
  52592. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52593. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52594. var parsedMaterial = parsedData.materials[index];
  52595. if (parsedMaterial.id === id) {
  52596. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52597. }
  52598. }
  52599. return null;
  52600. };
  52601. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52602. for (var i in names) {
  52603. if (mesh.name === names[i]) {
  52604. hierarchyIds.push(mesh.id);
  52605. return true;
  52606. }
  52607. }
  52608. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52609. hierarchyIds.push(mesh.id);
  52610. return true;
  52611. }
  52612. return false;
  52613. };
  52614. var logOperation = function (operation, producer) {
  52615. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52616. };
  52617. BABYLON.SceneLoader.RegisterPlugin({
  52618. name: "babylon.js",
  52619. extensions: ".babylon",
  52620. canDirectLoad: function (data) {
  52621. if (data.indexOf("babylon") !== -1) {
  52622. return true;
  52623. }
  52624. return false;
  52625. },
  52626. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52627. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52628. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52629. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52630. // and avoid problems with multiple concurrent .babylon loads.
  52631. var log = "importMesh has failed JSON parse";
  52632. try {
  52633. var parsedData = JSON.parse(data);
  52634. log = "";
  52635. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52636. if (!meshesNames) {
  52637. meshesNames = null;
  52638. }
  52639. else if (!Array.isArray(meshesNames)) {
  52640. meshesNames = [meshesNames];
  52641. }
  52642. var hierarchyIds = new Array();
  52643. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52644. var loadedSkeletonsIds = [];
  52645. var loadedMaterialsIds = [];
  52646. var index;
  52647. var cache;
  52648. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52649. var parsedMesh = parsedData.meshes[index];
  52650. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52651. if (meshesNames !== null) {
  52652. // Remove found mesh name from list.
  52653. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52654. }
  52655. //Geometry?
  52656. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  52657. //does the file contain geometries?
  52658. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  52659. //find the correct geometry and add it to the scene
  52660. var found = false;
  52661. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  52662. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  52663. return;
  52664. }
  52665. else {
  52666. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  52667. if (parsedGeometryData.id === parsedMesh.geometryId) {
  52668. switch (geometryType) {
  52669. case "boxes":
  52670. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  52671. break;
  52672. case "spheres":
  52673. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  52674. break;
  52675. case "cylinders":
  52676. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  52677. break;
  52678. case "toruses":
  52679. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  52680. break;
  52681. case "grounds":
  52682. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  52683. break;
  52684. case "planes":
  52685. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  52686. break;
  52687. case "torusKnots":
  52688. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  52689. break;
  52690. case "vertexData":
  52691. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  52692. break;
  52693. }
  52694. found = true;
  52695. }
  52696. });
  52697. }
  52698. });
  52699. if (found === false) {
  52700. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  52701. }
  52702. }
  52703. }
  52704. // Material ?
  52705. if (parsedMesh.materialId) {
  52706. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  52707. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52708. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  52709. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  52710. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  52711. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  52712. var subMatId = parsedMultiMaterial.materials[matIndex];
  52713. loadedMaterialsIds.push(subMatId);
  52714. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  52715. log += "\n\tMaterial " + mat.toString(fullDetails);
  52716. }
  52717. loadedMaterialsIds.push(parsedMultiMaterial.id);
  52718. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52719. materialFound = true;
  52720. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  52721. break;
  52722. }
  52723. }
  52724. }
  52725. if (materialFound === false) {
  52726. loadedMaterialsIds.push(parsedMesh.materialId);
  52727. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  52728. if (!mat) {
  52729. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  52730. }
  52731. else {
  52732. log += "\n\tMaterial " + mat.toString(fullDetails);
  52733. }
  52734. }
  52735. }
  52736. // Skeleton ?
  52737. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52738. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  52739. if (skeletonAlreadyLoaded === false) {
  52740. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  52741. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  52742. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  52743. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52744. skeletons.push(skeleton);
  52745. loadedSkeletonsIds.push(parsedSkeleton.id);
  52746. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  52747. }
  52748. }
  52749. }
  52750. }
  52751. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52752. meshes.push(mesh);
  52753. log += "\n\tMesh " + mesh.toString(fullDetails);
  52754. }
  52755. }
  52756. // Connecting parents
  52757. var currentMesh;
  52758. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52759. currentMesh = scene.meshes[index];
  52760. if (currentMesh._waitingParentId) {
  52761. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52762. currentMesh._waitingParentId = null;
  52763. }
  52764. }
  52765. // freeze and compute world matrix application
  52766. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52767. currentMesh = scene.meshes[index];
  52768. if (currentMesh._waitingFreezeWorldMatrix) {
  52769. currentMesh.freezeWorldMatrix();
  52770. currentMesh._waitingFreezeWorldMatrix = null;
  52771. }
  52772. else {
  52773. currentMesh.computeWorldMatrix(true);
  52774. }
  52775. }
  52776. }
  52777. // Particles
  52778. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52779. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52780. var parsedParticleSystem = parsedData.particleSystems[index];
  52781. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52782. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52783. }
  52784. }
  52785. }
  52786. return true;
  52787. }
  52788. catch (err) {
  52789. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52790. if (onError) {
  52791. onError(msg, err);
  52792. }
  52793. else {
  52794. BABYLON.Tools.Log(msg);
  52795. throw err;
  52796. }
  52797. }
  52798. finally {
  52799. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52800. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52801. }
  52802. }
  52803. return false;
  52804. },
  52805. load: function (scene, data, rootUrl, onError) {
  52806. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52807. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52808. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52809. // and avoid problems with multiple concurrent .babylon loads.
  52810. var log = "importScene has failed JSON parse";
  52811. try {
  52812. var parsedData = JSON.parse(data);
  52813. log = "";
  52814. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52815. // Scene
  52816. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52817. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52818. }
  52819. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52820. scene.autoClear = parsedData.autoClear;
  52821. }
  52822. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52823. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52824. }
  52825. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52826. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52827. }
  52828. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52829. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52830. }
  52831. // Fog
  52832. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52833. scene.fogMode = parsedData.fogMode;
  52834. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52835. scene.fogStart = parsedData.fogStart;
  52836. scene.fogEnd = parsedData.fogEnd;
  52837. scene.fogDensity = parsedData.fogDensity;
  52838. log += "\tFog mode for scene: ";
  52839. switch (scene.fogMode) {
  52840. // getters not compiling, so using hardcoded
  52841. case 1:
  52842. log += "exp\n";
  52843. break;
  52844. case 2:
  52845. log += "exp2\n";
  52846. break;
  52847. case 3:
  52848. log += "linear\n";
  52849. break;
  52850. }
  52851. }
  52852. //Physics
  52853. if (parsedData.physicsEnabled) {
  52854. var physicsPlugin;
  52855. if (parsedData.physicsEngine === "cannon") {
  52856. physicsPlugin = new BABYLON.CannonJSPlugin();
  52857. }
  52858. else if (parsedData.physicsEngine === "oimo") {
  52859. physicsPlugin = new BABYLON.OimoJSPlugin();
  52860. }
  52861. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52862. //else - default engine, which is currently oimo
  52863. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52864. scene.enablePhysics(physicsGravity, physicsPlugin);
  52865. }
  52866. // Metadata
  52867. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52868. scene.metadata = parsedData.metadata;
  52869. }
  52870. //collisions, if defined. otherwise, default is true
  52871. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52872. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52873. }
  52874. scene.workerCollisions = !!parsedData.workerCollisions;
  52875. var index;
  52876. var cache;
  52877. // Lights
  52878. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52879. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52880. var parsedLight = parsedData.lights[index];
  52881. var light = BABYLON.Light.Parse(parsedLight, scene);
  52882. if (light) {
  52883. log += (index === 0 ? "\n\tLights:" : "");
  52884. log += "\n\t\t" + light.toString(fullDetails);
  52885. }
  52886. }
  52887. }
  52888. // Animations
  52889. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52890. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52891. var parsedAnimation = parsedData.animations[index];
  52892. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52893. scene.animations.push(animation);
  52894. log += (index === 0 ? "\n\tAnimations:" : "");
  52895. log += "\n\t\t" + animation.toString(fullDetails);
  52896. }
  52897. }
  52898. if (parsedData.autoAnimate) {
  52899. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52900. }
  52901. // Materials
  52902. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52903. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52904. var parsedMaterial = parsedData.materials[index];
  52905. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52906. log += (index === 0 ? "\n\tMaterials:" : "");
  52907. log += "\n\t\t" + mat.toString(fullDetails);
  52908. }
  52909. }
  52910. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52911. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52912. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52913. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52914. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52915. log += "\n\t\t" + mmat.toString(fullDetails);
  52916. }
  52917. }
  52918. // Morph targets
  52919. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52920. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52921. var managerData = _a[_i];
  52922. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52923. }
  52924. }
  52925. // Skeletons
  52926. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52927. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52928. var parsedSkeleton = parsedData.skeletons[index];
  52929. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52930. log += (index === 0 ? "\n\tSkeletons:" : "");
  52931. log += "\n\t\t" + skeleton.toString(fullDetails);
  52932. }
  52933. }
  52934. // Geometries
  52935. var geometries = parsedData.geometries;
  52936. if (geometries !== undefined && geometries !== null) {
  52937. // Boxes
  52938. var boxes = geometries.boxes;
  52939. if (boxes !== undefined && boxes !== null) {
  52940. for (index = 0, cache = boxes.length; index < cache; index++) {
  52941. var parsedBox = boxes[index];
  52942. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52943. }
  52944. }
  52945. // Spheres
  52946. var spheres = geometries.spheres;
  52947. if (spheres !== undefined && spheres !== null) {
  52948. for (index = 0, cache = spheres.length; index < cache; index++) {
  52949. var parsedSphere = spheres[index];
  52950. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52951. }
  52952. }
  52953. // Cylinders
  52954. var cylinders = geometries.cylinders;
  52955. if (cylinders !== undefined && cylinders !== null) {
  52956. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52957. var parsedCylinder = cylinders[index];
  52958. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52959. }
  52960. }
  52961. // Toruses
  52962. var toruses = geometries.toruses;
  52963. if (toruses !== undefined && toruses !== null) {
  52964. for (index = 0, cache = toruses.length; index < cache; index++) {
  52965. var parsedTorus = toruses[index];
  52966. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52967. }
  52968. }
  52969. // Grounds
  52970. var grounds = geometries.grounds;
  52971. if (grounds !== undefined && grounds !== null) {
  52972. for (index = 0, cache = grounds.length; index < cache; index++) {
  52973. var parsedGround = grounds[index];
  52974. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52975. }
  52976. }
  52977. // Planes
  52978. var planes = geometries.planes;
  52979. if (planes !== undefined && planes !== null) {
  52980. for (index = 0, cache = planes.length; index < cache; index++) {
  52981. var parsedPlane = planes[index];
  52982. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52983. }
  52984. }
  52985. // TorusKnots
  52986. var torusKnots = geometries.torusKnots;
  52987. if (torusKnots !== undefined && torusKnots !== null) {
  52988. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52989. var parsedTorusKnot = torusKnots[index];
  52990. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52991. }
  52992. }
  52993. // VertexData
  52994. var vertexData = geometries.vertexData;
  52995. if (vertexData !== undefined && vertexData !== null) {
  52996. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52997. var parsedVertexData = vertexData[index];
  52998. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52999. }
  53000. }
  53001. }
  53002. // Meshes
  53003. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53004. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53005. var parsedMesh = parsedData.meshes[index];
  53006. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53007. log += (index === 0 ? "\n\tMeshes:" : "");
  53008. log += "\n\t\t" + mesh.toString(fullDetails);
  53009. }
  53010. }
  53011. // Cameras
  53012. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  53013. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  53014. var parsedCamera = parsedData.cameras[index];
  53015. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  53016. log += (index === 0 ? "\n\tCameras:" : "");
  53017. log += "\n\t\t" + camera.toString(fullDetails);
  53018. }
  53019. }
  53020. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  53021. scene.setActiveCameraByID(parsedData.activeCameraID);
  53022. }
  53023. // Browsing all the graph to connect the dots
  53024. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  53025. var camera = scene.cameras[index];
  53026. if (camera._waitingParentId) {
  53027. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  53028. camera._waitingParentId = null;
  53029. }
  53030. }
  53031. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53032. var light_1 = scene.lights[index];
  53033. if (light_1 && light_1._waitingParentId) {
  53034. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  53035. light_1._waitingParentId = null;
  53036. }
  53037. }
  53038. // Sounds
  53039. var loadedSounds = [];
  53040. var loadedSound;
  53041. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  53042. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  53043. var parsedSound = parsedData.sounds[index];
  53044. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53045. if (!parsedSound.url)
  53046. parsedSound.url = parsedSound.name;
  53047. if (!loadedSounds[parsedSound.url]) {
  53048. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  53049. loadedSounds[parsedSound.url] = loadedSound;
  53050. }
  53051. else {
  53052. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  53053. }
  53054. }
  53055. else {
  53056. new BABYLON.Sound(parsedSound.name, null, scene);
  53057. }
  53058. }
  53059. }
  53060. loadedSounds = [];
  53061. // Connect parents & children and parse actions
  53062. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53063. var mesh = scene.meshes[index];
  53064. if (mesh._waitingParentId) {
  53065. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  53066. mesh._waitingParentId = null;
  53067. }
  53068. if (mesh._waitingActions) {
  53069. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  53070. mesh._waitingActions = null;
  53071. }
  53072. }
  53073. // freeze world matrix application
  53074. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53075. var currentMesh = scene.meshes[index];
  53076. if (currentMesh._waitingFreezeWorldMatrix) {
  53077. currentMesh.freezeWorldMatrix();
  53078. currentMesh._waitingFreezeWorldMatrix = null;
  53079. }
  53080. else {
  53081. currentMesh.computeWorldMatrix(true);
  53082. }
  53083. }
  53084. // Particles Systems
  53085. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53086. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53087. var parsedParticleSystem = parsedData.particleSystems[index];
  53088. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  53089. }
  53090. }
  53091. // Environment texture
  53092. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  53093. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  53094. if (parsedData.createDefaultSkybox === true) {
  53095. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  53096. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  53097. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  53098. }
  53099. }
  53100. // Lens flares
  53101. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  53102. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  53103. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  53104. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  53105. }
  53106. }
  53107. // Shadows
  53108. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  53109. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  53110. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  53111. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  53112. }
  53113. }
  53114. // Lights exclusions / inclusions
  53115. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53116. var light_2 = scene.lights[index];
  53117. // Excluded check
  53118. if (light_2._excludedMeshesIds.length > 0) {
  53119. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  53120. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  53121. if (excludedMesh) {
  53122. light_2.excludedMeshes.push(excludedMesh);
  53123. }
  53124. }
  53125. light_2._excludedMeshesIds = [];
  53126. }
  53127. // Included check
  53128. if (light_2._includedOnlyMeshesIds.length > 0) {
  53129. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  53130. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  53131. if (includedOnlyMesh) {
  53132. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  53133. }
  53134. }
  53135. light_2._includedOnlyMeshesIds = [];
  53136. }
  53137. }
  53138. // Actions (scene)
  53139. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  53140. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  53141. }
  53142. // Finish
  53143. return true;
  53144. }
  53145. catch (err) {
  53146. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  53147. if (onError) {
  53148. onError(msg, err);
  53149. }
  53150. else {
  53151. BABYLON.Tools.Log(msg);
  53152. throw err;
  53153. }
  53154. }
  53155. finally {
  53156. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53157. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53158. }
  53159. }
  53160. return false;
  53161. }
  53162. });
  53163. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53164. })(BABYLON || (BABYLON = {}));
  53165. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  53166. var BABYLON;
  53167. (function (BABYLON) {
  53168. var FilesInput = /** @class */ (function () {
  53169. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  53170. this.onProcessFileCallback = function () { return true; };
  53171. this._engine = engine;
  53172. this._currentScene = scene;
  53173. this._sceneLoadedCallback = sceneLoadedCallback;
  53174. this._progressCallback = progressCallback;
  53175. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  53176. this._textureLoadingCallback = textureLoadingCallback;
  53177. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  53178. this._onReloadCallback = onReloadCallback;
  53179. this._errorCallback = errorCallback;
  53180. }
  53181. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  53182. var _this = this;
  53183. if (elementToMonitor) {
  53184. this._elementToMonitor = elementToMonitor;
  53185. this._dragEnterHandler = function (e) { _this.drag(e); };
  53186. this._dragOverHandler = function (e) { _this.drag(e); };
  53187. this._dropHandler = function (e) { _this.drop(e); };
  53188. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  53189. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  53190. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  53191. }
  53192. };
  53193. FilesInput.prototype.dispose = function () {
  53194. if (!this._elementToMonitor) {
  53195. return;
  53196. }
  53197. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  53198. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  53199. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  53200. };
  53201. FilesInput.prototype.renderFunction = function () {
  53202. if (this._additionalRenderLoopLogicCallback) {
  53203. this._additionalRenderLoopLogicCallback();
  53204. }
  53205. if (this._currentScene) {
  53206. if (this._textureLoadingCallback) {
  53207. var remaining = this._currentScene.getWaitingItemsCount();
  53208. if (remaining > 0) {
  53209. this._textureLoadingCallback(remaining);
  53210. }
  53211. }
  53212. this._currentScene.render();
  53213. }
  53214. };
  53215. FilesInput.prototype.drag = function (e) {
  53216. e.stopPropagation();
  53217. e.preventDefault();
  53218. };
  53219. FilesInput.prototype.drop = function (eventDrop) {
  53220. eventDrop.stopPropagation();
  53221. eventDrop.preventDefault();
  53222. this.loadFiles(eventDrop);
  53223. };
  53224. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  53225. var _this = this;
  53226. var reader = folder.createReader();
  53227. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  53228. reader.readEntries(function (entries) {
  53229. remaining.count += entries.length;
  53230. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  53231. var entry = entries_1[_i];
  53232. if (entry.isFile) {
  53233. entry.file(function (file) {
  53234. file.correctName = relativePath + file.name;
  53235. files.push(file);
  53236. if (--remaining.count === 0) {
  53237. callback();
  53238. }
  53239. });
  53240. }
  53241. else if (entry.isDirectory) {
  53242. _this._traverseFolder(entry, files, remaining, callback);
  53243. }
  53244. }
  53245. if (--remaining.count) {
  53246. callback();
  53247. }
  53248. });
  53249. };
  53250. FilesInput.prototype._processFiles = function (files) {
  53251. var skippedFiles = 0;
  53252. for (var i = 0; i < files.length; i++) {
  53253. var name = files[i].correctName.toLowerCase();
  53254. var extension = name.split('.').pop();
  53255. if (!this.onProcessFileCallback(files[i], name, extension)) {
  53256. skippedFiles++;
  53257. continue;
  53258. }
  53259. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  53260. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  53261. this._sceneFileToLoad = files[i];
  53262. }
  53263. else {
  53264. FilesInput.FilesToLoad[name] = files[i];
  53265. }
  53266. }
  53267. if (this._onReloadCallback) {
  53268. this._onReloadCallback(this._sceneFileToLoad);
  53269. }
  53270. else if (skippedFiles < files.length) {
  53271. this.reload();
  53272. }
  53273. };
  53274. FilesInput.prototype.loadFiles = function (event) {
  53275. var _this = this;
  53276. if (this._startingProcessingFilesCallback)
  53277. this._startingProcessingFilesCallback();
  53278. // Handling data transfer via drag'n'drop
  53279. if (event && event.dataTransfer && event.dataTransfer.files) {
  53280. this._filesToLoad = event.dataTransfer.files;
  53281. }
  53282. // Handling files from input files
  53283. if (event && event.target && event.target.files) {
  53284. this._filesToLoad = event.target.files;
  53285. }
  53286. if (this._filesToLoad && this._filesToLoad.length > 0) {
  53287. var files_1 = new Array();
  53288. var folders = [];
  53289. var items = event.dataTransfer ? event.dataTransfer.items : null;
  53290. for (var i = 0; i < this._filesToLoad.length; i++) {
  53291. var fileToLoad = this._filesToLoad[i];
  53292. var name_1 = fileToLoad.name.toLowerCase();
  53293. var entry = void 0;
  53294. fileToLoad.correctName = name_1;
  53295. if (items) {
  53296. var item = items[i];
  53297. if (item.getAsEntry) {
  53298. entry = item.getAsEntry();
  53299. }
  53300. else if (item.webkitGetAsEntry) {
  53301. entry = item.webkitGetAsEntry();
  53302. }
  53303. }
  53304. if (!entry) {
  53305. files_1.push(fileToLoad);
  53306. }
  53307. else {
  53308. if (entry.isDirectory) {
  53309. folders.push(entry);
  53310. }
  53311. else {
  53312. files_1.push(fileToLoad);
  53313. }
  53314. }
  53315. }
  53316. if (folders.length === 0) {
  53317. this._processFiles(files_1);
  53318. }
  53319. else {
  53320. var remaining = { count: folders.length };
  53321. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  53322. var folder = folders_1[_i];
  53323. this._traverseFolder(folder, files_1, remaining, function () {
  53324. _this._processFiles(files_1);
  53325. });
  53326. }
  53327. }
  53328. }
  53329. };
  53330. FilesInput.prototype.reload = function () {
  53331. var _this = this;
  53332. // If a ".babylon" file has been provided
  53333. if (this._sceneFileToLoad) {
  53334. if (this._currentScene) {
  53335. if (BABYLON.Tools.errorsCount > 0) {
  53336. BABYLON.Tools.ClearLogCache();
  53337. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  53338. }
  53339. this._engine.stopRenderLoop();
  53340. this._currentScene.dispose();
  53341. }
  53342. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  53343. _this._currentScene = newScene;
  53344. if (_this._sceneLoadedCallback) {
  53345. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  53346. }
  53347. // Wait for textures and shaders to be ready
  53348. _this._currentScene.executeWhenReady(function () {
  53349. _this._engine.runRenderLoop(function () {
  53350. _this.renderFunction();
  53351. });
  53352. });
  53353. }, function (progress) {
  53354. if (_this._progressCallback) {
  53355. _this._progressCallback(progress);
  53356. }
  53357. }, function (scene, message) {
  53358. _this._currentScene = scene;
  53359. if (_this._errorCallback) {
  53360. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  53361. }
  53362. });
  53363. }
  53364. else {
  53365. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  53366. }
  53367. };
  53368. FilesInput.FilesToLoad = {};
  53369. return FilesInput;
  53370. }());
  53371. BABYLON.FilesInput = FilesInput;
  53372. })(BABYLON || (BABYLON = {}));
  53373. //# sourceMappingURL=babylon.filesInput.js.map
  53374. var BABYLON;
  53375. (function (BABYLON) {
  53376. /**
  53377. * This class implement a typical dictionary using a string as key and the generic type T as value.
  53378. * The underlying implementation relies on an associative array to ensure the best performances.
  53379. * The value can be anything including 'null' but except 'undefined'
  53380. */
  53381. var StringDictionary = /** @class */ (function () {
  53382. function StringDictionary() {
  53383. this._count = 0;
  53384. this._data = {};
  53385. }
  53386. /**
  53387. * This will clear this dictionary and copy the content from the 'source' one.
  53388. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  53389. * @param source the dictionary to take the content from and copy to this dictionary
  53390. */
  53391. StringDictionary.prototype.copyFrom = function (source) {
  53392. var _this = this;
  53393. this.clear();
  53394. source.forEach(function (t, v) { return _this.add(t, v); });
  53395. };
  53396. /**
  53397. * Get a value based from its key
  53398. * @param key the given key to get the matching value from
  53399. * @return the value if found, otherwise undefined is returned
  53400. */
  53401. StringDictionary.prototype.get = function (key) {
  53402. var val = this._data[key];
  53403. if (val !== undefined) {
  53404. return val;
  53405. }
  53406. return undefined;
  53407. };
  53408. /**
  53409. * Get a value from its key or add it if it doesn't exist.
  53410. * This method will ensure you that a given key/data will be present in the dictionary.
  53411. * @param key the given key to get the matching value from
  53412. * @param factory the factory that will create the value if the key is not present in the dictionary.
  53413. * The factory will only be invoked if there's no data for the given key.
  53414. * @return the value corresponding to the key.
  53415. */
  53416. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  53417. var val = this.get(key);
  53418. if (val !== undefined) {
  53419. return val;
  53420. }
  53421. val = factory(key);
  53422. if (val) {
  53423. this.add(key, val);
  53424. }
  53425. return val;
  53426. };
  53427. /**
  53428. * Get a value from its key if present in the dictionary otherwise add it
  53429. * @param key the key to get the value from
  53430. * @param val if there's no such key/value pair in the dictionary add it with this value
  53431. * @return the value corresponding to the key
  53432. */
  53433. StringDictionary.prototype.getOrAdd = function (key, val) {
  53434. var curVal = this.get(key);
  53435. if (curVal !== undefined) {
  53436. return curVal;
  53437. }
  53438. this.add(key, val);
  53439. return val;
  53440. };
  53441. /**
  53442. * Check if there's a given key in the dictionary
  53443. * @param key the key to check for
  53444. * @return true if the key is present, false otherwise
  53445. */
  53446. StringDictionary.prototype.contains = function (key) {
  53447. return this._data[key] !== undefined;
  53448. };
  53449. /**
  53450. * Add a new key and its corresponding value
  53451. * @param key the key to add
  53452. * @param value the value corresponding to the key
  53453. * @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
  53454. */
  53455. StringDictionary.prototype.add = function (key, value) {
  53456. if (this._data[key] !== undefined) {
  53457. return false;
  53458. }
  53459. this._data[key] = value;
  53460. ++this._count;
  53461. return true;
  53462. };
  53463. StringDictionary.prototype.set = function (key, value) {
  53464. if (this._data[key] === undefined) {
  53465. return false;
  53466. }
  53467. this._data[key] = value;
  53468. return true;
  53469. };
  53470. /**
  53471. * Get the element of the given key and remove it from the dictionary
  53472. * @param key
  53473. */
  53474. StringDictionary.prototype.getAndRemove = function (key) {
  53475. var val = this.get(key);
  53476. if (val !== undefined) {
  53477. delete this._data[key];
  53478. --this._count;
  53479. return val;
  53480. }
  53481. return null;
  53482. };
  53483. /**
  53484. * Remove a key/value from the dictionary.
  53485. * @param key the key to remove
  53486. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  53487. */
  53488. StringDictionary.prototype.remove = function (key) {
  53489. if (this.contains(key)) {
  53490. delete this._data[key];
  53491. --this._count;
  53492. return true;
  53493. }
  53494. return false;
  53495. };
  53496. /**
  53497. * Clear the whole content of the dictionary
  53498. */
  53499. StringDictionary.prototype.clear = function () {
  53500. this._data = {};
  53501. this._count = 0;
  53502. };
  53503. Object.defineProperty(StringDictionary.prototype, "count", {
  53504. get: function () {
  53505. return this._count;
  53506. },
  53507. enumerable: true,
  53508. configurable: true
  53509. });
  53510. /**
  53511. * Execute a callback on each key/val of the dictionary.
  53512. * Note that you can remove any element in this dictionary in the callback implementation
  53513. * @param callback the callback to execute on a given key/value pair
  53514. */
  53515. StringDictionary.prototype.forEach = function (callback) {
  53516. for (var cur in this._data) {
  53517. var val = this._data[cur];
  53518. callback(cur, val);
  53519. }
  53520. };
  53521. /**
  53522. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  53523. * If the callback returns null or undefined the method will iterate to the next key/value pair
  53524. * Note that you can remove any element in this dictionary in the callback implementation
  53525. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  53526. */
  53527. StringDictionary.prototype.first = function (callback) {
  53528. for (var cur in this._data) {
  53529. var val = this._data[cur];
  53530. var res = callback(cur, val);
  53531. if (res) {
  53532. return res;
  53533. }
  53534. }
  53535. return null;
  53536. };
  53537. return StringDictionary;
  53538. }());
  53539. BABYLON.StringDictionary = StringDictionary;
  53540. })(BABYLON || (BABYLON = {}));
  53541. //# sourceMappingURL=babylon.stringDictionary.js.map
  53542. var BABYLON;
  53543. (function (BABYLON) {
  53544. var Tags = /** @class */ (function () {
  53545. function Tags() {
  53546. }
  53547. Tags.EnableFor = function (obj) {
  53548. obj._tags = obj._tags || {};
  53549. obj.hasTags = function () {
  53550. return Tags.HasTags(obj);
  53551. };
  53552. obj.addTags = function (tagsString) {
  53553. return Tags.AddTagsTo(obj, tagsString);
  53554. };
  53555. obj.removeTags = function (tagsString) {
  53556. return Tags.RemoveTagsFrom(obj, tagsString);
  53557. };
  53558. obj.matchesTagsQuery = function (tagsQuery) {
  53559. return Tags.MatchesQuery(obj, tagsQuery);
  53560. };
  53561. };
  53562. Tags.DisableFor = function (obj) {
  53563. delete obj._tags;
  53564. delete obj.hasTags;
  53565. delete obj.addTags;
  53566. delete obj.removeTags;
  53567. delete obj.matchesTagsQuery;
  53568. };
  53569. Tags.HasTags = function (obj) {
  53570. if (!obj._tags) {
  53571. return false;
  53572. }
  53573. return !BABYLON.Tools.IsEmpty(obj._tags);
  53574. };
  53575. Tags.GetTags = function (obj, asString) {
  53576. if (asString === void 0) { asString = true; }
  53577. if (!obj._tags) {
  53578. return null;
  53579. }
  53580. if (asString) {
  53581. var tagsArray = [];
  53582. for (var tag in obj._tags) {
  53583. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53584. tagsArray.push(tag);
  53585. }
  53586. }
  53587. return tagsArray.join(" ");
  53588. }
  53589. else {
  53590. return obj._tags;
  53591. }
  53592. };
  53593. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53594. // a tag cannot start with '||', '&&', and '!'
  53595. // it cannot contain whitespaces
  53596. Tags.AddTagsTo = function (obj, tagsString) {
  53597. if (!tagsString) {
  53598. return;
  53599. }
  53600. if (typeof tagsString !== "string") {
  53601. return;
  53602. }
  53603. var tags = tagsString.split(" ");
  53604. tags.forEach(function (tag, index, array) {
  53605. Tags._AddTagTo(obj, tag);
  53606. });
  53607. };
  53608. Tags._AddTagTo = function (obj, tag) {
  53609. tag = tag.trim();
  53610. if (tag === "" || tag === "true" || tag === "false") {
  53611. return;
  53612. }
  53613. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53614. return;
  53615. }
  53616. Tags.EnableFor(obj);
  53617. obj._tags[tag] = true;
  53618. };
  53619. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53620. if (!Tags.HasTags(obj)) {
  53621. return;
  53622. }
  53623. var tags = tagsString.split(" ");
  53624. for (var t in tags) {
  53625. Tags._RemoveTagFrom(obj, tags[t]);
  53626. }
  53627. };
  53628. Tags._RemoveTagFrom = function (obj, tag) {
  53629. delete obj._tags[tag];
  53630. };
  53631. Tags.MatchesQuery = function (obj, tagsQuery) {
  53632. if (tagsQuery === undefined) {
  53633. return true;
  53634. }
  53635. if (tagsQuery === "") {
  53636. return Tags.HasTags(obj);
  53637. }
  53638. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53639. };
  53640. return Tags;
  53641. }());
  53642. BABYLON.Tags = Tags;
  53643. })(BABYLON || (BABYLON = {}));
  53644. //# sourceMappingURL=babylon.tags.js.map
  53645. var BABYLON;
  53646. (function (BABYLON) {
  53647. var Internals;
  53648. (function (Internals) {
  53649. var AndOrNotEvaluator = /** @class */ (function () {
  53650. function AndOrNotEvaluator() {
  53651. }
  53652. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  53653. if (!query.match(/\([^\(\)]*\)/g)) {
  53654. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  53655. }
  53656. else {
  53657. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  53658. // remove parenthesis
  53659. r = r.slice(1, r.length - 1);
  53660. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  53661. });
  53662. }
  53663. if (query === "true") {
  53664. return true;
  53665. }
  53666. if (query === "false") {
  53667. return false;
  53668. }
  53669. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  53670. };
  53671. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  53672. evaluateCallback = evaluateCallback || (function (r) {
  53673. return r === "true" ? true : false;
  53674. });
  53675. var result;
  53676. var or = parenthesisContent.split("||");
  53677. for (var i in or) {
  53678. if (or.hasOwnProperty(i)) {
  53679. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  53680. var and = ori.split("&&");
  53681. if (and.length > 1) {
  53682. for (var j = 0; j < and.length; ++j) {
  53683. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  53684. if (andj !== "true" && andj !== "false") {
  53685. if (andj[0] === "!") {
  53686. result = !evaluateCallback(andj.substring(1));
  53687. }
  53688. else {
  53689. result = evaluateCallback(andj);
  53690. }
  53691. }
  53692. else {
  53693. result = andj === "true" ? true : false;
  53694. }
  53695. if (!result) {
  53696. ori = "false";
  53697. break;
  53698. }
  53699. }
  53700. }
  53701. if (result || ori === "true") {
  53702. result = true;
  53703. break;
  53704. }
  53705. // result equals false (or undefined)
  53706. if (ori !== "true" && ori !== "false") {
  53707. if (ori[0] === "!") {
  53708. result = !evaluateCallback(ori.substring(1));
  53709. }
  53710. else {
  53711. result = evaluateCallback(ori);
  53712. }
  53713. }
  53714. else {
  53715. result = ori === "true" ? true : false;
  53716. }
  53717. }
  53718. }
  53719. // the whole parenthesis scope is replaced by 'true' or 'false'
  53720. return result ? "true" : "false";
  53721. };
  53722. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  53723. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  53724. // remove whitespaces
  53725. r = r.replace(/[\s]/g, function () { return ""; });
  53726. return r.length % 2 ? "!" : "";
  53727. });
  53728. booleanString = booleanString.trim();
  53729. if (booleanString === "!true") {
  53730. booleanString = "false";
  53731. }
  53732. else if (booleanString === "!false") {
  53733. booleanString = "true";
  53734. }
  53735. return booleanString;
  53736. };
  53737. return AndOrNotEvaluator;
  53738. }());
  53739. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  53740. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53741. })(BABYLON || (BABYLON = {}));
  53742. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  53743. var BABYLON;
  53744. (function (BABYLON) {
  53745. var Database = /** @class */ (function () {
  53746. function Database(urlToScene, callbackManifestChecked) {
  53747. // Handling various flavors of prefixed version of IndexedDB
  53748. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53749. this.callbackManifestChecked = callbackManifestChecked;
  53750. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53751. this.db = null;
  53752. this._enableSceneOffline = false;
  53753. this._enableTexturesOffline = false;
  53754. this.manifestVersionFound = 0;
  53755. this.mustUpdateRessources = false;
  53756. this.hasReachedQuota = false;
  53757. if (!Database.IDBStorageEnabled) {
  53758. this.callbackManifestChecked(true);
  53759. }
  53760. else {
  53761. this.checkManifestFile();
  53762. }
  53763. }
  53764. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53765. get: function () {
  53766. return this._enableSceneOffline;
  53767. },
  53768. enumerable: true,
  53769. configurable: true
  53770. });
  53771. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53772. get: function () {
  53773. return this._enableTexturesOffline;
  53774. },
  53775. enumerable: true,
  53776. configurable: true
  53777. });
  53778. Database.prototype.checkManifestFile = function () {
  53779. var _this = this;
  53780. var noManifestFile = function () {
  53781. _this._enableSceneOffline = false;
  53782. _this._enableTexturesOffline = false;
  53783. _this.callbackManifestChecked(false);
  53784. };
  53785. var timeStampUsed = false;
  53786. var manifestURL = this.currentSceneUrl + ".manifest";
  53787. var xhr = new XMLHttpRequest();
  53788. if (navigator.onLine) {
  53789. // Adding a timestamp to by-pass browsers' cache
  53790. timeStampUsed = true;
  53791. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53792. }
  53793. xhr.open("GET", manifestURL, true);
  53794. xhr.addEventListener("load", function () {
  53795. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53796. try {
  53797. var manifestFile = JSON.parse(xhr.response);
  53798. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53799. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53800. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53801. _this.manifestVersionFound = manifestFile.version;
  53802. }
  53803. if (_this.callbackManifestChecked) {
  53804. _this.callbackManifestChecked(true);
  53805. }
  53806. }
  53807. catch (ex) {
  53808. noManifestFile();
  53809. }
  53810. }
  53811. else {
  53812. noManifestFile();
  53813. }
  53814. }, false);
  53815. xhr.addEventListener("error", function (event) {
  53816. if (timeStampUsed) {
  53817. timeStampUsed = false;
  53818. // Let's retry without the timeStamp
  53819. // It could fail when coupled with HTML5 Offline API
  53820. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53821. xhr.open("GET", retryManifestURL, true);
  53822. xhr.send();
  53823. }
  53824. else {
  53825. noManifestFile();
  53826. }
  53827. }, false);
  53828. try {
  53829. xhr.send();
  53830. }
  53831. catch (ex) {
  53832. BABYLON.Tools.Error("Error on XHR send request.");
  53833. this.callbackManifestChecked(false);
  53834. }
  53835. };
  53836. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53837. var _this = this;
  53838. var handleError = function () {
  53839. _this.isSupported = false;
  53840. if (errorCallback)
  53841. errorCallback();
  53842. };
  53843. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53844. // Your browser doesn't support IndexedDB
  53845. this.isSupported = false;
  53846. if (errorCallback)
  53847. errorCallback();
  53848. }
  53849. else {
  53850. // If the DB hasn't been opened or created yet
  53851. if (!this.db) {
  53852. this.hasReachedQuota = false;
  53853. this.isSupported = true;
  53854. var request = this.idbFactory.open("babylonjs", 1);
  53855. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53856. request.onerror = function (event) {
  53857. handleError();
  53858. };
  53859. // executes when a version change transaction cannot complete due to other active transactions
  53860. request.onblocked = function (event) {
  53861. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53862. handleError();
  53863. };
  53864. // DB has been opened successfully
  53865. request.onsuccess = function (event) {
  53866. _this.db = request.result;
  53867. successCallback();
  53868. };
  53869. // Initialization of the DB. Creating Scenes & Textures stores
  53870. request.onupgradeneeded = function (event) {
  53871. _this.db = (event.target).result;
  53872. if (_this.db) {
  53873. try {
  53874. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53875. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53876. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53877. }
  53878. catch (ex) {
  53879. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53880. handleError();
  53881. }
  53882. }
  53883. };
  53884. }
  53885. else {
  53886. if (successCallback)
  53887. successCallback();
  53888. }
  53889. }
  53890. };
  53891. Database.prototype.loadImageFromDB = function (url, image) {
  53892. var _this = this;
  53893. var completeURL = Database.ReturnFullUrlLocation(url);
  53894. var saveAndLoadImage = function () {
  53895. if (!_this.hasReachedQuota && _this.db !== null) {
  53896. // the texture is not yet in the DB, let's try to save it
  53897. _this._saveImageIntoDBAsync(completeURL, image);
  53898. }
  53899. else {
  53900. image.src = url;
  53901. }
  53902. };
  53903. if (!this.mustUpdateRessources) {
  53904. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53905. }
  53906. else {
  53907. saveAndLoadImage();
  53908. }
  53909. };
  53910. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53911. if (this.isSupported && this.db !== null) {
  53912. var texture;
  53913. var transaction = this.db.transaction(["textures"]);
  53914. transaction.onabort = function (event) {
  53915. image.src = url;
  53916. };
  53917. transaction.oncomplete = function (event) {
  53918. var blobTextureURL;
  53919. if (texture) {
  53920. var URL = window.URL || window.webkitURL;
  53921. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53922. image.onerror = function () {
  53923. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53924. image.src = url;
  53925. };
  53926. image.src = blobTextureURL;
  53927. }
  53928. else {
  53929. notInDBCallback();
  53930. }
  53931. };
  53932. var getRequest = transaction.objectStore("textures").get(url);
  53933. getRequest.onsuccess = function (event) {
  53934. texture = (event.target).result;
  53935. };
  53936. getRequest.onerror = function (event) {
  53937. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53938. image.src = url;
  53939. };
  53940. }
  53941. else {
  53942. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53943. image.src = url;
  53944. }
  53945. };
  53946. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53947. var _this = this;
  53948. if (this.isSupported) {
  53949. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53950. var generateBlobUrl = function () {
  53951. var blobTextureURL;
  53952. if (blob) {
  53953. var URL = window.URL || window.webkitURL;
  53954. try {
  53955. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53956. }
  53957. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53958. catch (ex) {
  53959. blobTextureURL = URL.createObjectURL(blob);
  53960. }
  53961. }
  53962. if (blobTextureURL) {
  53963. image.src = blobTextureURL;
  53964. }
  53965. };
  53966. if (Database.IsUASupportingBlobStorage) {
  53967. var xhr = new XMLHttpRequest(), blob;
  53968. xhr.open("GET", url, true);
  53969. xhr.responseType = "blob";
  53970. xhr.addEventListener("load", function () {
  53971. if (xhr.status === 200 && _this.db) {
  53972. // Blob as response (XHR2)
  53973. blob = xhr.response;
  53974. var transaction = _this.db.transaction(["textures"], "readwrite");
  53975. // the transaction could abort because of a QuotaExceededError error
  53976. transaction.onabort = function (event) {
  53977. try {
  53978. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53979. var srcElement = (event.srcElement || event.target);
  53980. var error = srcElement.error;
  53981. if (error && error.name === "QuotaExceededError") {
  53982. _this.hasReachedQuota = true;
  53983. }
  53984. }
  53985. catch (ex) { }
  53986. generateBlobUrl();
  53987. };
  53988. transaction.oncomplete = function (event) {
  53989. generateBlobUrl();
  53990. };
  53991. var newTexture = { textureUrl: url, data: blob };
  53992. try {
  53993. // Put the blob into the dabase
  53994. var addRequest = transaction.objectStore("textures").put(newTexture);
  53995. addRequest.onsuccess = function (event) {
  53996. };
  53997. addRequest.onerror = function (event) {
  53998. generateBlobUrl();
  53999. };
  54000. }
  54001. catch (ex) {
  54002. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  54003. if (ex.code === 25) {
  54004. Database.IsUASupportingBlobStorage = false;
  54005. }
  54006. image.src = url;
  54007. }
  54008. }
  54009. else {
  54010. image.src = url;
  54011. }
  54012. }, false);
  54013. xhr.addEventListener("error", function (event) {
  54014. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  54015. image.src = url;
  54016. }, false);
  54017. xhr.send();
  54018. }
  54019. else {
  54020. image.src = url;
  54021. }
  54022. }
  54023. else {
  54024. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54025. image.src = url;
  54026. }
  54027. };
  54028. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  54029. var _this = this;
  54030. var updateVersion = function () {
  54031. // the version is not yet in the DB or we need to update it
  54032. _this._saveVersionIntoDBAsync(url, versionLoaded);
  54033. };
  54034. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  54035. };
  54036. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  54037. var _this = this;
  54038. if (this.isSupported && this.db) {
  54039. var version;
  54040. try {
  54041. var transaction = this.db.transaction(["versions"]);
  54042. transaction.oncomplete = function (event) {
  54043. if (version) {
  54044. // If the version in the JSON file is > than the version in DB
  54045. if (_this.manifestVersionFound > version.data) {
  54046. _this.mustUpdateRessources = true;
  54047. updateInDBCallback();
  54048. }
  54049. else {
  54050. callback(version.data);
  54051. }
  54052. }
  54053. else {
  54054. _this.mustUpdateRessources = true;
  54055. updateInDBCallback();
  54056. }
  54057. };
  54058. transaction.onabort = function (event) {
  54059. callback(-1);
  54060. };
  54061. var getRequest = transaction.objectStore("versions").get(url);
  54062. getRequest.onsuccess = function (event) {
  54063. version = (event.target).result;
  54064. };
  54065. getRequest.onerror = function (event) {
  54066. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  54067. callback(-1);
  54068. };
  54069. }
  54070. catch (ex) {
  54071. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  54072. callback(-1);
  54073. }
  54074. }
  54075. else {
  54076. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54077. callback(-1);
  54078. }
  54079. };
  54080. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  54081. var _this = this;
  54082. if (this.isSupported && !this.hasReachedQuota && this.db) {
  54083. try {
  54084. // Open a transaction to the database
  54085. var transaction = this.db.transaction(["versions"], "readwrite");
  54086. // the transaction could abort because of a QuotaExceededError error
  54087. transaction.onabort = function (event) {
  54088. try {
  54089. var error = event.srcElement['error'];
  54090. if (error && error.name === "QuotaExceededError") {
  54091. _this.hasReachedQuota = true;
  54092. }
  54093. }
  54094. catch (ex) { }
  54095. callback(-1);
  54096. };
  54097. transaction.oncomplete = function (event) {
  54098. callback(_this.manifestVersionFound);
  54099. };
  54100. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  54101. // Put the scene into the database
  54102. var addRequest = transaction.objectStore("versions").put(newVersion);
  54103. addRequest.onsuccess = function (event) {
  54104. };
  54105. addRequest.onerror = function (event) {
  54106. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  54107. };
  54108. }
  54109. catch (ex) {
  54110. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  54111. callback(-1);
  54112. }
  54113. }
  54114. else {
  54115. callback(-1);
  54116. }
  54117. };
  54118. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  54119. var _this = this;
  54120. var completeUrl = Database.ReturnFullUrlLocation(url);
  54121. var saveAndLoadFile = function () {
  54122. // the scene is not yet in the DB, let's try to save it
  54123. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  54124. };
  54125. this._checkVersionFromDB(completeUrl, function (version) {
  54126. if (version !== -1) {
  54127. if (!_this.mustUpdateRessources) {
  54128. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  54129. }
  54130. else {
  54131. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  54132. }
  54133. }
  54134. else {
  54135. if (errorCallback) {
  54136. errorCallback();
  54137. }
  54138. }
  54139. });
  54140. };
  54141. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  54142. if (this.isSupported && this.db) {
  54143. var targetStore;
  54144. if (url.indexOf(".babylon") !== -1) {
  54145. targetStore = "scenes";
  54146. }
  54147. else {
  54148. targetStore = "textures";
  54149. }
  54150. var file;
  54151. var transaction = this.db.transaction([targetStore]);
  54152. transaction.oncomplete = function (event) {
  54153. if (file) {
  54154. callback(file.data);
  54155. }
  54156. else {
  54157. notInDBCallback();
  54158. }
  54159. };
  54160. transaction.onabort = function (event) {
  54161. notInDBCallback();
  54162. };
  54163. var getRequest = transaction.objectStore(targetStore).get(url);
  54164. getRequest.onsuccess = function (event) {
  54165. file = (event.target).result;
  54166. };
  54167. getRequest.onerror = function (event) {
  54168. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  54169. notInDBCallback();
  54170. };
  54171. }
  54172. else {
  54173. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54174. callback();
  54175. }
  54176. };
  54177. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  54178. var _this = this;
  54179. if (this.isSupported) {
  54180. var targetStore;
  54181. if (url.indexOf(".babylon") !== -1) {
  54182. targetStore = "scenes";
  54183. }
  54184. else {
  54185. targetStore = "textures";
  54186. }
  54187. // Create XHR
  54188. var xhr = new XMLHttpRequest();
  54189. var fileData;
  54190. xhr.open("GET", url, true);
  54191. if (useArrayBuffer) {
  54192. xhr.responseType = "arraybuffer";
  54193. }
  54194. if (progressCallback) {
  54195. xhr.onprogress = progressCallback;
  54196. }
  54197. xhr.addEventListener("load", function () {
  54198. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  54199. // Blob as response (XHR2)
  54200. //fileData = xhr.responseText;
  54201. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  54202. if (!_this.hasReachedQuota && _this.db) {
  54203. // Open a transaction to the database
  54204. var transaction = _this.db.transaction([targetStore], "readwrite");
  54205. // the transaction could abort because of a QuotaExceededError error
  54206. transaction.onabort = function (event) {
  54207. try {
  54208. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54209. var error = event.srcElement['error'];
  54210. if (error && error.name === "QuotaExceededError") {
  54211. _this.hasReachedQuota = true;
  54212. }
  54213. }
  54214. catch (ex) { }
  54215. callback(fileData);
  54216. };
  54217. transaction.oncomplete = function (event) {
  54218. callback(fileData);
  54219. };
  54220. var newFile;
  54221. if (targetStore === "scenes") {
  54222. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  54223. }
  54224. else {
  54225. newFile = { textureUrl: url, data: fileData };
  54226. }
  54227. try {
  54228. // Put the scene into the database
  54229. var addRequest = transaction.objectStore(targetStore).put(newFile);
  54230. addRequest.onsuccess = function (event) {
  54231. };
  54232. addRequest.onerror = function (event) {
  54233. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  54234. };
  54235. }
  54236. catch (ex) {
  54237. callback(fileData);
  54238. }
  54239. }
  54240. else {
  54241. callback(fileData);
  54242. }
  54243. }
  54244. else {
  54245. callback();
  54246. }
  54247. }, false);
  54248. xhr.addEventListener("error", function (event) {
  54249. BABYLON.Tools.Error("error on XHR request.");
  54250. callback();
  54251. }, false);
  54252. xhr.send();
  54253. }
  54254. else {
  54255. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54256. callback();
  54257. }
  54258. };
  54259. Database.IsUASupportingBlobStorage = true;
  54260. Database.IDBStorageEnabled = true;
  54261. Database.parseURL = function (url) {
  54262. var a = document.createElement('a');
  54263. a.href = url;
  54264. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  54265. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  54266. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  54267. return absLocation;
  54268. };
  54269. Database.ReturnFullUrlLocation = function (url) {
  54270. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  54271. return (Database.parseURL(window.location.href) + url);
  54272. }
  54273. else {
  54274. return url;
  54275. }
  54276. };
  54277. return Database;
  54278. }());
  54279. BABYLON.Database = Database;
  54280. })(BABYLON || (BABYLON = {}));
  54281. //# sourceMappingURL=babylon.database.js.map
  54282. var BABYLON;
  54283. (function (BABYLON) {
  54284. var FresnelParameters = /** @class */ (function () {
  54285. function FresnelParameters() {
  54286. this._isEnabled = true;
  54287. this.leftColor = BABYLON.Color3.White();
  54288. this.rightColor = BABYLON.Color3.Black();
  54289. this.bias = 0;
  54290. this.power = 1;
  54291. }
  54292. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  54293. get: function () {
  54294. return this._isEnabled;
  54295. },
  54296. set: function (value) {
  54297. if (this._isEnabled === value) {
  54298. return;
  54299. }
  54300. this._isEnabled = value;
  54301. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  54302. },
  54303. enumerable: true,
  54304. configurable: true
  54305. });
  54306. FresnelParameters.prototype.clone = function () {
  54307. var newFresnelParameters = new FresnelParameters();
  54308. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  54309. return newFresnelParameters;
  54310. };
  54311. FresnelParameters.prototype.serialize = function () {
  54312. var serializationObject = {};
  54313. serializationObject.isEnabled = this.isEnabled;
  54314. serializationObject.leftColor = this.leftColor;
  54315. serializationObject.rightColor = this.rightColor;
  54316. serializationObject.bias = this.bias;
  54317. serializationObject.power = this.power;
  54318. return serializationObject;
  54319. };
  54320. FresnelParameters.Parse = function (parsedFresnelParameters) {
  54321. var fresnelParameters = new FresnelParameters();
  54322. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  54323. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  54324. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  54325. fresnelParameters.bias = parsedFresnelParameters.bias;
  54326. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  54327. return fresnelParameters;
  54328. };
  54329. return FresnelParameters;
  54330. }());
  54331. BABYLON.FresnelParameters = FresnelParameters;
  54332. })(BABYLON || (BABYLON = {}));
  54333. //# sourceMappingURL=babylon.fresnelParameters.js.map
  54334. var BABYLON;
  54335. (function (BABYLON) {
  54336. var MultiMaterial = /** @class */ (function (_super) {
  54337. __extends(MultiMaterial, _super);
  54338. function MultiMaterial(name, scene) {
  54339. var _this = _super.call(this, name, scene, true) || this;
  54340. scene.multiMaterials.push(_this);
  54341. _this.subMaterials = new Array();
  54342. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  54343. return _this;
  54344. }
  54345. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  54346. get: function () {
  54347. return this._subMaterials;
  54348. },
  54349. set: function (value) {
  54350. this._subMaterials = value;
  54351. this._hookArray(value);
  54352. },
  54353. enumerable: true,
  54354. configurable: true
  54355. });
  54356. MultiMaterial.prototype._hookArray = function (array) {
  54357. var _this = this;
  54358. var oldPush = array.push;
  54359. array.push = function () {
  54360. var items = [];
  54361. for (var _i = 0; _i < arguments.length; _i++) {
  54362. items[_i] = arguments[_i];
  54363. }
  54364. var result = oldPush.apply(array, items);
  54365. _this._markAllSubMeshesAsTexturesDirty();
  54366. return result;
  54367. };
  54368. var oldSplice = array.splice;
  54369. array.splice = function (index, deleteCount) {
  54370. var deleted = oldSplice.apply(array, [index, deleteCount]);
  54371. _this._markAllSubMeshesAsTexturesDirty();
  54372. return deleted;
  54373. };
  54374. };
  54375. // Properties
  54376. MultiMaterial.prototype.getSubMaterial = function (index) {
  54377. if (index < 0 || index >= this.subMaterials.length) {
  54378. return this.getScene().defaultMaterial;
  54379. }
  54380. return this.subMaterials[index];
  54381. };
  54382. MultiMaterial.prototype.getActiveTextures = function () {
  54383. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  54384. if (subMaterial) {
  54385. return subMaterial.getActiveTextures();
  54386. }
  54387. else {
  54388. return [];
  54389. }
  54390. }));
  54391. var _a;
  54392. };
  54393. // Methods
  54394. MultiMaterial.prototype.getClassName = function () {
  54395. return "MultiMaterial";
  54396. };
  54397. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  54398. for (var index = 0; index < this.subMaterials.length; index++) {
  54399. var subMaterial = this.subMaterials[index];
  54400. if (subMaterial) {
  54401. if (subMaterial.storeEffectOnSubMeshes) {
  54402. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  54403. return false;
  54404. }
  54405. continue;
  54406. }
  54407. if (!subMaterial.isReady(mesh)) {
  54408. return false;
  54409. }
  54410. }
  54411. }
  54412. return true;
  54413. };
  54414. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  54415. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  54416. for (var index = 0; index < this.subMaterials.length; index++) {
  54417. var subMaterial = null;
  54418. var current = this.subMaterials[index];
  54419. if (cloneChildren && current) {
  54420. subMaterial = current.clone(name + "-" + current.name);
  54421. }
  54422. else {
  54423. subMaterial = this.subMaterials[index];
  54424. }
  54425. newMultiMaterial.subMaterials.push(subMaterial);
  54426. }
  54427. return newMultiMaterial;
  54428. };
  54429. MultiMaterial.prototype.serialize = function () {
  54430. var serializationObject = {};
  54431. serializationObject.name = this.name;
  54432. serializationObject.id = this.id;
  54433. serializationObject.tags = BABYLON.Tags.GetTags(this);
  54434. serializationObject.materials = [];
  54435. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  54436. var subMat = this.subMaterials[matIndex];
  54437. if (subMat) {
  54438. serializationObject.materials.push(subMat.id);
  54439. }
  54440. else {
  54441. serializationObject.materials.push(null);
  54442. }
  54443. }
  54444. return serializationObject;
  54445. };
  54446. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54447. var scene = this.getScene();
  54448. if (!scene) {
  54449. return;
  54450. }
  54451. var index = scene.multiMaterials.indexOf(this);
  54452. if (index >= 0) {
  54453. scene.multiMaterials.splice(index, 1);
  54454. }
  54455. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54456. };
  54457. return MultiMaterial;
  54458. }(BABYLON.Material));
  54459. BABYLON.MultiMaterial = MultiMaterial;
  54460. })(BABYLON || (BABYLON = {}));
  54461. //# sourceMappingURL=babylon.multiMaterial.js.map
  54462. var BABYLON;
  54463. (function (BABYLON) {
  54464. var FreeCameraTouchInput = /** @class */ (function () {
  54465. function FreeCameraTouchInput() {
  54466. this._offsetX = null;
  54467. this._offsetY = null;
  54468. this._pointerCount = 0;
  54469. this._pointerPressed = new Array();
  54470. this.touchAngularSensibility = 200000.0;
  54471. this.touchMoveSensibility = 250.0;
  54472. }
  54473. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  54474. var _this = this;
  54475. var previousPosition = null;
  54476. if (this._pointerInput === undefined) {
  54477. this._onLostFocus = function (evt) {
  54478. _this._offsetX = null;
  54479. _this._offsetY = null;
  54480. };
  54481. this._pointerInput = function (p, s) {
  54482. var evt = p.event;
  54483. if (evt.pointerType === "mouse") {
  54484. return;
  54485. }
  54486. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  54487. if (!noPreventDefault) {
  54488. evt.preventDefault();
  54489. }
  54490. _this._pointerPressed.push(evt.pointerId);
  54491. if (_this._pointerPressed.length !== 1) {
  54492. return;
  54493. }
  54494. previousPosition = {
  54495. x: evt.clientX,
  54496. y: evt.clientY
  54497. };
  54498. }
  54499. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  54500. if (!noPreventDefault) {
  54501. evt.preventDefault();
  54502. }
  54503. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54504. if (index === -1) {
  54505. return;
  54506. }
  54507. _this._pointerPressed.splice(index, 1);
  54508. if (index != 0) {
  54509. return;
  54510. }
  54511. previousPosition = null;
  54512. _this._offsetX = null;
  54513. _this._offsetY = null;
  54514. }
  54515. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  54516. if (!noPreventDefault) {
  54517. evt.preventDefault();
  54518. }
  54519. if (!previousPosition) {
  54520. return;
  54521. }
  54522. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54523. if (index != 0) {
  54524. return;
  54525. }
  54526. _this._offsetX = evt.clientX - previousPosition.x;
  54527. _this._offsetY = -(evt.clientY - previousPosition.y);
  54528. }
  54529. };
  54530. }
  54531. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  54532. if (this._onLostFocus) {
  54533. element.addEventListener("blur", this._onLostFocus);
  54534. }
  54535. };
  54536. FreeCameraTouchInput.prototype.detachControl = function (element) {
  54537. if (this._pointerInput && element) {
  54538. if (this._observer) {
  54539. this.camera.getScene().onPointerObservable.remove(this._observer);
  54540. this._observer = null;
  54541. }
  54542. if (this._onLostFocus) {
  54543. element.removeEventListener("blur", this._onLostFocus);
  54544. this._onLostFocus = null;
  54545. }
  54546. this._pointerPressed = [];
  54547. this._offsetX = null;
  54548. this._offsetY = null;
  54549. this._pointerCount = 0;
  54550. }
  54551. };
  54552. FreeCameraTouchInput.prototype.checkInputs = function () {
  54553. if (this._offsetX && this._offsetY) {
  54554. var camera = this.camera;
  54555. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  54556. if (this._pointerPressed.length > 1) {
  54557. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  54558. }
  54559. else {
  54560. var speed = camera._computeLocalCameraSpeed();
  54561. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  54562. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54563. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  54564. }
  54565. }
  54566. };
  54567. FreeCameraTouchInput.prototype.getClassName = function () {
  54568. return "FreeCameraTouchInput";
  54569. };
  54570. FreeCameraTouchInput.prototype.getSimpleName = function () {
  54571. return "touch";
  54572. };
  54573. __decorate([
  54574. BABYLON.serialize()
  54575. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  54576. __decorate([
  54577. BABYLON.serialize()
  54578. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54579. return FreeCameraTouchInput;
  54580. }());
  54581. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54582. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54583. })(BABYLON || (BABYLON = {}));
  54584. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54585. var BABYLON;
  54586. (function (BABYLON) {
  54587. // We're mainly based on the logic defined into the FreeCamera code
  54588. var TouchCamera = /** @class */ (function (_super) {
  54589. __extends(TouchCamera, _super);
  54590. //-- end properties for backward compatibility for inputs
  54591. function TouchCamera(name, position, scene) {
  54592. var _this = _super.call(this, name, position, scene) || this;
  54593. _this.inputs.addTouch();
  54594. _this._setupInputs();
  54595. return _this;
  54596. }
  54597. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54598. //-- Begin properties for backward compatibility for inputs
  54599. get: function () {
  54600. var touch = this.inputs.attached["touch"];
  54601. if (touch)
  54602. return touch.touchAngularSensibility;
  54603. return 0;
  54604. },
  54605. set: function (value) {
  54606. var touch = this.inputs.attached["touch"];
  54607. if (touch)
  54608. touch.touchAngularSensibility = value;
  54609. },
  54610. enumerable: true,
  54611. configurable: true
  54612. });
  54613. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54614. get: function () {
  54615. var touch = this.inputs.attached["touch"];
  54616. if (touch)
  54617. return touch.touchMoveSensibility;
  54618. return 0;
  54619. },
  54620. set: function (value) {
  54621. var touch = this.inputs.attached["touch"];
  54622. if (touch)
  54623. touch.touchMoveSensibility = value;
  54624. },
  54625. enumerable: true,
  54626. configurable: true
  54627. });
  54628. TouchCamera.prototype.getClassName = function () {
  54629. return "TouchCamera";
  54630. };
  54631. TouchCamera.prototype._setupInputs = function () {
  54632. var mouse = this.inputs.attached["mouse"];
  54633. if (mouse) {
  54634. mouse.touchEnabled = false;
  54635. }
  54636. };
  54637. return TouchCamera;
  54638. }(BABYLON.FreeCamera));
  54639. BABYLON.TouchCamera = TouchCamera;
  54640. })(BABYLON || (BABYLON = {}));
  54641. //# sourceMappingURL=babylon.touchCamera.js.map
  54642. var BABYLON;
  54643. (function (BABYLON) {
  54644. var ProceduralTexture = /** @class */ (function (_super) {
  54645. __extends(ProceduralTexture, _super);
  54646. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  54647. if (fallbackTexture === void 0) { fallbackTexture = null; }
  54648. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54649. if (isCube === void 0) { isCube = false; }
  54650. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54651. _this.isCube = isCube;
  54652. _this.isEnabled = true;
  54653. _this._currentRefreshId = -1;
  54654. _this._refreshRate = 1;
  54655. _this._vertexBuffers = {};
  54656. _this._uniforms = new Array();
  54657. _this._samplers = new Array();
  54658. _this._textures = {};
  54659. _this._floats = {};
  54660. _this._floatsArrays = {};
  54661. _this._colors3 = {};
  54662. _this._colors4 = {};
  54663. _this._vectors2 = {};
  54664. _this._vectors3 = {};
  54665. _this._matrices = {};
  54666. _this._fallbackTextureUsed = false;
  54667. scene._proceduralTextures.push(_this);
  54668. _this._engine = scene.getEngine();
  54669. _this.name = name;
  54670. _this.isRenderTarget = true;
  54671. _this._size = size;
  54672. _this._generateMipMaps = generateMipMaps;
  54673. _this.setFragment(fragment);
  54674. _this._fallbackTexture = fallbackTexture;
  54675. if (isCube) {
  54676. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  54677. _this.setFloat("face", 0);
  54678. }
  54679. else {
  54680. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  54681. }
  54682. // VBO
  54683. var vertices = [];
  54684. vertices.push(1, 1);
  54685. vertices.push(-1, 1);
  54686. vertices.push(-1, -1);
  54687. vertices.push(1, -1);
  54688. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54689. _this._createIndexBuffer();
  54690. return _this;
  54691. }
  54692. ProceduralTexture.prototype._createIndexBuffer = function () {
  54693. var engine = this._engine;
  54694. // Indices
  54695. var indices = [];
  54696. indices.push(0);
  54697. indices.push(1);
  54698. indices.push(2);
  54699. indices.push(0);
  54700. indices.push(2);
  54701. indices.push(3);
  54702. this._indexBuffer = engine.createIndexBuffer(indices);
  54703. };
  54704. ProceduralTexture.prototype._rebuild = function () {
  54705. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54706. if (vb) {
  54707. vb._rebuild();
  54708. }
  54709. this._createIndexBuffer();
  54710. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54711. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54712. }
  54713. };
  54714. ProceduralTexture.prototype.reset = function () {
  54715. if (this._effect === undefined) {
  54716. return;
  54717. }
  54718. var engine = this._engine;
  54719. engine._releaseEffect(this._effect);
  54720. };
  54721. ProceduralTexture.prototype.isReady = function () {
  54722. var _this = this;
  54723. var engine = this._engine;
  54724. var shaders;
  54725. if (!this._fragment) {
  54726. return false;
  54727. }
  54728. if (this._fallbackTextureUsed) {
  54729. return true;
  54730. }
  54731. if (this._fragment.fragmentElement !== undefined) {
  54732. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  54733. }
  54734. else {
  54735. shaders = { vertex: "procedural", fragment: this._fragment };
  54736. }
  54737. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  54738. _this.releaseInternalTexture();
  54739. if (_this._fallbackTexture) {
  54740. _this._texture = _this._fallbackTexture._texture;
  54741. if (_this._texture) {
  54742. _this._texture.incrementReferences();
  54743. }
  54744. }
  54745. _this._fallbackTextureUsed = true;
  54746. });
  54747. return this._effect.isReady();
  54748. };
  54749. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54750. this._currentRefreshId = -1;
  54751. };
  54752. ProceduralTexture.prototype.setFragment = function (fragment) {
  54753. this._fragment = fragment;
  54754. };
  54755. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54756. get: function () {
  54757. return this._refreshRate;
  54758. },
  54759. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54760. set: function (value) {
  54761. this._refreshRate = value;
  54762. this.resetRefreshCounter();
  54763. },
  54764. enumerable: true,
  54765. configurable: true
  54766. });
  54767. ProceduralTexture.prototype._shouldRender = function () {
  54768. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54769. return false;
  54770. }
  54771. if (this._fallbackTextureUsed) {
  54772. return false;
  54773. }
  54774. if (this._currentRefreshId === -1) {
  54775. this._currentRefreshId = 1;
  54776. return true;
  54777. }
  54778. if (this.refreshRate === this._currentRefreshId) {
  54779. this._currentRefreshId = 1;
  54780. return true;
  54781. }
  54782. this._currentRefreshId++;
  54783. return false;
  54784. };
  54785. ProceduralTexture.prototype.getRenderSize = function () {
  54786. return this._size;
  54787. };
  54788. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54789. if (this._fallbackTextureUsed) {
  54790. return;
  54791. }
  54792. this.releaseInternalTexture();
  54793. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54794. };
  54795. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54796. if (this._uniforms.indexOf(uniformName) === -1) {
  54797. this._uniforms.push(uniformName);
  54798. }
  54799. };
  54800. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54801. if (this._samplers.indexOf(name) === -1) {
  54802. this._samplers.push(name);
  54803. }
  54804. this._textures[name] = texture;
  54805. return this;
  54806. };
  54807. ProceduralTexture.prototype.setFloat = function (name, value) {
  54808. this._checkUniform(name);
  54809. this._floats[name] = value;
  54810. return this;
  54811. };
  54812. ProceduralTexture.prototype.setFloats = function (name, value) {
  54813. this._checkUniform(name);
  54814. this._floatsArrays[name] = value;
  54815. return this;
  54816. };
  54817. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54818. this._checkUniform(name);
  54819. this._colors3[name] = value;
  54820. return this;
  54821. };
  54822. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54823. this._checkUniform(name);
  54824. this._colors4[name] = value;
  54825. return this;
  54826. };
  54827. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54828. this._checkUniform(name);
  54829. this._vectors2[name] = value;
  54830. return this;
  54831. };
  54832. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54833. this._checkUniform(name);
  54834. this._vectors3[name] = value;
  54835. return this;
  54836. };
  54837. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54838. this._checkUniform(name);
  54839. this._matrices[name] = value;
  54840. return this;
  54841. };
  54842. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54843. var scene = this.getScene();
  54844. if (!scene) {
  54845. return;
  54846. }
  54847. var engine = this._engine;
  54848. // Render
  54849. engine.enableEffect(this._effect);
  54850. engine.setState(false);
  54851. // Texture
  54852. for (var name in this._textures) {
  54853. this._effect.setTexture(name, this._textures[name]);
  54854. }
  54855. // Float
  54856. for (name in this._floats) {
  54857. this._effect.setFloat(name, this._floats[name]);
  54858. }
  54859. // Floats
  54860. for (name in this._floatsArrays) {
  54861. this._effect.setArray(name, this._floatsArrays[name]);
  54862. }
  54863. // Color3
  54864. for (name in this._colors3) {
  54865. this._effect.setColor3(name, this._colors3[name]);
  54866. }
  54867. // Color4
  54868. for (name in this._colors4) {
  54869. var color = this._colors4[name];
  54870. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54871. }
  54872. // Vector2
  54873. for (name in this._vectors2) {
  54874. this._effect.setVector2(name, this._vectors2[name]);
  54875. }
  54876. // Vector3
  54877. for (name in this._vectors3) {
  54878. this._effect.setVector3(name, this._vectors3[name]);
  54879. }
  54880. // Matrix
  54881. for (name in this._matrices) {
  54882. this._effect.setMatrix(name, this._matrices[name]);
  54883. }
  54884. if (!this._texture) {
  54885. return;
  54886. }
  54887. if (this.isCube) {
  54888. for (var face = 0; face < 6; face++) {
  54889. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54890. // VBOs
  54891. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54892. this._effect.setFloat("face", face);
  54893. // Clear
  54894. engine.clear(scene.clearColor, true, true, true);
  54895. // Draw order
  54896. engine.draw(true, 0, 6);
  54897. // Mipmaps
  54898. if (face === 5) {
  54899. engine.generateMipMapsForCubemap(this._texture);
  54900. }
  54901. }
  54902. }
  54903. else {
  54904. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54905. // VBOs
  54906. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54907. // Clear
  54908. engine.clear(scene.clearColor, true, true, true);
  54909. // Draw order
  54910. engine.draw(true, 0, 6);
  54911. }
  54912. // Unbind
  54913. engine.unBindFramebuffer(this._texture, this.isCube);
  54914. if (this.onGenerated) {
  54915. this.onGenerated();
  54916. }
  54917. };
  54918. ProceduralTexture.prototype.clone = function () {
  54919. var textureSize = this.getSize();
  54920. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54921. // Base texture
  54922. newTexture.hasAlpha = this.hasAlpha;
  54923. newTexture.level = this.level;
  54924. // RenderTarget Texture
  54925. newTexture.coordinatesMode = this.coordinatesMode;
  54926. return newTexture;
  54927. };
  54928. ProceduralTexture.prototype.dispose = function () {
  54929. var scene = this.getScene();
  54930. if (!scene) {
  54931. return;
  54932. }
  54933. var index = scene._proceduralTextures.indexOf(this);
  54934. if (index >= 0) {
  54935. scene._proceduralTextures.splice(index, 1);
  54936. }
  54937. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54938. if (vertexBuffer) {
  54939. vertexBuffer.dispose();
  54940. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54941. }
  54942. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54943. this._indexBuffer = null;
  54944. }
  54945. _super.prototype.dispose.call(this);
  54946. };
  54947. return ProceduralTexture;
  54948. }(BABYLON.Texture));
  54949. BABYLON.ProceduralTexture = ProceduralTexture;
  54950. })(BABYLON || (BABYLON = {}));
  54951. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54952. var BABYLON;
  54953. (function (BABYLON) {
  54954. var CustomProceduralTexture = /** @class */ (function (_super) {
  54955. __extends(CustomProceduralTexture, _super);
  54956. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54957. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54958. _this._animate = true;
  54959. _this._time = 0;
  54960. _this._texturePath = texturePath;
  54961. //Try to load json
  54962. _this.loadJson(texturePath);
  54963. _this.refreshRate = 1;
  54964. return _this;
  54965. }
  54966. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54967. var _this = this;
  54968. var noConfigFile = function () {
  54969. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54970. try {
  54971. _this.setFragment(_this._texturePath);
  54972. }
  54973. catch (ex) {
  54974. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54975. }
  54976. };
  54977. var configFileUrl = jsonUrl + "/config.json";
  54978. var xhr = new XMLHttpRequest();
  54979. xhr.open("GET", configFileUrl, true);
  54980. xhr.addEventListener("load", function () {
  54981. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54982. try {
  54983. _this._config = JSON.parse(xhr.response);
  54984. _this.updateShaderUniforms();
  54985. _this.updateTextures();
  54986. _this.setFragment(_this._texturePath + "/custom");
  54987. _this._animate = _this._config.animate;
  54988. _this.refreshRate = _this._config.refreshrate;
  54989. }
  54990. catch (ex) {
  54991. noConfigFile();
  54992. }
  54993. }
  54994. else {
  54995. noConfigFile();
  54996. }
  54997. }, false);
  54998. xhr.addEventListener("error", function () {
  54999. noConfigFile();
  55000. }, false);
  55001. try {
  55002. xhr.send();
  55003. }
  55004. catch (ex) {
  55005. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  55006. }
  55007. };
  55008. CustomProceduralTexture.prototype.isReady = function () {
  55009. if (!_super.prototype.isReady.call(this)) {
  55010. return false;
  55011. }
  55012. for (var name in this._textures) {
  55013. var texture = this._textures[name];
  55014. if (!texture.isReady()) {
  55015. return false;
  55016. }
  55017. }
  55018. return true;
  55019. };
  55020. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55021. var scene = this.getScene();
  55022. if (this._animate && scene) {
  55023. this._time += scene.getAnimationRatio() * 0.03;
  55024. this.updateShaderUniforms();
  55025. }
  55026. _super.prototype.render.call(this, useCameraPostProcess);
  55027. };
  55028. CustomProceduralTexture.prototype.updateTextures = function () {
  55029. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  55030. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  55031. }
  55032. };
  55033. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  55034. if (this._config) {
  55035. for (var j = 0; j < this._config.uniforms.length; j++) {
  55036. var uniform = this._config.uniforms[j];
  55037. switch (uniform.type) {
  55038. case "float":
  55039. this.setFloat(uniform.name, uniform.value);
  55040. break;
  55041. case "color3":
  55042. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  55043. break;
  55044. case "color4":
  55045. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  55046. break;
  55047. case "vector2":
  55048. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  55049. break;
  55050. case "vector3":
  55051. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  55052. break;
  55053. }
  55054. }
  55055. }
  55056. this.setFloat("time", this._time);
  55057. };
  55058. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  55059. get: function () {
  55060. return this._animate;
  55061. },
  55062. set: function (value) {
  55063. this._animate = value;
  55064. },
  55065. enumerable: true,
  55066. configurable: true
  55067. });
  55068. return CustomProceduralTexture;
  55069. }(BABYLON.ProceduralTexture));
  55070. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  55071. })(BABYLON || (BABYLON = {}));
  55072. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  55073. var BABYLON;
  55074. (function (BABYLON) {
  55075. var FreeCameraGamepadInput = /** @class */ (function () {
  55076. function FreeCameraGamepadInput() {
  55077. this.gamepadAngularSensibility = 200;
  55078. this.gamepadMoveSensibility = 40;
  55079. // private members
  55080. this._cameraTransform = BABYLON.Matrix.Identity();
  55081. this._deltaTransform = BABYLON.Vector3.Zero();
  55082. this._vector3 = BABYLON.Vector3.Zero();
  55083. this._vector2 = BABYLON.Vector2.Zero();
  55084. }
  55085. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55086. var _this = this;
  55087. var manager = this.camera.getScene().gamepadManager;
  55088. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55089. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55090. // prioritize XBOX gamepads.
  55091. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55092. _this.gamepad = gamepad;
  55093. }
  55094. }
  55095. });
  55096. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55097. if (_this.gamepad === gamepad) {
  55098. _this.gamepad = null;
  55099. }
  55100. });
  55101. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55102. };
  55103. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  55104. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55105. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55106. this.gamepad = null;
  55107. };
  55108. FreeCameraGamepadInput.prototype.checkInputs = function () {
  55109. if (this.gamepad && this.gamepad.leftStick) {
  55110. var camera = this.camera;
  55111. var LSValues = this.gamepad.leftStick;
  55112. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  55113. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55114. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  55115. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  55116. var RSValues = this.gamepad.rightStick;
  55117. if (RSValues) {
  55118. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  55119. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  55120. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  55121. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  55122. }
  55123. else {
  55124. RSValues = { x: 0, y: 0 };
  55125. }
  55126. if (!camera.rotationQuaternion) {
  55127. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  55128. }
  55129. else {
  55130. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  55131. }
  55132. var speed = camera._computeLocalCameraSpeed() * 50.0;
  55133. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  55134. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  55135. camera.cameraDirection.addInPlace(this._deltaTransform);
  55136. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  55137. camera.cameraRotation.addInPlace(this._vector2);
  55138. }
  55139. };
  55140. FreeCameraGamepadInput.prototype.getClassName = function () {
  55141. return "FreeCameraGamepadInput";
  55142. };
  55143. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  55144. return "gamepad";
  55145. };
  55146. __decorate([
  55147. BABYLON.serialize()
  55148. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  55149. __decorate([
  55150. BABYLON.serialize()
  55151. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55152. return FreeCameraGamepadInput;
  55153. }());
  55154. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  55155. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  55156. })(BABYLON || (BABYLON = {}));
  55157. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  55158. var BABYLON;
  55159. (function (BABYLON) {
  55160. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  55161. function ArcRotateCameraGamepadInput() {
  55162. this.gamepadRotationSensibility = 80;
  55163. this.gamepadMoveSensibility = 40;
  55164. }
  55165. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55166. var _this = this;
  55167. var manager = this.camera.getScene().gamepadManager;
  55168. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55169. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55170. // prioritize XBOX gamepads.
  55171. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55172. _this.gamepad = gamepad;
  55173. }
  55174. }
  55175. });
  55176. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55177. if (_this.gamepad === gamepad) {
  55178. _this.gamepad = null;
  55179. }
  55180. });
  55181. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55182. };
  55183. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  55184. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55185. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55186. this.gamepad = null;
  55187. };
  55188. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  55189. if (this.gamepad) {
  55190. var camera = this.camera;
  55191. var RSValues = this.gamepad.rightStick;
  55192. if (RSValues) {
  55193. if (RSValues.x != 0) {
  55194. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  55195. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  55196. camera.inertialAlphaOffset += normalizedRX;
  55197. }
  55198. }
  55199. if (RSValues.y != 0) {
  55200. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  55201. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  55202. camera.inertialBetaOffset += normalizedRY;
  55203. }
  55204. }
  55205. }
  55206. var LSValues = this.gamepad.leftStick;
  55207. if (LSValues && LSValues.y != 0) {
  55208. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55209. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  55210. this.camera.inertialRadiusOffset -= normalizedLY;
  55211. }
  55212. }
  55213. }
  55214. };
  55215. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  55216. return "ArcRotateCameraGamepadInput";
  55217. };
  55218. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  55219. return "gamepad";
  55220. };
  55221. __decorate([
  55222. BABYLON.serialize()
  55223. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  55224. __decorate([
  55225. BABYLON.serialize()
  55226. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55227. return ArcRotateCameraGamepadInput;
  55228. }());
  55229. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  55230. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  55231. })(BABYLON || (BABYLON = {}));
  55232. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  55233. var BABYLON;
  55234. (function (BABYLON) {
  55235. var GamepadManager = /** @class */ (function () {
  55236. function GamepadManager() {
  55237. var _this = this;
  55238. this._babylonGamepads = [];
  55239. this._oneGamepadConnected = false;
  55240. this._isMonitoring = false;
  55241. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  55242. if (!BABYLON.Tools.IsWindowObjectExist()) {
  55243. this._gamepadEventSupported = false;
  55244. }
  55245. else {
  55246. this._gamepadEventSupported = 'GamepadEvent' in window;
  55247. this._gamepadSupport = (navigator.getGamepads ||
  55248. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  55249. }
  55250. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  55251. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  55252. for (var i in _this._babylonGamepads) {
  55253. var gamepad = _this._babylonGamepads[i];
  55254. if (gamepad && gamepad._isConnected) {
  55255. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  55256. }
  55257. }
  55258. });
  55259. this._onGamepadConnectedEvent = function (evt) {
  55260. var gamepad = evt.gamepad;
  55261. if (gamepad.index in _this._babylonGamepads) {
  55262. if (_this._babylonGamepads[gamepad.index].isConnected) {
  55263. return;
  55264. }
  55265. }
  55266. var newGamepad;
  55267. if (_this._babylonGamepads[gamepad.index]) {
  55268. newGamepad = _this._babylonGamepads[gamepad.index];
  55269. newGamepad.browserGamepad = gamepad;
  55270. newGamepad._isConnected = true;
  55271. }
  55272. else {
  55273. newGamepad = _this._addNewGamepad(gamepad);
  55274. }
  55275. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55276. _this._startMonitoringGamepads();
  55277. };
  55278. this._onGamepadDisconnectedEvent = function (evt) {
  55279. var gamepad = evt.gamepad;
  55280. // Remove the gamepad from the list of gamepads to monitor.
  55281. for (var i in _this._babylonGamepads) {
  55282. if (_this._babylonGamepads[i].index === gamepad.index) {
  55283. var disconnectedGamepad = _this._babylonGamepads[i];
  55284. disconnectedGamepad._isConnected = false;
  55285. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  55286. break;
  55287. }
  55288. }
  55289. };
  55290. if (this._gamepadSupport) {
  55291. //first add already-connected gamepads
  55292. this._updateGamepadObjects();
  55293. if (this._babylonGamepads.length) {
  55294. this._startMonitoringGamepads();
  55295. }
  55296. // Checking if the gamepad connected event is supported (like in Firefox)
  55297. if (this._gamepadEventSupported) {
  55298. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55299. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  55300. }
  55301. else {
  55302. this._startMonitoringGamepads();
  55303. }
  55304. }
  55305. }
  55306. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  55307. get: function () {
  55308. return this._babylonGamepads;
  55309. },
  55310. enumerable: true,
  55311. configurable: true
  55312. });
  55313. GamepadManager.prototype.getGamepadByType = function (type) {
  55314. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  55315. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  55316. var gamepad = _a[_i];
  55317. if (gamepad && gamepad.type === type) {
  55318. return gamepad;
  55319. }
  55320. }
  55321. return null;
  55322. };
  55323. GamepadManager.prototype.dispose = function () {
  55324. if (this._gamepadEventSupported) {
  55325. if (this._onGamepadConnectedEvent) {
  55326. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  55327. }
  55328. if (this._onGamepadDisconnectedEvent) {
  55329. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  55330. }
  55331. this._onGamepadConnectedEvent = null;
  55332. this._onGamepadDisconnectedEvent = null;
  55333. }
  55334. this._babylonGamepads.forEach(function (gamepad) {
  55335. gamepad.dispose();
  55336. });
  55337. this.onGamepadConnectedObservable.clear();
  55338. this.onGamepadDisconnectedObservable.clear();
  55339. this._oneGamepadConnected = false;
  55340. this._stopMonitoringGamepads();
  55341. this._babylonGamepads = [];
  55342. };
  55343. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  55344. if (!this._oneGamepadConnected) {
  55345. this._oneGamepadConnected = true;
  55346. }
  55347. var newGamepad;
  55348. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  55349. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55350. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  55351. }
  55352. else if (gamepad.pose) {
  55353. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  55354. }
  55355. else {
  55356. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  55357. }
  55358. this._babylonGamepads[newGamepad.index] = newGamepad;
  55359. return newGamepad;
  55360. };
  55361. GamepadManager.prototype._startMonitoringGamepads = function () {
  55362. if (!this._isMonitoring) {
  55363. this._isMonitoring = true;
  55364. this._checkGamepadsStatus();
  55365. }
  55366. };
  55367. GamepadManager.prototype._stopMonitoringGamepads = function () {
  55368. this._isMonitoring = false;
  55369. };
  55370. GamepadManager.prototype._checkGamepadsStatus = function () {
  55371. var _this = this;
  55372. // Hack to be compatible Chrome
  55373. this._updateGamepadObjects();
  55374. for (var i in this._babylonGamepads) {
  55375. var gamepad = this._babylonGamepads[i];
  55376. if (!gamepad || !gamepad.isConnected) {
  55377. continue;
  55378. }
  55379. gamepad.update();
  55380. }
  55381. if (this._isMonitoring) {
  55382. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  55383. }
  55384. };
  55385. // This function is called only on Chrome, which does not properly support
  55386. // connection/disconnection events and forces you to recopy again the gamepad object
  55387. GamepadManager.prototype._updateGamepadObjects = function () {
  55388. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  55389. for (var i = 0; i < gamepads.length; i++) {
  55390. if (gamepads[i]) {
  55391. if (!this._babylonGamepads[gamepads[i].index]) {
  55392. var newGamepad = this._addNewGamepad(gamepads[i]);
  55393. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55394. }
  55395. else {
  55396. // Forced to copy again this object for Chrome for unknown reason
  55397. this._babylonGamepads[i].browserGamepad = gamepads[i];
  55398. if (!this._babylonGamepads[i].isConnected) {
  55399. this._babylonGamepads[i]._isConnected = true;
  55400. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  55401. }
  55402. }
  55403. }
  55404. }
  55405. };
  55406. return GamepadManager;
  55407. }());
  55408. BABYLON.GamepadManager = GamepadManager;
  55409. })(BABYLON || (BABYLON = {}));
  55410. //# sourceMappingURL=babylon.gamepadManager.js.map
  55411. var BABYLON;
  55412. (function (BABYLON) {
  55413. var StickValues = /** @class */ (function () {
  55414. function StickValues(x, y) {
  55415. this.x = x;
  55416. this.y = y;
  55417. }
  55418. return StickValues;
  55419. }());
  55420. BABYLON.StickValues = StickValues;
  55421. var Gamepad = /** @class */ (function () {
  55422. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  55423. if (leftStickX === void 0) { leftStickX = 0; }
  55424. if (leftStickY === void 0) { leftStickY = 1; }
  55425. if (rightStickX === void 0) { rightStickX = 2; }
  55426. if (rightStickY === void 0) { rightStickY = 3; }
  55427. this.id = id;
  55428. this.index = index;
  55429. this.browserGamepad = browserGamepad;
  55430. this._isConnected = true;
  55431. this.type = Gamepad.GAMEPAD;
  55432. this._leftStickAxisX = leftStickX;
  55433. this._leftStickAxisY = leftStickY;
  55434. this._rightStickAxisX = rightStickX;
  55435. this._rightStickAxisY = rightStickY;
  55436. if (this.browserGamepad.axes.length >= 2) {
  55437. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55438. }
  55439. if (this.browserGamepad.axes.length >= 4) {
  55440. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55441. }
  55442. }
  55443. Object.defineProperty(Gamepad.prototype, "isConnected", {
  55444. get: function () {
  55445. return this._isConnected;
  55446. },
  55447. enumerable: true,
  55448. configurable: true
  55449. });
  55450. Gamepad.prototype.onleftstickchanged = function (callback) {
  55451. this._onleftstickchanged = callback;
  55452. };
  55453. Gamepad.prototype.onrightstickchanged = function (callback) {
  55454. this._onrightstickchanged = callback;
  55455. };
  55456. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55457. get: function () {
  55458. return this._leftStick;
  55459. },
  55460. set: function (newValues) {
  55461. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55462. this._onleftstickchanged(newValues);
  55463. }
  55464. this._leftStick = newValues;
  55465. },
  55466. enumerable: true,
  55467. configurable: true
  55468. });
  55469. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55470. get: function () {
  55471. return this._rightStick;
  55472. },
  55473. set: function (newValues) {
  55474. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55475. this._onrightstickchanged(newValues);
  55476. }
  55477. this._rightStick = newValues;
  55478. },
  55479. enumerable: true,
  55480. configurable: true
  55481. });
  55482. Gamepad.prototype.update = function () {
  55483. if (this._leftStick) {
  55484. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55485. }
  55486. if (this._rightStick) {
  55487. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55488. }
  55489. };
  55490. Gamepad.prototype.dispose = function () {
  55491. };
  55492. Gamepad.GAMEPAD = 0;
  55493. Gamepad.GENERIC = 1;
  55494. Gamepad.XBOX = 2;
  55495. Gamepad.POSE_ENABLED = 3;
  55496. return Gamepad;
  55497. }());
  55498. BABYLON.Gamepad = Gamepad;
  55499. var GenericPad = /** @class */ (function (_super) {
  55500. __extends(GenericPad, _super);
  55501. function GenericPad(id, index, browserGamepad) {
  55502. var _this = _super.call(this, id, index, browserGamepad) || this;
  55503. _this.onButtonDownObservable = new BABYLON.Observable();
  55504. _this.onButtonUpObservable = new BABYLON.Observable();
  55505. _this.type = Gamepad.GENERIC;
  55506. _this._buttons = new Array(browserGamepad.buttons.length);
  55507. return _this;
  55508. }
  55509. GenericPad.prototype.onbuttondown = function (callback) {
  55510. this._onbuttondown = callback;
  55511. };
  55512. GenericPad.prototype.onbuttonup = function (callback) {
  55513. this._onbuttonup = callback;
  55514. };
  55515. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55516. if (newValue !== currentValue) {
  55517. if (newValue === 1) {
  55518. if (this._onbuttondown) {
  55519. this._onbuttondown(buttonIndex);
  55520. }
  55521. this.onButtonDownObservable.notifyObservers(buttonIndex);
  55522. }
  55523. if (newValue === 0) {
  55524. if (this._onbuttonup) {
  55525. this._onbuttonup(buttonIndex);
  55526. }
  55527. this.onButtonUpObservable.notifyObservers(buttonIndex);
  55528. }
  55529. }
  55530. return newValue;
  55531. };
  55532. GenericPad.prototype.update = function () {
  55533. _super.prototype.update.call(this);
  55534. for (var index = 0; index < this._buttons.length; index++) {
  55535. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  55536. }
  55537. };
  55538. return GenericPad;
  55539. }(Gamepad));
  55540. BABYLON.GenericPad = GenericPad;
  55541. })(BABYLON || (BABYLON = {}));
  55542. //# sourceMappingURL=babylon.gamepad.js.map
  55543. var BABYLON;
  55544. (function (BABYLON) {
  55545. var Xbox360Button;
  55546. (function (Xbox360Button) {
  55547. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55548. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55549. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55550. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55551. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55552. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55553. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55554. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55555. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55556. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55557. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55558. var Xbox360Dpad;
  55559. (function (Xbox360Dpad) {
  55560. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55561. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55562. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55563. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55564. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55565. var Xbox360Pad = /** @class */ (function (_super) {
  55566. __extends(Xbox360Pad, _super);
  55567. function Xbox360Pad(id, index, gamepad, xboxOne) {
  55568. if (xboxOne === void 0) { xboxOne = false; }
  55569. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  55570. _this._leftTrigger = 0;
  55571. _this._rightTrigger = 0;
  55572. _this.onButtonDownObservable = new BABYLON.Observable();
  55573. _this.onButtonUpObservable = new BABYLON.Observable();
  55574. _this.onPadDownObservable = new BABYLON.Observable();
  55575. _this.onPadUpObservable = new BABYLON.Observable();
  55576. _this._buttonA = 0;
  55577. _this._buttonB = 0;
  55578. _this._buttonX = 0;
  55579. _this._buttonY = 0;
  55580. _this._buttonBack = 0;
  55581. _this._buttonStart = 0;
  55582. _this._buttonLB = 0;
  55583. _this._buttonRB = 0;
  55584. _this._buttonLeftStick = 0;
  55585. _this._buttonRightStick = 0;
  55586. _this._dPadUp = 0;
  55587. _this._dPadDown = 0;
  55588. _this._dPadLeft = 0;
  55589. _this._dPadRight = 0;
  55590. _this._isXboxOnePad = false;
  55591. _this.type = BABYLON.Gamepad.XBOX;
  55592. _this._isXboxOnePad = xboxOne;
  55593. return _this;
  55594. }
  55595. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55596. this._onlefttriggerchanged = callback;
  55597. };
  55598. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55599. this._onrighttriggerchanged = callback;
  55600. };
  55601. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55602. get: function () {
  55603. return this._leftTrigger;
  55604. },
  55605. set: function (newValue) {
  55606. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55607. this._onlefttriggerchanged(newValue);
  55608. }
  55609. this._leftTrigger = newValue;
  55610. },
  55611. enumerable: true,
  55612. configurable: true
  55613. });
  55614. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55615. get: function () {
  55616. return this._rightTrigger;
  55617. },
  55618. set: function (newValue) {
  55619. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55620. this._onrighttriggerchanged(newValue);
  55621. }
  55622. this._rightTrigger = newValue;
  55623. },
  55624. enumerable: true,
  55625. configurable: true
  55626. });
  55627. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55628. this._onbuttondown = callback;
  55629. };
  55630. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55631. this._onbuttonup = callback;
  55632. };
  55633. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55634. this._ondpaddown = callback;
  55635. };
  55636. Xbox360Pad.prototype.ondpadup = function (callback) {
  55637. this._ondpadup = callback;
  55638. };
  55639. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55640. if (newValue !== currentValue) {
  55641. if (newValue === 1) {
  55642. if (this._onbuttondown) {
  55643. this._onbuttondown(buttonType);
  55644. }
  55645. this.onButtonDownObservable.notifyObservers(buttonType);
  55646. }
  55647. if (newValue === 0) {
  55648. if (this._onbuttonup) {
  55649. this._onbuttonup(buttonType);
  55650. }
  55651. this.onButtonUpObservable.notifyObservers(buttonType);
  55652. }
  55653. }
  55654. return newValue;
  55655. };
  55656. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55657. if (newValue !== currentValue) {
  55658. if (newValue === 1) {
  55659. if (this._ondpaddown) {
  55660. this._ondpaddown(buttonType);
  55661. }
  55662. this.onPadDownObservable.notifyObservers(buttonType);
  55663. }
  55664. if (newValue === 0) {
  55665. if (this._ondpadup) {
  55666. this._ondpadup(buttonType);
  55667. }
  55668. this.onPadUpObservable.notifyObservers(buttonType);
  55669. }
  55670. }
  55671. return newValue;
  55672. };
  55673. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55674. get: function () {
  55675. return this._buttonA;
  55676. },
  55677. set: function (value) {
  55678. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55679. },
  55680. enumerable: true,
  55681. configurable: true
  55682. });
  55683. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55684. get: function () {
  55685. return this._buttonB;
  55686. },
  55687. set: function (value) {
  55688. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55689. },
  55690. enumerable: true,
  55691. configurable: true
  55692. });
  55693. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55694. get: function () {
  55695. return this._buttonX;
  55696. },
  55697. set: function (value) {
  55698. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55699. },
  55700. enumerable: true,
  55701. configurable: true
  55702. });
  55703. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55704. get: function () {
  55705. return this._buttonY;
  55706. },
  55707. set: function (value) {
  55708. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55709. },
  55710. enumerable: true,
  55711. configurable: true
  55712. });
  55713. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55714. get: function () {
  55715. return this._buttonStart;
  55716. },
  55717. set: function (value) {
  55718. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55719. },
  55720. enumerable: true,
  55721. configurable: true
  55722. });
  55723. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55724. get: function () {
  55725. return this._buttonBack;
  55726. },
  55727. set: function (value) {
  55728. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55729. },
  55730. enumerable: true,
  55731. configurable: true
  55732. });
  55733. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55734. get: function () {
  55735. return this._buttonLB;
  55736. },
  55737. set: function (value) {
  55738. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55739. },
  55740. enumerable: true,
  55741. configurable: true
  55742. });
  55743. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55744. get: function () {
  55745. return this._buttonRB;
  55746. },
  55747. set: function (value) {
  55748. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55749. },
  55750. enumerable: true,
  55751. configurable: true
  55752. });
  55753. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55754. get: function () {
  55755. return this._buttonLeftStick;
  55756. },
  55757. set: function (value) {
  55758. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55759. },
  55760. enumerable: true,
  55761. configurable: true
  55762. });
  55763. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55764. get: function () {
  55765. return this._buttonRightStick;
  55766. },
  55767. set: function (value) {
  55768. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55769. },
  55770. enumerable: true,
  55771. configurable: true
  55772. });
  55773. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55774. get: function () {
  55775. return this._dPadUp;
  55776. },
  55777. set: function (value) {
  55778. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55779. },
  55780. enumerable: true,
  55781. configurable: true
  55782. });
  55783. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55784. get: function () {
  55785. return this._dPadDown;
  55786. },
  55787. set: function (value) {
  55788. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55789. },
  55790. enumerable: true,
  55791. configurable: true
  55792. });
  55793. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55794. get: function () {
  55795. return this._dPadLeft;
  55796. },
  55797. set: function (value) {
  55798. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55799. },
  55800. enumerable: true,
  55801. configurable: true
  55802. });
  55803. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55804. get: function () {
  55805. return this._dPadRight;
  55806. },
  55807. set: function (value) {
  55808. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55809. },
  55810. enumerable: true,
  55811. configurable: true
  55812. });
  55813. Xbox360Pad.prototype.update = function () {
  55814. _super.prototype.update.call(this);
  55815. if (this._isXboxOnePad) {
  55816. this.buttonA = this.browserGamepad.buttons[0].value;
  55817. this.buttonB = this.browserGamepad.buttons[1].value;
  55818. this.buttonX = this.browserGamepad.buttons[2].value;
  55819. this.buttonY = this.browserGamepad.buttons[3].value;
  55820. this.buttonLB = this.browserGamepad.buttons[4].value;
  55821. this.buttonRB = this.browserGamepad.buttons[5].value;
  55822. this.leftTrigger = this.browserGamepad.axes[2];
  55823. this.rightTrigger = this.browserGamepad.axes[5];
  55824. this.buttonBack = this.browserGamepad.buttons[9].value;
  55825. this.buttonStart = this.browserGamepad.buttons[8].value;
  55826. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55827. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55828. this.dPadUp = this.browserGamepad.buttons[11].value;
  55829. this.dPadDown = this.browserGamepad.buttons[12].value;
  55830. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55831. this.dPadRight = this.browserGamepad.buttons[14].value;
  55832. }
  55833. else {
  55834. this.buttonA = this.browserGamepad.buttons[0].value;
  55835. this.buttonB = this.browserGamepad.buttons[1].value;
  55836. this.buttonX = this.browserGamepad.buttons[2].value;
  55837. this.buttonY = this.browserGamepad.buttons[3].value;
  55838. this.buttonLB = this.browserGamepad.buttons[4].value;
  55839. this.buttonRB = this.browserGamepad.buttons[5].value;
  55840. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55841. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55842. this.buttonBack = this.browserGamepad.buttons[8].value;
  55843. this.buttonStart = this.browserGamepad.buttons[9].value;
  55844. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55845. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55846. this.dPadUp = this.browserGamepad.buttons[12].value;
  55847. this.dPadDown = this.browserGamepad.buttons[13].value;
  55848. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55849. this.dPadRight = this.browserGamepad.buttons[15].value;
  55850. }
  55851. };
  55852. return Xbox360Pad;
  55853. }(BABYLON.Gamepad));
  55854. BABYLON.Xbox360Pad = Xbox360Pad;
  55855. })(BABYLON || (BABYLON = {}));
  55856. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55857. var BABYLON;
  55858. (function (BABYLON) {
  55859. var PoseEnabledControllerType;
  55860. (function (PoseEnabledControllerType) {
  55861. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55862. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55863. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55864. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55865. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55866. var PoseEnabledControllerHelper = /** @class */ (function () {
  55867. function PoseEnabledControllerHelper() {
  55868. }
  55869. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55870. // Oculus Touch
  55871. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55872. return new BABYLON.OculusTouchController(vrGamepad);
  55873. }
  55874. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55875. return new BABYLON.WindowsMotionController(vrGamepad);
  55876. }
  55877. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55878. return new BABYLON.ViveController(vrGamepad);
  55879. }
  55880. else {
  55881. return new BABYLON.GenericController(vrGamepad);
  55882. }
  55883. };
  55884. return PoseEnabledControllerHelper;
  55885. }());
  55886. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55887. var PoseEnabledController = /** @class */ (function (_super) {
  55888. __extends(PoseEnabledController, _super);
  55889. function PoseEnabledController(browserGamepad) {
  55890. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55891. _this.deviceScaleFactor = 1;
  55892. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55893. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55894. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55895. _this.position = BABYLON.Vector3.Zero();
  55896. _this.rotationQuaternion = new BABYLON.Quaternion();
  55897. _this.devicePosition = BABYLON.Vector3.Zero();
  55898. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55899. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55900. _this._calculatedRotation = new BABYLON.Quaternion();
  55901. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55902. return _this;
  55903. }
  55904. PoseEnabledController.prototype.update = function () {
  55905. _super.prototype.update.call(this);
  55906. var pose = this.browserGamepad.pose;
  55907. this.updateFromDevice(pose);
  55908. if (this._mesh) {
  55909. this._mesh.position.copyFrom(this._calculatedPosition);
  55910. if (this._mesh.rotationQuaternion) {
  55911. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55912. }
  55913. }
  55914. };
  55915. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55916. if (poseData) {
  55917. this.rawPose = poseData;
  55918. if (poseData.position) {
  55919. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55920. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55921. this.devicePosition.z *= -1;
  55922. }
  55923. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55924. this._calculatedPosition.addInPlace(this.position);
  55925. }
  55926. var pose = this.rawPose;
  55927. if (poseData.orientation && pose.orientation) {
  55928. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55929. if (this._mesh) {
  55930. if (this._mesh.getScene().useRightHandedSystem) {
  55931. this.deviceRotationQuaternion.z *= -1;
  55932. this.deviceRotationQuaternion.w *= -1;
  55933. }
  55934. else {
  55935. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55936. }
  55937. }
  55938. // if the camera is set, rotate to the camera's rotation
  55939. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55940. }
  55941. }
  55942. };
  55943. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55944. if (this._mesh) {
  55945. this._mesh.parent = null;
  55946. }
  55947. this._mesh = mesh;
  55948. if (this._poseControlledCamera) {
  55949. this._mesh.parent = this._poseControlledCamera;
  55950. }
  55951. if (!this._mesh.rotationQuaternion) {
  55952. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55953. }
  55954. };
  55955. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55956. this._poseControlledCamera = camera;
  55957. if (this._mesh) {
  55958. this._mesh.parent = this._poseControlledCamera;
  55959. }
  55960. };
  55961. PoseEnabledController.prototype.dispose = function () {
  55962. if (this._mesh) {
  55963. this._mesh.dispose();
  55964. }
  55965. this._mesh = null;
  55966. _super.prototype.dispose.call(this);
  55967. };
  55968. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55969. get: function () {
  55970. return this._mesh;
  55971. },
  55972. enumerable: true,
  55973. configurable: true
  55974. });
  55975. PoseEnabledController.prototype.getForwardRay = function (length) {
  55976. if (length === void 0) { length = 100; }
  55977. if (!this.mesh) {
  55978. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55979. }
  55980. var m = this.mesh.getWorldMatrix();
  55981. var origin = m.getTranslation();
  55982. var forward = new BABYLON.Vector3(0, 0, -1);
  55983. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55984. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55985. return new BABYLON.Ray(origin, direction, length);
  55986. };
  55987. return PoseEnabledController;
  55988. }(BABYLON.Gamepad));
  55989. BABYLON.PoseEnabledController = PoseEnabledController;
  55990. })(BABYLON || (BABYLON = {}));
  55991. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55992. var BABYLON;
  55993. (function (BABYLON) {
  55994. var WebVRController = /** @class */ (function (_super) {
  55995. __extends(WebVRController, _super);
  55996. function WebVRController(vrGamepad) {
  55997. var _this = _super.call(this, vrGamepad) || this;
  55998. // Observables
  55999. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  56000. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  56001. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  56002. _this.onPadStateChangedObservable = new BABYLON.Observable();
  56003. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  56004. _this.pad = { x: 0, y: 0 };
  56005. // avoid GC, store state in a tmp object
  56006. _this._changes = {
  56007. pressChanged: false,
  56008. touchChanged: false,
  56009. valueChanged: false,
  56010. changed: false
  56011. };
  56012. _this._buttons = new Array(vrGamepad.buttons.length);
  56013. _this.hand = vrGamepad.hand;
  56014. return _this;
  56015. }
  56016. WebVRController.prototype.onButtonStateChange = function (callback) {
  56017. this._onButtonStateChange = callback;
  56018. };
  56019. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  56020. get: function () {
  56021. return this._defaultModel;
  56022. },
  56023. enumerable: true,
  56024. configurable: true
  56025. });
  56026. WebVRController.prototype.update = function () {
  56027. _super.prototype.update.call(this);
  56028. for (var index = 0; index < this._buttons.length; index++) {
  56029. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  56030. }
  56031. ;
  56032. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  56033. this.pad.x = this.leftStick.x;
  56034. this.pad.y = this.leftStick.y;
  56035. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  56036. }
  56037. };
  56038. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  56039. if (!newState) {
  56040. newState = {
  56041. pressed: false,
  56042. touched: false,
  56043. value: 0
  56044. };
  56045. }
  56046. if (!currentState) {
  56047. this._buttons[buttonIndex] = {
  56048. pressed: newState.pressed,
  56049. touched: newState.touched,
  56050. value: newState.value
  56051. };
  56052. return;
  56053. }
  56054. this._checkChanges(newState, currentState);
  56055. if (this._changes.changed) {
  56056. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  56057. this.handleButtonChange(buttonIndex, newState, this._changes);
  56058. }
  56059. this._buttons[buttonIndex].pressed = newState.pressed;
  56060. this._buttons[buttonIndex].touched = newState.touched;
  56061. // oculus triggers are never 0, thou not touched.
  56062. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  56063. };
  56064. WebVRController.prototype._checkChanges = function (newState, currentState) {
  56065. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  56066. this._changes.touchChanged = newState.touched !== currentState.touched;
  56067. this._changes.valueChanged = newState.value !== currentState.value;
  56068. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  56069. return this._changes;
  56070. };
  56071. WebVRController.prototype.dispose = function () {
  56072. _super.prototype.dispose.call(this);
  56073. this.onTriggerStateChangedObservable.clear();
  56074. this.onMainButtonStateChangedObservable.clear();
  56075. this.onSecondaryButtonStateChangedObservable.clear();
  56076. this.onPadStateChangedObservable.clear();
  56077. this.onPadValuesChangedObservable.clear();
  56078. };
  56079. return WebVRController;
  56080. }(BABYLON.PoseEnabledController));
  56081. BABYLON.WebVRController = WebVRController;
  56082. })(BABYLON || (BABYLON = {}));
  56083. //# sourceMappingURL=babylon.webVRController.js.map
  56084. var BABYLON;
  56085. (function (BABYLON) {
  56086. var OculusTouchController = /** @class */ (function (_super) {
  56087. __extends(OculusTouchController, _super);
  56088. function OculusTouchController(vrGamepad) {
  56089. var _this = _super.call(this, vrGamepad) || this;
  56090. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  56091. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  56092. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  56093. return _this;
  56094. }
  56095. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56096. var _this = this;
  56097. var meshName;
  56098. // Hand
  56099. if (this.hand === 'left') {
  56100. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  56101. }
  56102. else {
  56103. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  56104. }
  56105. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  56106. /*
  56107. Parent Mesh name: oculus_touch_left
  56108. - body
  56109. - trigger
  56110. - thumbstick
  56111. - grip
  56112. - button_y
  56113. - button_x
  56114. - button_enter
  56115. */
  56116. _this._defaultModel = newMeshes[1];
  56117. _this.attachToMesh(_this._defaultModel);
  56118. if (meshLoaded) {
  56119. meshLoaded(_this._defaultModel);
  56120. }
  56121. });
  56122. };
  56123. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  56124. // helper getters for left and right hand.
  56125. get: function () {
  56126. if (this.hand === 'right') {
  56127. return this.onMainButtonStateChangedObservable;
  56128. }
  56129. else {
  56130. throw new Error('No A button on left hand');
  56131. }
  56132. },
  56133. enumerable: true,
  56134. configurable: true
  56135. });
  56136. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  56137. get: function () {
  56138. if (this.hand === 'right') {
  56139. return this.onSecondaryButtonStateChangedObservable;
  56140. }
  56141. else {
  56142. throw new Error('No B button on left hand');
  56143. }
  56144. },
  56145. enumerable: true,
  56146. configurable: true
  56147. });
  56148. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  56149. get: function () {
  56150. if (this.hand === 'left') {
  56151. return this.onMainButtonStateChangedObservable;
  56152. }
  56153. else {
  56154. throw new Error('No X button on right hand');
  56155. }
  56156. },
  56157. enumerable: true,
  56158. configurable: true
  56159. });
  56160. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  56161. get: function () {
  56162. if (this.hand === 'left') {
  56163. return this.onSecondaryButtonStateChangedObservable;
  56164. }
  56165. else {
  56166. throw new Error('No Y button on right hand');
  56167. }
  56168. },
  56169. enumerable: true,
  56170. configurable: true
  56171. });
  56172. /*
  56173. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  56174. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  56175. 2) secondary trigger (same)
  56176. 3) A (right) X (left), touch, pressed = value
  56177. 4) B / Y
  56178. 5) thumb rest
  56179. */
  56180. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56181. var notifyObject = state; //{ state: state, changes: changes };
  56182. var triggerDirection = this.hand === 'right' ? -1 : 1;
  56183. switch (buttonIdx) {
  56184. case 0:
  56185. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56186. return;
  56187. case 1:// index trigger
  56188. if (this._defaultModel) {
  56189. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  56190. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  56191. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  56192. }
  56193. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56194. return;
  56195. case 2:// secondary trigger
  56196. if (this._defaultModel) {
  56197. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  56198. }
  56199. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  56200. return;
  56201. case 3:
  56202. if (this._defaultModel) {
  56203. if (notifyObject.pressed) {
  56204. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  56205. }
  56206. else {
  56207. (this._defaultModel.getChildren()[1]).position.y = 0;
  56208. }
  56209. }
  56210. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56211. return;
  56212. case 4:
  56213. if (this._defaultModel) {
  56214. if (notifyObject.pressed) {
  56215. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56216. }
  56217. else {
  56218. (this._defaultModel.getChildren()[2]).position.y = 0;
  56219. }
  56220. }
  56221. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56222. return;
  56223. case 5:
  56224. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  56225. return;
  56226. }
  56227. };
  56228. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  56229. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  56230. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  56231. return OculusTouchController;
  56232. }(BABYLON.WebVRController));
  56233. BABYLON.OculusTouchController = OculusTouchController;
  56234. })(BABYLON || (BABYLON = {}));
  56235. //# sourceMappingURL=babylon.oculusTouchController.js.map
  56236. var BABYLON;
  56237. (function (BABYLON) {
  56238. var ViveController = /** @class */ (function (_super) {
  56239. __extends(ViveController, _super);
  56240. function ViveController(vrGamepad) {
  56241. var _this = _super.call(this, vrGamepad) || this;
  56242. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  56243. return _this;
  56244. }
  56245. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56246. var _this = this;
  56247. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  56248. /*
  56249. Parent Mesh name: ViveWand
  56250. - body
  56251. - r_gripper
  56252. - l_gripper
  56253. - menu_button
  56254. - system_button
  56255. - trackpad
  56256. - trigger
  56257. - LED
  56258. */
  56259. _this._defaultModel = newMeshes[1];
  56260. _this.attachToMesh(_this._defaultModel);
  56261. if (meshLoaded) {
  56262. meshLoaded(_this._defaultModel);
  56263. }
  56264. });
  56265. };
  56266. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  56267. get: function () {
  56268. return this.onMainButtonStateChangedObservable;
  56269. },
  56270. enumerable: true,
  56271. configurable: true
  56272. });
  56273. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  56274. get: function () {
  56275. return this.onMainButtonStateChangedObservable;
  56276. },
  56277. enumerable: true,
  56278. configurable: true
  56279. });
  56280. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  56281. get: function () {
  56282. return this.onSecondaryButtonStateChangedObservable;
  56283. },
  56284. enumerable: true,
  56285. configurable: true
  56286. });
  56287. /**
  56288. * Vive mapping:
  56289. * 0: touchpad
  56290. * 1: trigger
  56291. * 2: left AND right buttons
  56292. * 3: menu button
  56293. */
  56294. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56295. var notifyObject = state; //{ state: state, changes: changes };
  56296. switch (buttonIdx) {
  56297. case 0:
  56298. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56299. return;
  56300. case 1:// index trigger
  56301. if (this._defaultModel) {
  56302. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  56303. }
  56304. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56305. return;
  56306. case 2:// left AND right button
  56307. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56308. return;
  56309. case 3:
  56310. if (this._defaultModel) {
  56311. if (notifyObject.pressed) {
  56312. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56313. }
  56314. else {
  56315. (this._defaultModel.getChildren()[2]).position.y = 0;
  56316. }
  56317. }
  56318. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56319. return;
  56320. }
  56321. };
  56322. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  56323. ViveController.MODEL_FILENAME = 'wand.babylon';
  56324. return ViveController;
  56325. }(BABYLON.WebVRController));
  56326. BABYLON.ViveController = ViveController;
  56327. })(BABYLON || (BABYLON = {}));
  56328. //# sourceMappingURL=babylon.viveController.js.map
  56329. var BABYLON;
  56330. (function (BABYLON) {
  56331. var GenericController = /** @class */ (function (_super) {
  56332. __extends(GenericController, _super);
  56333. function GenericController(vrGamepad) {
  56334. return _super.call(this, vrGamepad) || this;
  56335. }
  56336. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56337. var _this = this;
  56338. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  56339. _this._defaultModel = newMeshes[1];
  56340. _this.attachToMesh(_this._defaultModel);
  56341. if (meshLoaded) {
  56342. meshLoaded(_this._defaultModel);
  56343. }
  56344. });
  56345. };
  56346. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56347. console.log("Button id: " + buttonIdx + "state: ");
  56348. console.dir(state);
  56349. };
  56350. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  56351. GenericController.MODEL_FILENAME = 'generic.babylon';
  56352. return GenericController;
  56353. }(BABYLON.WebVRController));
  56354. BABYLON.GenericController = GenericController;
  56355. })(BABYLON || (BABYLON = {}));
  56356. //# sourceMappingURL=babylon.genericController.js.map
  56357. var BABYLON;
  56358. (function (BABYLON) {
  56359. var LoadedMeshInfo = /** @class */ (function () {
  56360. function LoadedMeshInfo() {
  56361. this.buttonMeshes = {};
  56362. this.axisMeshes = {};
  56363. }
  56364. return LoadedMeshInfo;
  56365. }());
  56366. var WindowsMotionController = /** @class */ (function (_super) {
  56367. __extends(WindowsMotionController, _super);
  56368. function WindowsMotionController(vrGamepad) {
  56369. var _this = _super.call(this, vrGamepad) || this;
  56370. _this._mapping = {
  56371. // Semantic button names
  56372. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  56373. // A mapping of the button name to glTF model node name
  56374. // that should be transformed by button value.
  56375. buttonMeshNames: {
  56376. 'trigger': 'SELECT',
  56377. 'menu': 'MENU',
  56378. 'grip': 'GRASP',
  56379. 'thumbstick': 'THUMBSTICK_PRESS',
  56380. 'trackpad': 'TOUCHPAD_PRESS'
  56381. },
  56382. // This mapping is used to translate from the Motion Controller to Babylon semantics
  56383. buttonObservableNames: {
  56384. 'trigger': 'onTriggerStateChangedObservable',
  56385. 'menu': 'onSecondaryButtonStateChangedObservable',
  56386. 'grip': 'onMainButtonStateChangedObservable',
  56387. 'thumbstick': 'onPadStateChangedObservable',
  56388. 'trackpad': 'onTrackpadChangedObservable'
  56389. },
  56390. // A mapping of the axis name to glTF model node name
  56391. // that should be transformed by axis value.
  56392. // This array mirrors the browserGamepad.axes array, such that
  56393. // the mesh corresponding to axis 0 is in this array index 0.
  56394. axisMeshNames: [
  56395. 'THUMBSTICK_X',
  56396. 'THUMBSTICK_Y',
  56397. 'TOUCHPAD_TOUCH_X',
  56398. 'TOUCHPAD_TOUCH_Y'
  56399. ],
  56400. pointingPoseMeshName: 'POINTING_POSE'
  56401. };
  56402. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  56403. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  56404. _this._loadedMeshInfo = null;
  56405. return _this;
  56406. }
  56407. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  56408. get: function () {
  56409. return this.onTriggerStateChangedObservable;
  56410. },
  56411. enumerable: true,
  56412. configurable: true
  56413. });
  56414. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  56415. get: function () {
  56416. return this.onSecondaryButtonStateChangedObservable;
  56417. },
  56418. enumerable: true,
  56419. configurable: true
  56420. });
  56421. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  56422. get: function () {
  56423. return this.onMainButtonStateChangedObservable;
  56424. },
  56425. enumerable: true,
  56426. configurable: true
  56427. });
  56428. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  56429. get: function () {
  56430. return this.onPadStateChangedObservable;
  56431. },
  56432. enumerable: true,
  56433. configurable: true
  56434. });
  56435. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  56436. get: function () {
  56437. return this.onTrackpadChangedObservable;
  56438. },
  56439. enumerable: true,
  56440. configurable: true
  56441. });
  56442. /**
  56443. * Called once per frame by the engine.
  56444. */
  56445. WindowsMotionController.prototype.update = function () {
  56446. _super.prototype.update.call(this);
  56447. // Only need to animate axes if there is a loaded mesh
  56448. if (this._loadedMeshInfo) {
  56449. if (this.browserGamepad.axes) {
  56450. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  56451. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  56452. }
  56453. }
  56454. }
  56455. };
  56456. /**
  56457. * Called once for each button that changed state since the last frame
  56458. * @param buttonIdx Which button index changed
  56459. * @param state New state of the button
  56460. * @param changes Which properties on the state changed since last frame
  56461. */
  56462. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56463. var buttonName = this._mapping.buttons[buttonIdx];
  56464. if (!buttonName) {
  56465. return;
  56466. }
  56467. // Only emit events for buttons that we know how to map from index to name
  56468. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  56469. if (observable) {
  56470. observable.notifyObservers(state);
  56471. }
  56472. this.lerpButtonTransform(buttonName, state.value);
  56473. };
  56474. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  56475. // If there is no loaded mesh, there is nothing to transform.
  56476. if (!this._loadedMeshInfo) {
  56477. return;
  56478. }
  56479. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  56480. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56481. return;
  56482. }
  56483. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  56484. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  56485. };
  56486. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  56487. if (!this._loadedMeshInfo) {
  56488. return;
  56489. }
  56490. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  56491. if (!meshInfo) {
  56492. return;
  56493. }
  56494. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56495. return;
  56496. }
  56497. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  56498. var lerpValue = axisValue * 0.5 + 0.5;
  56499. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  56500. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  56501. };
  56502. /**
  56503. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  56504. * @param scene scene in which to add meshes
  56505. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  56506. */
  56507. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  56508. var _this = this;
  56509. if (forceDefault === void 0) { forceDefault = false; }
  56510. var path;
  56511. var filename;
  56512. // Checking if GLB loader is present
  56513. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  56514. // Determine the device specific folder based on the ID suffix
  56515. var device = 'default';
  56516. if (this.id && !forceDefault) {
  56517. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  56518. device = ((match && match[0]) || device);
  56519. }
  56520. // Hand
  56521. if (this.hand === 'left') {
  56522. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  56523. }
  56524. else {
  56525. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  56526. }
  56527. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  56528. }
  56529. else {
  56530. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  56531. path = BABYLON.GenericController.MODEL_BASE_URL;
  56532. filename = BABYLON.GenericController.MODEL_FILENAME;
  56533. }
  56534. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  56535. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  56536. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  56537. if (!_this._loadedMeshInfo) {
  56538. return;
  56539. }
  56540. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  56541. _this.attachToMesh(_this._defaultModel);
  56542. if (meshLoaded) {
  56543. meshLoaded(_this._defaultModel);
  56544. }
  56545. }, null, function (scene, message) {
  56546. BABYLON.Tools.Log(message);
  56547. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  56548. if (!forceDefault) {
  56549. _this.initControllerMesh(scene, meshLoaded, true);
  56550. }
  56551. });
  56552. };
  56553. /**
  56554. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  56555. * can be transformed by button presses and axes values, based on this._mapping.
  56556. *
  56557. * @param scene scene in which the meshes exist
  56558. * @param meshes list of meshes that make up the controller model to process
  56559. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  56560. */
  56561. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  56562. var loadedMeshInfo = null;
  56563. // Create a new mesh to contain the glTF hierarchy
  56564. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  56565. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  56566. var childMesh = null;
  56567. for (var i = 0; i < meshes.length; i++) {
  56568. var mesh = meshes[i];
  56569. if (!mesh.parent) {
  56570. // Exclude controller meshes from picking results
  56571. mesh.isPickable = false;
  56572. // Handle root node, attach to the new parentMesh
  56573. childMesh = mesh;
  56574. break;
  56575. }
  56576. }
  56577. if (childMesh) {
  56578. childMesh.setParent(parentMesh);
  56579. // Create our mesh info. Note that this method will always return non-null.
  56580. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56581. }
  56582. else {
  56583. BABYLON.Tools.Warn('Could not find root node in model file.');
  56584. }
  56585. return loadedMeshInfo;
  56586. };
  56587. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56588. var loadedMeshInfo = new LoadedMeshInfo();
  56589. var i;
  56590. loadedMeshInfo.rootNode = rootNode;
  56591. // Reset the caches
  56592. loadedMeshInfo.buttonMeshes = {};
  56593. loadedMeshInfo.axisMeshes = {};
  56594. // Button Meshes
  56595. for (i = 0; i < this._mapping.buttons.length; i++) {
  56596. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56597. if (!buttonMeshName) {
  56598. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56599. continue;
  56600. }
  56601. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56602. if (!buttonMesh) {
  56603. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56604. continue;
  56605. }
  56606. var buttonMeshInfo = {
  56607. index: i,
  56608. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56609. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56610. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56611. };
  56612. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56613. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56614. }
  56615. else {
  56616. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56617. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56618. '(VALUE: ' + !!buttonMeshInfo.value +
  56619. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56620. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56621. ')');
  56622. }
  56623. }
  56624. // Axis Meshes
  56625. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56626. var axisMeshName = this._mapping.axisMeshNames[i];
  56627. if (!axisMeshName) {
  56628. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56629. continue;
  56630. }
  56631. var axisMesh = getChildByName(rootNode, axisMeshName);
  56632. if (!axisMesh) {
  56633. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56634. continue;
  56635. }
  56636. var axisMeshInfo = {
  56637. index: i,
  56638. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56639. min: getImmediateChildByName(axisMesh, 'MIN'),
  56640. max: getImmediateChildByName(axisMesh, 'MAX')
  56641. };
  56642. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56643. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56644. }
  56645. else {
  56646. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  56647. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  56648. '(VALUE: ' + !!axisMeshInfo.value +
  56649. ', MIN: ' + !!axisMeshInfo.min +
  56650. ', MAX:' + !!axisMeshInfo.max +
  56651. ')');
  56652. }
  56653. }
  56654. // Pointing Ray
  56655. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  56656. if (!loadedMeshInfo.pointingPoseNode) {
  56657. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  56658. }
  56659. return loadedMeshInfo;
  56660. // Look through all children recursively. This will return null if no mesh exists with the given name.
  56661. function getChildByName(node, name) {
  56662. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  56663. }
  56664. // Look through only immediate children. This will return null if no mesh exists with the given name.
  56665. function getImmediateChildByName(node, name) {
  56666. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  56667. }
  56668. };
  56669. WindowsMotionController.prototype.getForwardRay = function (length) {
  56670. if (length === void 0) { length = 100; }
  56671. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  56672. return _super.prototype.getForwardRay.call(this, length);
  56673. }
  56674. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  56675. var origin = m.getTranslation();
  56676. var forward = new BABYLON.Vector3(0, 0, -1);
  56677. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56678. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56679. return new BABYLON.Ray(origin, direction, length);
  56680. };
  56681. WindowsMotionController.prototype.dispose = function () {
  56682. _super.prototype.dispose.call(this);
  56683. this.onTrackpadChangedObservable.clear();
  56684. };
  56685. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  56686. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  56687. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  56688. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  56689. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  56690. return WindowsMotionController;
  56691. }(BABYLON.WebVRController));
  56692. BABYLON.WindowsMotionController = WindowsMotionController;
  56693. })(BABYLON || (BABYLON = {}));
  56694. //# sourceMappingURL=babylon.windowsMotionController.js.map
  56695. var BABYLON;
  56696. (function (BABYLON) {
  56697. var FollowCamera = /** @class */ (function (_super) {
  56698. __extends(FollowCamera, _super);
  56699. function FollowCamera(name, position, scene, lockedTarget) {
  56700. if (lockedTarget === void 0) { lockedTarget = null; }
  56701. var _this = _super.call(this, name, position, scene) || this;
  56702. _this.radius = 12;
  56703. _this.rotationOffset = 0;
  56704. _this.heightOffset = 4;
  56705. _this.cameraAcceleration = 0.05;
  56706. _this.maxCameraSpeed = 20;
  56707. _this.lockedTarget = lockedTarget;
  56708. return _this;
  56709. }
  56710. FollowCamera.prototype.getRadians = function (degrees) {
  56711. return degrees * Math.PI / 180;
  56712. };
  56713. FollowCamera.prototype.follow = function (cameraTarget) {
  56714. if (!cameraTarget)
  56715. return;
  56716. var yRotation;
  56717. if (cameraTarget.rotationQuaternion) {
  56718. var rotMatrix = new BABYLON.Matrix();
  56719. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  56720. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  56721. }
  56722. else {
  56723. yRotation = cameraTarget.rotation.y;
  56724. }
  56725. var radians = this.getRadians(this.rotationOffset) + yRotation;
  56726. var targetPosition = cameraTarget.getAbsolutePosition();
  56727. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  56728. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  56729. var dx = targetX - this.position.x;
  56730. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  56731. var dz = (targetZ) - this.position.z;
  56732. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  56733. var vy = dy * this.cameraAcceleration;
  56734. var vz = dz * this.cameraAcceleration * 2;
  56735. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  56736. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56737. }
  56738. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  56739. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56740. }
  56741. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  56742. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56743. }
  56744. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56745. this.setTarget(targetPosition);
  56746. };
  56747. FollowCamera.prototype._checkInputs = function () {
  56748. _super.prototype._checkInputs.call(this);
  56749. if (this.lockedTarget) {
  56750. this.follow(this.lockedTarget);
  56751. }
  56752. };
  56753. FollowCamera.prototype.getClassName = function () {
  56754. return "FollowCamera";
  56755. };
  56756. __decorate([
  56757. BABYLON.serialize()
  56758. ], FollowCamera.prototype, "radius", void 0);
  56759. __decorate([
  56760. BABYLON.serialize()
  56761. ], FollowCamera.prototype, "rotationOffset", void 0);
  56762. __decorate([
  56763. BABYLON.serialize()
  56764. ], FollowCamera.prototype, "heightOffset", void 0);
  56765. __decorate([
  56766. BABYLON.serialize()
  56767. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56768. __decorate([
  56769. BABYLON.serialize()
  56770. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56771. __decorate([
  56772. BABYLON.serializeAsMeshReference("lockedTargetId")
  56773. ], FollowCamera.prototype, "lockedTarget", void 0);
  56774. return FollowCamera;
  56775. }(BABYLON.TargetCamera));
  56776. BABYLON.FollowCamera = FollowCamera;
  56777. var ArcFollowCamera = /** @class */ (function (_super) {
  56778. __extends(ArcFollowCamera, _super);
  56779. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56780. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56781. _this.alpha = alpha;
  56782. _this.beta = beta;
  56783. _this.radius = radius;
  56784. _this.target = target;
  56785. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56786. _this.follow();
  56787. return _this;
  56788. }
  56789. ArcFollowCamera.prototype.follow = function () {
  56790. if (!this.target) {
  56791. return;
  56792. }
  56793. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56794. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56795. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56796. var targetPosition = this.target.getAbsolutePosition();
  56797. this.position = targetPosition.add(this._cartesianCoordinates);
  56798. this.setTarget(targetPosition);
  56799. };
  56800. ArcFollowCamera.prototype._checkInputs = function () {
  56801. _super.prototype._checkInputs.call(this);
  56802. this.follow();
  56803. };
  56804. ArcFollowCamera.prototype.getClassName = function () {
  56805. return "ArcFollowCamera";
  56806. };
  56807. return ArcFollowCamera;
  56808. }(BABYLON.TargetCamera));
  56809. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56810. })(BABYLON || (BABYLON = {}));
  56811. //# sourceMappingURL=babylon.followCamera.js.map
  56812. var BABYLON;
  56813. (function (BABYLON) {
  56814. // We're mainly based on the logic defined into the FreeCamera code
  56815. var UniversalCamera = /** @class */ (function (_super) {
  56816. __extends(UniversalCamera, _super);
  56817. //-- end properties for backward compatibility for inputs
  56818. function UniversalCamera(name, position, scene) {
  56819. var _this = _super.call(this, name, position, scene) || this;
  56820. _this.inputs.addGamepad();
  56821. return _this;
  56822. }
  56823. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56824. //-- Begin properties for backward compatibility for inputs
  56825. get: function () {
  56826. var gamepad = this.inputs.attached["gamepad"];
  56827. if (gamepad)
  56828. return gamepad.gamepadAngularSensibility;
  56829. return 0;
  56830. },
  56831. set: function (value) {
  56832. var gamepad = this.inputs.attached["gamepad"];
  56833. if (gamepad)
  56834. gamepad.gamepadAngularSensibility = value;
  56835. },
  56836. enumerable: true,
  56837. configurable: true
  56838. });
  56839. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56840. get: function () {
  56841. var gamepad = this.inputs.attached["gamepad"];
  56842. if (gamepad)
  56843. return gamepad.gamepadMoveSensibility;
  56844. return 0;
  56845. },
  56846. set: function (value) {
  56847. var gamepad = this.inputs.attached["gamepad"];
  56848. if (gamepad)
  56849. gamepad.gamepadMoveSensibility = value;
  56850. },
  56851. enumerable: true,
  56852. configurable: true
  56853. });
  56854. UniversalCamera.prototype.getClassName = function () {
  56855. return "UniversalCamera";
  56856. };
  56857. return UniversalCamera;
  56858. }(BABYLON.TouchCamera));
  56859. BABYLON.UniversalCamera = UniversalCamera;
  56860. })(BABYLON || (BABYLON = {}));
  56861. //# sourceMappingURL=babylon.universalCamera.js.map
  56862. var BABYLON;
  56863. (function (BABYLON) {
  56864. // We're mainly based on the logic defined into the FreeCamera code
  56865. var GamepadCamera = /** @class */ (function (_super) {
  56866. __extends(GamepadCamera, _super);
  56867. //-- end properties for backward compatibility for inputs
  56868. function GamepadCamera(name, position, scene) {
  56869. return _super.call(this, name, position, scene) || this;
  56870. }
  56871. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56872. //-- Begin properties for backward compatibility for inputs
  56873. get: function () {
  56874. var gamepad = this.inputs.attached["gamepad"];
  56875. if (gamepad)
  56876. return gamepad.gamepadAngularSensibility;
  56877. return 0;
  56878. },
  56879. set: function (value) {
  56880. var gamepad = this.inputs.attached["gamepad"];
  56881. if (gamepad)
  56882. gamepad.gamepadAngularSensibility = value;
  56883. },
  56884. enumerable: true,
  56885. configurable: true
  56886. });
  56887. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56888. get: function () {
  56889. var gamepad = this.inputs.attached["gamepad"];
  56890. if (gamepad)
  56891. return gamepad.gamepadMoveSensibility;
  56892. return 0;
  56893. },
  56894. set: function (value) {
  56895. var gamepad = this.inputs.attached["gamepad"];
  56896. if (gamepad)
  56897. gamepad.gamepadMoveSensibility = value;
  56898. },
  56899. enumerable: true,
  56900. configurable: true
  56901. });
  56902. GamepadCamera.prototype.getClassName = function () {
  56903. return "GamepadCamera";
  56904. };
  56905. return GamepadCamera;
  56906. }(BABYLON.UniversalCamera));
  56907. BABYLON.GamepadCamera = GamepadCamera;
  56908. })(BABYLON || (BABYLON = {}));
  56909. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56910. var BABYLON;
  56911. (function (BABYLON) {
  56912. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56913. function PostProcessRenderPipelineManager() {
  56914. this._renderPipelines = {};
  56915. }
  56916. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56917. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56918. };
  56919. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56920. if (unique === void 0) { unique = false; }
  56921. var renderPipeline = this._renderPipelines[renderPipelineName];
  56922. if (!renderPipeline) {
  56923. return;
  56924. }
  56925. renderPipeline._attachCameras(cameras, unique);
  56926. };
  56927. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56928. var renderPipeline = this._renderPipelines[renderPipelineName];
  56929. if (!renderPipeline) {
  56930. return;
  56931. }
  56932. renderPipeline._detachCameras(cameras);
  56933. };
  56934. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56935. var renderPipeline = this._renderPipelines[renderPipelineName];
  56936. if (!renderPipeline) {
  56937. return;
  56938. }
  56939. renderPipeline._enableEffect(renderEffectName, cameras);
  56940. };
  56941. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56942. var renderPipeline = this._renderPipelines[renderPipelineName];
  56943. if (!renderPipeline) {
  56944. return;
  56945. }
  56946. renderPipeline._disableEffect(renderEffectName, cameras);
  56947. };
  56948. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56949. var renderPipeline = this._renderPipelines[renderPipelineName];
  56950. if (!renderPipeline) {
  56951. return;
  56952. }
  56953. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56954. };
  56955. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56956. var renderPipeline = this._renderPipelines[renderPipelineName];
  56957. if (!renderPipeline) {
  56958. return;
  56959. }
  56960. renderPipeline._disableDisplayOnlyPass(cameras);
  56961. };
  56962. PostProcessRenderPipelineManager.prototype.update = function () {
  56963. for (var renderPipelineName in this._renderPipelines) {
  56964. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56965. var pipeline = this._renderPipelines[renderPipelineName];
  56966. if (!pipeline.isSupported) {
  56967. pipeline.dispose();
  56968. delete this._renderPipelines[renderPipelineName];
  56969. }
  56970. else {
  56971. pipeline._update();
  56972. }
  56973. }
  56974. }
  56975. };
  56976. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56977. for (var renderPipelineName in this._renderPipelines) {
  56978. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56979. var pipeline = this._renderPipelines[renderPipelineName];
  56980. pipeline._rebuild();
  56981. }
  56982. }
  56983. };
  56984. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56985. for (var renderPipelineName in this._renderPipelines) {
  56986. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56987. var pipeline = this._renderPipelines[renderPipelineName];
  56988. pipeline.dispose();
  56989. }
  56990. }
  56991. };
  56992. return PostProcessRenderPipelineManager;
  56993. }());
  56994. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56995. })(BABYLON || (BABYLON = {}));
  56996. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56997. var BABYLON;
  56998. (function (BABYLON) {
  56999. var PostProcessRenderPass = /** @class */ (function () {
  57000. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  57001. this._refCount = 0;
  57002. this._name = name;
  57003. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  57004. this.setRenderList(renderList);
  57005. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  57006. this._renderTexture.onAfterRenderObservable.add(afterRender);
  57007. this._scene = scene;
  57008. this._renderList = renderList;
  57009. }
  57010. // private
  57011. PostProcessRenderPass.prototype._incRefCount = function () {
  57012. if (this._refCount === 0) {
  57013. this._scene.customRenderTargets.push(this._renderTexture);
  57014. }
  57015. return ++this._refCount;
  57016. };
  57017. PostProcessRenderPass.prototype._decRefCount = function () {
  57018. this._refCount--;
  57019. if (this._refCount <= 0) {
  57020. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  57021. }
  57022. return this._refCount;
  57023. };
  57024. PostProcessRenderPass.prototype._update = function () {
  57025. this.setRenderList(this._renderList);
  57026. };
  57027. // public
  57028. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  57029. this._renderTexture.renderList = renderList;
  57030. };
  57031. PostProcessRenderPass.prototype.getRenderTexture = function () {
  57032. return this._renderTexture;
  57033. };
  57034. return PostProcessRenderPass;
  57035. }());
  57036. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  57037. })(BABYLON || (BABYLON = {}));
  57038. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  57039. var BABYLON;
  57040. (function (BABYLON) {
  57041. var PostProcessRenderEffect = /** @class */ (function () {
  57042. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  57043. this._engine = engine;
  57044. this._name = name;
  57045. this._singleInstance = singleInstance || true;
  57046. this._getPostProcess = getPostProcess;
  57047. this._cameras = {};
  57048. this._indicesForCamera = {};
  57049. this._postProcesses = {};
  57050. this._renderPasses = {};
  57051. this._renderEffectAsPasses = {};
  57052. }
  57053. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  57054. get: function () {
  57055. for (var index in this._postProcesses) {
  57056. if (!this._postProcesses[index].isSupported) {
  57057. return false;
  57058. }
  57059. }
  57060. return true;
  57061. },
  57062. enumerable: true,
  57063. configurable: true
  57064. });
  57065. PostProcessRenderEffect.prototype._update = function () {
  57066. for (var renderPassName in this._renderPasses) {
  57067. this._renderPasses[renderPassName]._update();
  57068. }
  57069. };
  57070. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  57071. this._renderPasses[renderPass._name] = renderPass;
  57072. this._linkParameters();
  57073. };
  57074. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  57075. delete this._renderPasses[renderPass._name];
  57076. this._linkParameters();
  57077. };
  57078. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  57079. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  57080. this._linkParameters();
  57081. };
  57082. PostProcessRenderEffect.prototype.getPass = function (passName) {
  57083. for (var renderPassName in this._renderPasses) {
  57084. if (renderPassName === passName) {
  57085. return this._renderPasses[passName];
  57086. }
  57087. }
  57088. return null;
  57089. };
  57090. PostProcessRenderEffect.prototype.emptyPasses = function () {
  57091. this._renderPasses = {};
  57092. this._linkParameters();
  57093. };
  57094. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  57095. var cameraKey;
  57096. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57097. if (!cams) {
  57098. return;
  57099. }
  57100. for (var i = 0; i < cams.length; i++) {
  57101. var camera = cams[i];
  57102. var cameraName = camera.name;
  57103. if (this._singleInstance) {
  57104. cameraKey = 0;
  57105. }
  57106. else {
  57107. cameraKey = cameraName;
  57108. }
  57109. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  57110. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  57111. if (!this._indicesForCamera[cameraName]) {
  57112. this._indicesForCamera[cameraName] = [];
  57113. }
  57114. this._indicesForCamera[cameraName].push(index);
  57115. if (!this._cameras[cameraName]) {
  57116. this._cameras[cameraName] = camera;
  57117. }
  57118. for (var passName in this._renderPasses) {
  57119. this._renderPasses[passName]._incRefCount();
  57120. }
  57121. }
  57122. this._linkParameters();
  57123. };
  57124. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  57125. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57126. if (!cams) {
  57127. return;
  57128. }
  57129. for (var i = 0; i < cams.length; i++) {
  57130. var camera = cams[i];
  57131. var cameraName = camera.name;
  57132. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57133. if (this._cameras[cameraName]) {
  57134. //this._indicesForCamera.splice(index, 1);
  57135. this._cameras[cameraName] = null;
  57136. }
  57137. for (var passName in this._renderPasses) {
  57138. this._renderPasses[passName]._decRefCount();
  57139. }
  57140. }
  57141. };
  57142. PostProcessRenderEffect.prototype._enable = function (cameras) {
  57143. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57144. if (!cams) {
  57145. return;
  57146. }
  57147. for (var i = 0; i < cams.length; i++) {
  57148. var camera = cams[i];
  57149. var cameraName = camera.name;
  57150. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  57151. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  57152. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  57153. }
  57154. }
  57155. for (var passName in this._renderPasses) {
  57156. this._renderPasses[passName]._incRefCount();
  57157. }
  57158. }
  57159. };
  57160. PostProcessRenderEffect.prototype._disable = function (cameras) {
  57161. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57162. if (!cams) {
  57163. return;
  57164. }
  57165. for (var i = 0; i < cams.length; i++) {
  57166. var camera = cams[i];
  57167. var cameraName = camera.Name;
  57168. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57169. for (var passName in this._renderPasses) {
  57170. this._renderPasses[passName]._decRefCount();
  57171. }
  57172. }
  57173. };
  57174. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  57175. if (this._singleInstance) {
  57176. return this._postProcesses[0];
  57177. }
  57178. else {
  57179. if (!camera) {
  57180. return null;
  57181. }
  57182. return this._postProcesses[camera.name];
  57183. }
  57184. };
  57185. PostProcessRenderEffect.prototype._linkParameters = function () {
  57186. var _this = this;
  57187. for (var index in this._postProcesses) {
  57188. if (this.applyParameters) {
  57189. this.applyParameters(this._postProcesses[index]);
  57190. }
  57191. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  57192. _this._linkTextures(effect);
  57193. });
  57194. }
  57195. };
  57196. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  57197. for (var renderPassName in this._renderPasses) {
  57198. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  57199. }
  57200. for (var renderEffectName in this._renderEffectAsPasses) {
  57201. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  57202. }
  57203. };
  57204. return PostProcessRenderEffect;
  57205. }());
  57206. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  57207. })(BABYLON || (BABYLON = {}));
  57208. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  57209. var BABYLON;
  57210. (function (BABYLON) {
  57211. var PostProcessRenderPipeline = /** @class */ (function () {
  57212. function PostProcessRenderPipeline(engine, name) {
  57213. this._engine = engine;
  57214. this._name = name;
  57215. this._renderEffects = {};
  57216. this._renderEffectsForIsolatedPass = new Array();
  57217. this._cameras = [];
  57218. }
  57219. PostProcessRenderPipeline.prototype.getClassName = function () {
  57220. return "PostProcessRenderPipeline";
  57221. };
  57222. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  57223. get: function () {
  57224. for (var renderEffectName in this._renderEffects) {
  57225. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57226. if (!this._renderEffects[renderEffectName].isSupported) {
  57227. return false;
  57228. }
  57229. }
  57230. }
  57231. return true;
  57232. },
  57233. enumerable: true,
  57234. configurable: true
  57235. });
  57236. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  57237. this._renderEffects[renderEffect._name] = renderEffect;
  57238. };
  57239. // private
  57240. PostProcessRenderPipeline.prototype._rebuild = function () {
  57241. };
  57242. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  57243. var renderEffects = this._renderEffects[renderEffectName];
  57244. if (!renderEffects) {
  57245. return;
  57246. }
  57247. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57248. };
  57249. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  57250. var renderEffects = this._renderEffects[renderEffectName];
  57251. if (!renderEffects) {
  57252. return;
  57253. }
  57254. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57255. };
  57256. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  57257. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57258. if (!cams) {
  57259. return;
  57260. }
  57261. var indicesToDelete = [];
  57262. var i;
  57263. for (i = 0; i < cams.length; i++) {
  57264. var camera = cams[i];
  57265. var cameraName = camera.name;
  57266. if (this._cameras.indexOf(camera) === -1) {
  57267. this._cameras[cameraName] = camera;
  57268. }
  57269. else if (unique) {
  57270. indicesToDelete.push(i);
  57271. }
  57272. }
  57273. for (i = 0; i < indicesToDelete.length; i++) {
  57274. cameras.splice(indicesToDelete[i], 1);
  57275. }
  57276. for (var renderEffectName in this._renderEffects) {
  57277. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57278. this._renderEffects[renderEffectName]._attachCameras(cams);
  57279. }
  57280. }
  57281. };
  57282. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  57283. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57284. if (!cams) {
  57285. return;
  57286. }
  57287. for (var renderEffectName in this._renderEffects) {
  57288. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57289. this._renderEffects[renderEffectName]._detachCameras(cams);
  57290. }
  57291. }
  57292. for (var i = 0; i < cams.length; i++) {
  57293. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  57294. }
  57295. };
  57296. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  57297. var _this = this;
  57298. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57299. if (!cams) {
  57300. return;
  57301. }
  57302. var pass = null;
  57303. var renderEffectName;
  57304. for (renderEffectName in this._renderEffects) {
  57305. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57306. pass = this._renderEffects[renderEffectName].getPass(passName);
  57307. if (pass != null) {
  57308. break;
  57309. }
  57310. }
  57311. }
  57312. if (pass === null) {
  57313. return;
  57314. }
  57315. for (renderEffectName in this._renderEffects) {
  57316. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57317. this._renderEffects[renderEffectName]._disable(cams);
  57318. }
  57319. }
  57320. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  57321. for (var i = 0; i < cams.length; i++) {
  57322. var camera = cams[i];
  57323. var cameraName = camera.name;
  57324. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  57325. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  57326. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  57327. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  57328. }
  57329. };
  57330. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  57331. var _this = this;
  57332. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57333. if (!cams) {
  57334. return;
  57335. }
  57336. for (var i = 0; i < cams.length; i++) {
  57337. var camera = cams[i];
  57338. var cameraName = camera.name;
  57339. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  57340. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  57341. }
  57342. for (var renderEffectName in this._renderEffects) {
  57343. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57344. this._renderEffects[renderEffectName]._enable(cams);
  57345. }
  57346. }
  57347. };
  57348. PostProcessRenderPipeline.prototype._update = function () {
  57349. for (var renderEffectName in this._renderEffects) {
  57350. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57351. this._renderEffects[renderEffectName]._update();
  57352. }
  57353. }
  57354. for (var i = 0; i < this._cameras.length; i++) {
  57355. var cameraName = this._cameras[i].name;
  57356. if (this._renderEffectsForIsolatedPass[cameraName]) {
  57357. this._renderEffectsForIsolatedPass[cameraName]._update();
  57358. }
  57359. }
  57360. };
  57361. PostProcessRenderPipeline.prototype._reset = function () {
  57362. this._renderEffects = {};
  57363. this._renderEffectsForIsolatedPass = new Array();
  57364. };
  57365. PostProcessRenderPipeline.prototype.dispose = function () {
  57366. // Must be implemented by children
  57367. };
  57368. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  57369. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  57370. __decorate([
  57371. BABYLON.serialize()
  57372. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  57373. return PostProcessRenderPipeline;
  57374. }());
  57375. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  57376. })(BABYLON || (BABYLON = {}));
  57377. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  57378. var BABYLON;
  57379. (function (BABYLON) {
  57380. var DepthRenderer = /** @class */ (function () {
  57381. function DepthRenderer(scene, type) {
  57382. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  57383. var _this = this;
  57384. this._scene = scene;
  57385. var engine = scene.getEngine();
  57386. // Render target
  57387. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  57388. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57389. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57390. this._depthMap.refreshRate = 1;
  57391. this._depthMap.renderParticles = false;
  57392. this._depthMap.renderList = null;
  57393. // set default depth value to 1.0 (far away)
  57394. this._depthMap.onClearObservable.add(function (engine) {
  57395. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  57396. });
  57397. // Custom render function
  57398. var renderSubMesh = function (subMesh) {
  57399. var mesh = subMesh.getRenderingMesh();
  57400. var scene = _this._scene;
  57401. var engine = scene.getEngine();
  57402. var material = subMesh.getMaterial();
  57403. if (!material) {
  57404. return;
  57405. }
  57406. // Culling
  57407. engine.setState(material.backFaceCulling);
  57408. // Managing instances
  57409. var batch = mesh._getInstancesRenderList(subMesh._id);
  57410. if (batch.mustReturn) {
  57411. return;
  57412. }
  57413. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57414. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  57415. engine.enableEffect(_this._effect);
  57416. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57417. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57418. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  57419. // Alpha test
  57420. if (material && material.needAlphaTesting()) {
  57421. var alphaTexture = material.getAlphaTestTexture();
  57422. if (alphaTexture) {
  57423. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57424. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57425. }
  57426. }
  57427. // Bones
  57428. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57429. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57430. }
  57431. // Draw
  57432. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57433. }
  57434. };
  57435. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57436. var index;
  57437. if (depthOnlySubMeshes.length) {
  57438. engine.setColorWrite(false);
  57439. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57440. renderSubMesh(depthOnlySubMeshes.data[index]);
  57441. }
  57442. engine.setColorWrite(true);
  57443. }
  57444. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57445. renderSubMesh(opaqueSubMeshes.data[index]);
  57446. }
  57447. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57448. renderSubMesh(alphaTestSubMeshes.data[index]);
  57449. }
  57450. };
  57451. }
  57452. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  57453. var material = subMesh.getMaterial();
  57454. if (material.disableDepthWrite) {
  57455. return false;
  57456. }
  57457. var defines = [];
  57458. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57459. var mesh = subMesh.getMesh();
  57460. // Alpha test
  57461. if (material && material.needAlphaTesting()) {
  57462. defines.push("#define ALPHATEST");
  57463. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57464. attribs.push(BABYLON.VertexBuffer.UVKind);
  57465. defines.push("#define UV1");
  57466. }
  57467. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57468. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57469. defines.push("#define UV2");
  57470. }
  57471. }
  57472. // Bones
  57473. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57474. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57475. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57476. if (mesh.numBoneInfluencers > 4) {
  57477. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57478. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57479. }
  57480. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57481. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  57482. }
  57483. else {
  57484. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57485. }
  57486. // Instances
  57487. if (useInstances) {
  57488. defines.push("#define INSTANCES");
  57489. attribs.push("world0");
  57490. attribs.push("world1");
  57491. attribs.push("world2");
  57492. attribs.push("world3");
  57493. }
  57494. // Get correct effect
  57495. var join = defines.join("\n");
  57496. if (this._cachedDefines !== join) {
  57497. this._cachedDefines = join;
  57498. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  57499. }
  57500. return this._effect.isReady();
  57501. };
  57502. DepthRenderer.prototype.getDepthMap = function () {
  57503. return this._depthMap;
  57504. };
  57505. // Methods
  57506. DepthRenderer.prototype.dispose = function () {
  57507. this._depthMap.dispose();
  57508. };
  57509. return DepthRenderer;
  57510. }());
  57511. BABYLON.DepthRenderer = DepthRenderer;
  57512. })(BABYLON || (BABYLON = {}));
  57513. //# sourceMappingURL=babylon.depthRenderer.js.map
  57514. var BABYLON;
  57515. (function (BABYLON) {
  57516. var SSAORenderingPipeline = /** @class */ (function (_super) {
  57517. __extends(SSAORenderingPipeline, _super);
  57518. /**
  57519. * @constructor
  57520. * @param {string} name - The rendering pipeline name
  57521. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57522. * @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 }
  57523. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57524. */
  57525. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  57526. var _this = _super.call(this, scene.getEngine(), name) || this;
  57527. // Members
  57528. /**
  57529. * The PassPostProcess id in the pipeline that contains the original scene color
  57530. * @type {string}
  57531. */
  57532. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57533. /**
  57534. * The SSAO PostProcess id in the pipeline
  57535. * @type {string}
  57536. */
  57537. _this.SSAORenderEffect = "SSAORenderEffect";
  57538. /**
  57539. * The horizontal blur PostProcess id in the pipeline
  57540. * @type {string}
  57541. */
  57542. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57543. /**
  57544. * The vertical blur PostProcess id in the pipeline
  57545. * @type {string}
  57546. */
  57547. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57548. /**
  57549. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57550. * @type {string}
  57551. */
  57552. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57553. /**
  57554. * The output strength of the SSAO post-process. Default value is 1.0.
  57555. * @type {number}
  57556. */
  57557. _this.totalStrength = 1.0;
  57558. /**
  57559. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  57560. * @type {number}
  57561. */
  57562. _this.radius = 0.0001;
  57563. /**
  57564. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  57565. * Must not be equal to fallOff and superior to fallOff.
  57566. * Default value is 0.975
  57567. * @type {number}
  57568. */
  57569. _this.area = 0.0075;
  57570. /**
  57571. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  57572. * Must not be equal to area and inferior to area.
  57573. * Default value is 0.0
  57574. * @type {number}
  57575. */
  57576. _this.fallOff = 0.000001;
  57577. /**
  57578. * The base color of the SSAO post-process
  57579. * The final result is "base + ssao" between [0, 1]
  57580. * @type {number}
  57581. */
  57582. _this.base = 0.5;
  57583. _this._firstUpdate = true;
  57584. _this._scene = scene;
  57585. // Set up assets
  57586. _this._createRandomTexture();
  57587. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57588. var ssaoRatio = ratio.ssaoRatio || ratio;
  57589. var combineRatio = ratio.combineRatio || ratio;
  57590. _this._ratio = {
  57591. ssaoRatio: ssaoRatio,
  57592. combineRatio: combineRatio
  57593. };
  57594. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57595. _this._createSSAOPostProcess(ssaoRatio);
  57596. _this._createBlurPostProcess(ssaoRatio);
  57597. _this._createSSAOCombinePostProcess(combineRatio);
  57598. // Set up pipeline
  57599. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57600. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57601. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57602. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57603. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57604. // Finish
  57605. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57606. if (cameras)
  57607. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57608. return _this;
  57609. }
  57610. // Public Methods
  57611. /**
  57612. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57613. */
  57614. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57615. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57616. for (var i = 0; i < this._scene.cameras.length; i++) {
  57617. var camera = this._scene.cameras[i];
  57618. this._originalColorPostProcess.dispose(camera);
  57619. this._ssaoPostProcess.dispose(camera);
  57620. this._blurHPostProcess.dispose(camera);
  57621. this._blurVPostProcess.dispose(camera);
  57622. this._ssaoCombinePostProcess.dispose(camera);
  57623. }
  57624. this._randomTexture.dispose();
  57625. if (disableDepthRender)
  57626. this._scene.disableDepthRenderer();
  57627. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57628. _super.prototype.dispose.call(this);
  57629. };
  57630. // Private Methods
  57631. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57632. var _this = this;
  57633. /*
  57634. var samplerOffsets = [
  57635. -8.0, -6.0, -4.0, -2.0,
  57636. 0.0,
  57637. 2.0, 4.0, 6.0, 8.0
  57638. ];
  57639. */
  57640. var samplerOffsets = new Array();
  57641. for (var i = -8; i < 8; i++) {
  57642. samplerOffsets.push(i * 2);
  57643. }
  57644. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  57645. this._blurHPostProcess.onApply = function (effect) {
  57646. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57647. effect.setTexture("depthSampler", _this._depthTexture);
  57648. if (_this._firstUpdate) {
  57649. effect.setArray("samplerOffsets", samplerOffsets);
  57650. }
  57651. };
  57652. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  57653. this._blurVPostProcess.onApply = function (effect) {
  57654. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57655. effect.setTexture("depthSampler", _this._depthTexture);
  57656. if (_this._firstUpdate) {
  57657. effect.setArray("samplerOffsets", samplerOffsets);
  57658. _this._firstUpdate = false;
  57659. }
  57660. };
  57661. };
  57662. SSAORenderingPipeline.prototype._rebuild = function () {
  57663. this._firstUpdate = true;
  57664. _super.prototype._rebuild.call(this);
  57665. };
  57666. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57667. var _this = this;
  57668. var numSamples = 16;
  57669. var sampleSphere = [
  57670. 0.5381, 0.1856, -0.4319,
  57671. 0.1379, 0.2486, 0.4430,
  57672. 0.3371, 0.5679, -0.0057,
  57673. -0.6999, -0.0451, -0.0019,
  57674. 0.0689, -0.1598, -0.8547,
  57675. 0.0560, 0.0069, -0.1843,
  57676. -0.0146, 0.1402, 0.0762,
  57677. 0.0100, -0.1924, -0.0344,
  57678. -0.3577, -0.5301, -0.4358,
  57679. -0.3169, 0.1063, 0.0158,
  57680. 0.0103, -0.5869, 0.0046,
  57681. -0.0897, -0.4940, 0.3287,
  57682. 0.7119, -0.0154, -0.0918,
  57683. -0.0533, 0.0596, -0.5411,
  57684. 0.0352, -0.0631, 0.5460,
  57685. -0.4776, 0.2847, -0.0271
  57686. ];
  57687. var samplesFactor = 1.0 / numSamples;
  57688. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  57689. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57690. "area", "fallOff", "base", "range", "viewport"
  57691. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57692. this._ssaoPostProcess.onApply = function (effect) {
  57693. if (_this._firstUpdate) {
  57694. effect.setArray3("sampleSphere", sampleSphere);
  57695. effect.setFloat("samplesFactor", samplesFactor);
  57696. effect.setFloat("randTextureTiles", 4.0);
  57697. }
  57698. effect.setFloat("totalStrength", _this.totalStrength);
  57699. effect.setFloat("radius", _this.radius);
  57700. effect.setFloat("area", _this.area);
  57701. effect.setFloat("fallOff", _this.fallOff);
  57702. effect.setFloat("base", _this.base);
  57703. effect.setTexture("textureSampler", _this._depthTexture);
  57704. effect.setTexture("randomSampler", _this._randomTexture);
  57705. };
  57706. };
  57707. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57708. var _this = this;
  57709. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57710. this._ssaoCombinePostProcess.onApply = function (effect) {
  57711. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57712. };
  57713. };
  57714. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  57715. var size = 512;
  57716. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57717. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57718. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57719. var context = this._randomTexture.getContext();
  57720. var rand = function (min, max) {
  57721. return Math.random() * (max - min) + min;
  57722. };
  57723. var randVector = BABYLON.Vector3.Zero();
  57724. for (var x = 0; x < size; x++) {
  57725. for (var y = 0; y < size; y++) {
  57726. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  57727. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  57728. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  57729. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57730. context.fillRect(x, y, 1, 1);
  57731. }
  57732. }
  57733. this._randomTexture.update(false);
  57734. };
  57735. __decorate([
  57736. BABYLON.serialize()
  57737. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  57738. __decorate([
  57739. BABYLON.serialize()
  57740. ], SSAORenderingPipeline.prototype, "radius", void 0);
  57741. __decorate([
  57742. BABYLON.serialize()
  57743. ], SSAORenderingPipeline.prototype, "area", void 0);
  57744. __decorate([
  57745. BABYLON.serialize()
  57746. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57747. __decorate([
  57748. BABYLON.serialize()
  57749. ], SSAORenderingPipeline.prototype, "base", void 0);
  57750. __decorate([
  57751. BABYLON.serialize()
  57752. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57753. return SSAORenderingPipeline;
  57754. }(BABYLON.PostProcessRenderPipeline));
  57755. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57756. })(BABYLON || (BABYLON = {}));
  57757. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57758. var BABYLON;
  57759. (function (BABYLON) {
  57760. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57761. __extends(SSAO2RenderingPipeline, _super);
  57762. /**
  57763. * @constructor
  57764. * @param {string} name - The rendering pipeline name
  57765. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57766. * @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 }
  57767. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57768. */
  57769. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57770. var _this = _super.call(this, scene.getEngine(), name) || this;
  57771. // Members
  57772. /**
  57773. * The PassPostProcess id in the pipeline that contains the original scene color
  57774. * @type {string}
  57775. */
  57776. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57777. /**
  57778. * The SSAO PostProcess id in the pipeline
  57779. * @type {string}
  57780. */
  57781. _this.SSAORenderEffect = "SSAORenderEffect";
  57782. /**
  57783. * The horizontal blur PostProcess id in the pipeline
  57784. * @type {string}
  57785. */
  57786. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57787. /**
  57788. * The vertical blur PostProcess id in the pipeline
  57789. * @type {string}
  57790. */
  57791. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57792. /**
  57793. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57794. * @type {string}
  57795. */
  57796. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57797. /**
  57798. * The output strength of the SSAO post-process. Default value is 1.0.
  57799. * @type {number}
  57800. */
  57801. _this.totalStrength = 1.0;
  57802. /**
  57803. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57804. * @type {number}
  57805. */
  57806. _this.maxZ = 100.0;
  57807. /**
  57808. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57809. * @type {number}
  57810. */
  57811. _this.minZAspect = 0.2;
  57812. /**
  57813. * Number of samples used for the SSAO calculations. Default value is 8
  57814. * @type {number}
  57815. */
  57816. _this._samples = 8;
  57817. /**
  57818. * Are we using bilateral blur ?
  57819. * @type {boolean}
  57820. */
  57821. _this._expensiveBlur = true;
  57822. /**
  57823. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57824. * @type {number}
  57825. */
  57826. _this.radius = 2.0;
  57827. /**
  57828. * The base color of the SSAO post-process
  57829. * The final result is "base + ssao" between [0, 1]
  57830. * @type {number}
  57831. */
  57832. _this.base = 0.1;
  57833. _this._firstUpdate = true;
  57834. _this._scene = scene;
  57835. if (!_this.isSupported) {
  57836. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57837. return _this;
  57838. }
  57839. var ssaoRatio = ratio.ssaoRatio || ratio;
  57840. var blurRatio = ratio.blurRatio || ratio;
  57841. _this._ratio = {
  57842. ssaoRatio: ssaoRatio,
  57843. blurRatio: blurRatio
  57844. };
  57845. // Set up assets
  57846. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57847. _this._createRandomTexture();
  57848. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57849. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57850. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57851. _this._createSSAOPostProcess(1.0);
  57852. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57853. _this._createSSAOCombinePostProcess(blurRatio);
  57854. // Set up pipeline
  57855. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57856. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57857. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57858. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57859. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57860. // Finish
  57861. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57862. if (cameras)
  57863. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57864. return _this;
  57865. }
  57866. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57867. get: function () {
  57868. return this._samples;
  57869. },
  57870. set: function (n) {
  57871. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57872. this._samples = n;
  57873. this._sampleSphere = this._generateHemisphere();
  57874. this._firstUpdate = true;
  57875. },
  57876. enumerable: true,
  57877. configurable: true
  57878. });
  57879. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57880. get: function () {
  57881. return this._expensiveBlur;
  57882. },
  57883. set: function (b) {
  57884. 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"]);
  57885. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57886. this._expensiveBlur = b;
  57887. this._firstUpdate = true;
  57888. },
  57889. enumerable: true,
  57890. configurable: true
  57891. });
  57892. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57893. /**
  57894. * Support test.
  57895. * @type {boolean}
  57896. */
  57897. get: function () {
  57898. var engine = BABYLON.Engine.LastCreatedEngine;
  57899. if (!engine) {
  57900. return false;
  57901. }
  57902. return engine.getCaps().drawBuffersExtension;
  57903. },
  57904. enumerable: true,
  57905. configurable: true
  57906. });
  57907. // Public Methods
  57908. /**
  57909. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57910. */
  57911. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57912. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57913. for (var i = 0; i < this._scene.cameras.length; i++) {
  57914. var camera = this._scene.cameras[i];
  57915. this._originalColorPostProcess.dispose(camera);
  57916. this._ssaoPostProcess.dispose(camera);
  57917. this._blurHPostProcess.dispose(camera);
  57918. this._blurVPostProcess.dispose(camera);
  57919. this._ssaoCombinePostProcess.dispose(camera);
  57920. }
  57921. this._randomTexture.dispose();
  57922. if (disableGeometryBufferRenderer)
  57923. this._scene.disableGeometryBufferRenderer();
  57924. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57925. _super.prototype.dispose.call(this);
  57926. };
  57927. // Private Methods
  57928. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57929. var _this = this;
  57930. this._samplerOffsets = [];
  57931. var expensive = this.expensiveBlur;
  57932. for (var i = -8; i < 8; i++) {
  57933. this._samplerOffsets.push(i * 2 + 0.5);
  57934. }
  57935. 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");
  57936. this._blurHPostProcess.onApply = function (effect) {
  57937. if (!_this._scene.activeCamera) {
  57938. return;
  57939. }
  57940. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  57941. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57942. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57943. effect.setFloat("radius", _this.radius);
  57944. effect.setTexture("depthSampler", _this._depthTexture);
  57945. if (_this._firstUpdate) {
  57946. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57947. }
  57948. };
  57949. 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");
  57950. this._blurVPostProcess.onApply = function (effect) {
  57951. if (!_this._scene.activeCamera) {
  57952. return;
  57953. }
  57954. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  57955. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57956. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57957. effect.setFloat("radius", _this.radius);
  57958. effect.setTexture("depthSampler", _this._depthTexture);
  57959. if (_this._firstUpdate) {
  57960. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57961. _this._firstUpdate = false;
  57962. }
  57963. };
  57964. };
  57965. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57966. this._firstUpdate = true;
  57967. _super.prototype._rebuild.call(this);
  57968. };
  57969. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57970. var numSamples = this.samples;
  57971. var result = [];
  57972. var vector, scale;
  57973. var rand = function (min, max) {
  57974. return Math.random() * (max - min) + min;
  57975. };
  57976. var i = 0;
  57977. while (i < numSamples) {
  57978. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57979. vector.normalize();
  57980. scale = i / numSamples;
  57981. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57982. vector.scaleInPlace(scale);
  57983. result.push(vector.x, vector.y, vector.z);
  57984. i++;
  57985. }
  57986. return result;
  57987. };
  57988. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57989. var _this = this;
  57990. var numSamples = this.samples;
  57991. this._sampleSphere = this._generateHemisphere();
  57992. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57993. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57994. "base", "range", "projection", "near", "far", "texelSize",
  57995. "xViewport", "yViewport", "maxZ", "minZAspect"
  57996. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57997. this._ssaoPostProcess.onApply = function (effect) {
  57998. if (_this._firstUpdate) {
  57999. effect.setArray3("sampleSphere", _this._sampleSphere);
  58000. effect.setFloat("randTextureTiles", 4.0);
  58001. }
  58002. if (!_this._scene.activeCamera) {
  58003. return;
  58004. }
  58005. effect.setFloat("samplesFactor", 1 / _this.samples);
  58006. effect.setFloat("totalStrength", _this.totalStrength);
  58007. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  58008. effect.setFloat("radius", _this.radius);
  58009. effect.setFloat("maxZ", _this.maxZ);
  58010. effect.setFloat("minZAspect", _this.minZAspect);
  58011. effect.setFloat("base", _this.base);
  58012. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58013. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58014. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  58015. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  58016. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  58017. effect.setTexture("textureSampler", _this._depthTexture);
  58018. effect.setTexture("normalSampler", _this._normalTexture);
  58019. effect.setTexture("randomSampler", _this._randomTexture);
  58020. };
  58021. };
  58022. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58023. var _this = this;
  58024. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58025. this._ssaoCombinePostProcess.onApply = function (effect) {
  58026. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58027. };
  58028. };
  58029. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  58030. var size = 512;
  58031. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58032. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58033. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58034. var context = this._randomTexture.getContext();
  58035. var rand = function (min, max) {
  58036. return Math.random() * (max - min) + min;
  58037. };
  58038. var randVector = BABYLON.Vector3.Zero();
  58039. for (var x = 0; x < size; x++) {
  58040. for (var y = 0; y < size; y++) {
  58041. randVector.x = rand(0.0, 1.0);
  58042. randVector.y = rand(0.0, 1.0);
  58043. randVector.z = 0.0;
  58044. randVector.normalize();
  58045. randVector.scaleInPlace(255);
  58046. randVector.x = Math.floor(randVector.x);
  58047. randVector.y = Math.floor(randVector.y);
  58048. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58049. context.fillRect(x, y, 1, 1);
  58050. }
  58051. }
  58052. this._randomTexture.update(false);
  58053. };
  58054. __decorate([
  58055. BABYLON.serialize()
  58056. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  58057. __decorate([
  58058. BABYLON.serialize()
  58059. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  58060. __decorate([
  58061. BABYLON.serialize()
  58062. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  58063. __decorate([
  58064. BABYLON.serialize("samples")
  58065. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  58066. __decorate([
  58067. BABYLON.serialize("expensiveBlur")
  58068. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  58069. __decorate([
  58070. BABYLON.serialize()
  58071. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  58072. __decorate([
  58073. BABYLON.serialize()
  58074. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  58075. __decorate([
  58076. BABYLON.serialize()
  58077. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  58078. return SSAO2RenderingPipeline;
  58079. }(BABYLON.PostProcessRenderPipeline));
  58080. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  58081. })(BABYLON || (BABYLON = {}));
  58082. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  58083. // BABYLON.JS Chromatic Aberration GLSL Shader
  58084. // Author: Olivier Guyot
  58085. // Separates very slightly R, G and B colors on the edges of the screen
  58086. // Inspired by Francois Tarlier & Martins Upitis
  58087. var BABYLON;
  58088. (function (BABYLON) {
  58089. var LensRenderingPipeline = /** @class */ (function (_super) {
  58090. __extends(LensRenderingPipeline, _super);
  58091. /**
  58092. * @constructor
  58093. *
  58094. * Effect parameters are as follow:
  58095. * {
  58096. * chromatic_aberration: number; // from 0 to x (1 for realism)
  58097. * edge_blur: number; // from 0 to x (1 for realism)
  58098. * distortion: number; // from 0 to x (1 for realism)
  58099. * grain_amount: number; // from 0 to 1
  58100. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  58101. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  58102. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  58103. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  58104. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  58105. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  58106. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  58107. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  58108. * }
  58109. * Note: if an effect parameter is unset, effect is disabled
  58110. *
  58111. * @param {string} name - The rendering pipeline name
  58112. * @param {object} parameters - An object containing all parameters (see above)
  58113. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58114. * @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)
  58115. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58116. */
  58117. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  58118. if (ratio === void 0) { ratio = 1.0; }
  58119. var _this = _super.call(this, scene.getEngine(), name) || this;
  58120. // Lens effects can be of the following:
  58121. // - chromatic aberration (slight shift of RGB colors)
  58122. // - blur on the edge of the lens
  58123. // - lens distortion
  58124. // - depth-of-field blur & highlights enhancing
  58125. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  58126. // - grain effect (noise or custom texture)
  58127. // Two additional texture samplers are needed:
  58128. // - depth map (for depth-of-field)
  58129. // - grain texture
  58130. /**
  58131. * The chromatic aberration PostProcess id in the pipeline
  58132. * @type {string}
  58133. */
  58134. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  58135. /**
  58136. * The highlights enhancing PostProcess id in the pipeline
  58137. * @type {string}
  58138. */
  58139. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  58140. /**
  58141. * The depth-of-field PostProcess id in the pipeline
  58142. * @type {string}
  58143. */
  58144. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  58145. _this._scene = scene;
  58146. // Fetch texture samplers
  58147. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58148. if (parameters.grain_texture) {
  58149. _this._grainTexture = parameters.grain_texture;
  58150. }
  58151. else {
  58152. _this._createGrainTexture();
  58153. }
  58154. // save parameters
  58155. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  58156. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  58157. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  58158. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  58159. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  58160. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  58161. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  58162. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  58163. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  58164. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  58165. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  58166. // Create effects
  58167. _this._createChromaticAberrationPostProcess(ratio);
  58168. _this._createHighlightsPostProcess(ratio);
  58169. _this._createDepthOfFieldPostProcess(ratio / 4);
  58170. // Set up pipeline
  58171. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  58172. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  58173. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  58174. if (_this._highlightsGain === -1) {
  58175. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  58176. }
  58177. // Finish
  58178. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58179. if (cameras) {
  58180. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58181. }
  58182. return _this;
  58183. }
  58184. // public methods (self explanatory)
  58185. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  58186. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  58187. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  58188. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  58189. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  58190. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  58191. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  58192. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  58193. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  58194. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  58195. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  58196. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  58197. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  58198. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  58199. };
  58200. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  58201. this._highlightsPostProcess.updateEffect();
  58202. };
  58203. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  58204. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  58205. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  58206. this._highlightsGain = amount;
  58207. };
  58208. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  58209. if (this._highlightsGain === -1) {
  58210. this._highlightsGain = 1.0;
  58211. }
  58212. this._highlightsThreshold = amount;
  58213. };
  58214. LensRenderingPipeline.prototype.disableHighlights = function () {
  58215. this._highlightsGain = -1;
  58216. };
  58217. /**
  58218. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  58219. */
  58220. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58221. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58222. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58223. this._chromaticAberrationPostProcess = null;
  58224. this._highlightsPostProcess = null;
  58225. this._depthOfFieldPostProcess = null;
  58226. this._grainTexture.dispose();
  58227. if (disableDepthRender)
  58228. this._scene.disableDepthRenderer();
  58229. };
  58230. // colors shifting and distortion
  58231. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  58232. var _this = this;
  58233. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  58234. [], // samplers
  58235. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58236. this._chromaticAberrationPostProcess.onApply = function (effect) {
  58237. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  58238. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58239. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58240. };
  58241. };
  58242. // highlights enhancing
  58243. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  58244. var _this = this;
  58245. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  58246. [], // samplers
  58247. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  58248. this._highlightsPostProcess.onApply = function (effect) {
  58249. effect.setFloat('gain', _this._highlightsGain);
  58250. effect.setFloat('threshold', _this._highlightsThreshold);
  58251. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  58252. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58253. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58254. };
  58255. };
  58256. // colors shifting and distortion
  58257. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  58258. var _this = this;
  58259. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  58260. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  58261. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  58262. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58263. this._depthOfFieldPostProcess.onApply = function (effect) {
  58264. effect.setTexture("depthSampler", _this._depthTexture);
  58265. effect.setTexture("grainSampler", _this._grainTexture);
  58266. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  58267. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  58268. effect.setFloat('grain_amount', _this._grainAmount);
  58269. effect.setBool('blur_noise', _this._blurNoise);
  58270. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58271. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58272. effect.setFloat('distortion', _this._distortion);
  58273. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  58274. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  58275. effect.setFloat('aperture', _this._dofAperture);
  58276. effect.setFloat('darken', _this._dofDarken);
  58277. effect.setFloat('edge_blur', _this._edgeBlur);
  58278. effect.setBool('highlights', (_this._highlightsGain !== -1));
  58279. if (_this._scene.activeCamera) {
  58280. effect.setFloat('near', _this._scene.activeCamera.minZ);
  58281. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  58282. }
  58283. };
  58284. };
  58285. // creates a black and white random noise texture, 512x512
  58286. LensRenderingPipeline.prototype._createGrainTexture = function () {
  58287. var size = 512;
  58288. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58289. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58290. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58291. var context = this._grainTexture.getContext();
  58292. var rand = function (min, max) {
  58293. return Math.random() * (max - min) + min;
  58294. };
  58295. var value;
  58296. for (var x = 0; x < size; x++) {
  58297. for (var y = 0; y < size; y++) {
  58298. value = Math.floor(rand(0.42, 0.58) * 255);
  58299. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  58300. context.fillRect(x, y, 1, 1);
  58301. }
  58302. }
  58303. this._grainTexture.update(false);
  58304. };
  58305. return LensRenderingPipeline;
  58306. }(BABYLON.PostProcessRenderPipeline));
  58307. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  58308. })(BABYLON || (BABYLON = {}));
  58309. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  58310. var BABYLON;
  58311. (function (BABYLON) {
  58312. var StandardRenderingPipeline = /** @class */ (function (_super) {
  58313. __extends(StandardRenderingPipeline, _super);
  58314. /**
  58315. * @constructor
  58316. * @param {string} name - The rendering pipeline name
  58317. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58318. * @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)
  58319. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  58320. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58321. */
  58322. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  58323. if (originalPostProcess === void 0) { originalPostProcess = null; }
  58324. var _this = _super.call(this, scene.getEngine(), name) || this;
  58325. _this.downSampleX4PostProcess = null;
  58326. _this.brightPassPostProcess = null;
  58327. _this.blurHPostProcesses = [];
  58328. _this.blurVPostProcesses = [];
  58329. _this.textureAdderPostProcess = null;
  58330. _this.volumetricLightPostProcess = null;
  58331. _this.volumetricLightSmoothXPostProcess = null;
  58332. _this.volumetricLightSmoothYPostProcess = null;
  58333. _this.volumetricLightMergePostProces = null;
  58334. _this.volumetricLightFinalPostProcess = null;
  58335. _this.luminancePostProcess = null;
  58336. _this.luminanceDownSamplePostProcesses = [];
  58337. _this.hdrPostProcess = null;
  58338. _this.textureAdderFinalPostProcess = null;
  58339. _this.lensFlareFinalPostProcess = null;
  58340. _this.hdrFinalPostProcess = null;
  58341. _this.lensFlarePostProcess = null;
  58342. _this.lensFlareComposePostProcess = null;
  58343. _this.motionBlurPostProcess = null;
  58344. _this.depthOfFieldPostProcess = null;
  58345. // Values
  58346. _this.brightThreshold = 1.0;
  58347. _this.blurWidth = 512.0;
  58348. _this.horizontalBlur = false;
  58349. _this.exposure = 1.0;
  58350. _this.lensTexture = null;
  58351. _this.volumetricLightCoefficient = 0.2;
  58352. _this.volumetricLightPower = 4.0;
  58353. _this.volumetricLightBlurScale = 64.0;
  58354. _this.sourceLight = null;
  58355. _this.hdrMinimumLuminance = 1.0;
  58356. _this.hdrDecreaseRate = 0.5;
  58357. _this.hdrIncreaseRate = 0.5;
  58358. _this.lensColorTexture = null;
  58359. _this.lensFlareStrength = 20.0;
  58360. _this.lensFlareGhostDispersal = 1.4;
  58361. _this.lensFlareHaloWidth = 0.7;
  58362. _this.lensFlareDistortionStrength = 16.0;
  58363. _this.lensStarTexture = null;
  58364. _this.lensFlareDirtTexture = null;
  58365. _this.depthOfFieldDistance = 10.0;
  58366. _this.depthOfFieldBlurWidth = 64.0;
  58367. _this.motionStrength = 1.0;
  58368. // IAnimatable
  58369. _this.animations = [];
  58370. _this._currentDepthOfFieldSource = null;
  58371. _this._hdrCurrentLuminance = 1.0;
  58372. // Getters and setters
  58373. _this._bloomEnabled = true;
  58374. _this._depthOfFieldEnabled = false;
  58375. _this._vlsEnabled = false;
  58376. _this._lensFlareEnabled = false;
  58377. _this._hdrEnabled = false;
  58378. _this._motionBlurEnabled = false;
  58379. _this._motionBlurSamples = 64.0;
  58380. _this._volumetricLightStepsCount = 50.0;
  58381. _this._cameras = cameras || [];
  58382. // Initialize
  58383. _this._scene = scene;
  58384. _this._basePostProcess = originalPostProcess;
  58385. _this._ratio = ratio;
  58386. // Misc
  58387. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58388. // Finish
  58389. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58390. _this._buildPipeline();
  58391. return _this;
  58392. }
  58393. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  58394. get: function () {
  58395. return this._bloomEnabled;
  58396. },
  58397. set: function (enabled) {
  58398. if (this._bloomEnabled === enabled) {
  58399. return;
  58400. }
  58401. this._bloomEnabled = enabled;
  58402. this._buildPipeline();
  58403. },
  58404. enumerable: true,
  58405. configurable: true
  58406. });
  58407. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  58408. get: function () {
  58409. return this._depthOfFieldEnabled;
  58410. },
  58411. set: function (enabled) {
  58412. if (this._depthOfFieldEnabled === enabled) {
  58413. return;
  58414. }
  58415. this._depthOfFieldEnabled = enabled;
  58416. this._buildPipeline();
  58417. },
  58418. enumerable: true,
  58419. configurable: true
  58420. });
  58421. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  58422. get: function () {
  58423. return this._lensFlareEnabled;
  58424. },
  58425. set: function (enabled) {
  58426. if (this._lensFlareEnabled === enabled) {
  58427. return;
  58428. }
  58429. this._lensFlareEnabled = enabled;
  58430. this._buildPipeline();
  58431. },
  58432. enumerable: true,
  58433. configurable: true
  58434. });
  58435. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  58436. get: function () {
  58437. return this._hdrEnabled;
  58438. },
  58439. set: function (enabled) {
  58440. if (this._hdrEnabled === enabled) {
  58441. return;
  58442. }
  58443. this._hdrEnabled = enabled;
  58444. this._buildPipeline();
  58445. },
  58446. enumerable: true,
  58447. configurable: true
  58448. });
  58449. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  58450. get: function () {
  58451. return this._vlsEnabled;
  58452. },
  58453. set: function (enabled) {
  58454. if (this._vlsEnabled === enabled) {
  58455. return;
  58456. }
  58457. if (enabled) {
  58458. var geometry = this._scene.enableGeometryBufferRenderer();
  58459. if (!geometry) {
  58460. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  58461. return;
  58462. }
  58463. }
  58464. this._vlsEnabled = enabled;
  58465. this._buildPipeline();
  58466. },
  58467. enumerable: true,
  58468. configurable: true
  58469. });
  58470. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  58471. get: function () {
  58472. return this._motionBlurEnabled;
  58473. },
  58474. set: function (enabled) {
  58475. if (this._motionBlurEnabled === enabled) {
  58476. return;
  58477. }
  58478. this._motionBlurEnabled = enabled;
  58479. this._buildPipeline();
  58480. },
  58481. enumerable: true,
  58482. configurable: true
  58483. });
  58484. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  58485. get: function () {
  58486. return this._volumetricLightStepsCount;
  58487. },
  58488. set: function (count) {
  58489. if (this.volumetricLightPostProcess) {
  58490. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  58491. }
  58492. this._volumetricLightStepsCount = count;
  58493. },
  58494. enumerable: true,
  58495. configurable: true
  58496. });
  58497. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  58498. get: function () {
  58499. return this._motionBlurSamples;
  58500. },
  58501. set: function (samples) {
  58502. if (this.motionBlurPostProcess) {
  58503. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  58504. }
  58505. this._motionBlurSamples = samples;
  58506. },
  58507. enumerable: true,
  58508. configurable: true
  58509. });
  58510. StandardRenderingPipeline.prototype._buildPipeline = function () {
  58511. var _this = this;
  58512. var ratio = this._ratio;
  58513. var scene = this._scene;
  58514. this._disposePostProcesses();
  58515. this._reset();
  58516. // Create pass post-process
  58517. if (!this._basePostProcess) {
  58518. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  58519. this.originalPostProcess.onApply = function (effect) {
  58520. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  58521. };
  58522. }
  58523. else {
  58524. this.originalPostProcess = this._basePostProcess;
  58525. }
  58526. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58527. this._currentDepthOfFieldSource = this.originalPostProcess;
  58528. if (this._vlsEnabled) {
  58529. // Create volumetric light
  58530. this._createVolumetricLightPostProcess(scene, ratio);
  58531. // Create volumetric light final post-process
  58532. 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);
  58533. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  58534. }
  58535. if (this._bloomEnabled) {
  58536. // Create down sample X4 post-process
  58537. this._createDownSampleX4PostProcess(scene, ratio / 2);
  58538. // Create bright pass post-process
  58539. this._createBrightPassPostProcess(scene, ratio / 2);
  58540. // Create gaussian blur post-processes (down sampling blurs)
  58541. this._createBlurPostProcesses(scene, ratio / 4, 1);
  58542. // Create texture adder post-process
  58543. this._createTextureAdderPostProcess(scene, ratio);
  58544. // Create depth-of-field source post-process
  58545. 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);
  58546. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58547. }
  58548. if (this._lensFlareEnabled) {
  58549. // Create lens flare post-process
  58550. this._createLensFlarePostProcess(scene, ratio);
  58551. // Create depth-of-field source post-process post lens-flare and disable it now
  58552. 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);
  58553. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58554. }
  58555. if (this._hdrEnabled) {
  58556. // Create luminance
  58557. this._createLuminancePostProcesses(scene, this._floatTextureType);
  58558. // Create HDR
  58559. this._createHdrPostProcess(scene, ratio);
  58560. // Create depth-of-field source post-process post hdr and disable it now
  58561. 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);
  58562. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  58563. }
  58564. if (this._depthOfFieldEnabled) {
  58565. // Create gaussian blur used by depth-of-field
  58566. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  58567. // Create depth-of-field post-process
  58568. this._createDepthOfFieldPostProcess(scene, ratio);
  58569. }
  58570. if (this._motionBlurEnabled) {
  58571. // Create motion blur post-process
  58572. this._createMotionBlurPostProcess(scene, ratio);
  58573. }
  58574. if (this._cameras !== null) {
  58575. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58576. }
  58577. };
  58578. // Down Sample X4 Post-Processs
  58579. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58580. var _this = this;
  58581. var downSampleX4Offsets = new Array(32);
  58582. 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);
  58583. this.downSampleX4PostProcess.onApply = function (effect) {
  58584. var id = 0;
  58585. var width = _this.downSampleX4PostProcess.width;
  58586. var height = _this.downSampleX4PostProcess.height;
  58587. for (var i = -2; i < 2; i++) {
  58588. for (var j = -2; j < 2; j++) {
  58589. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58590. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58591. id += 2;
  58592. }
  58593. }
  58594. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58595. };
  58596. // Add to pipeline
  58597. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58598. };
  58599. // Brightpass Post-Process
  58600. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58601. var _this = this;
  58602. var brightOffsets = new Array(8);
  58603. 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);
  58604. this.brightPassPostProcess.onApply = function (effect) {
  58605. var sU = (1.0 / _this.brightPassPostProcess.width);
  58606. var sV = (1.0 / _this.brightPassPostProcess.height);
  58607. brightOffsets[0] = -0.5 * sU;
  58608. brightOffsets[1] = 0.5 * sV;
  58609. brightOffsets[2] = 0.5 * sU;
  58610. brightOffsets[3] = 0.5 * sV;
  58611. brightOffsets[4] = -0.5 * sU;
  58612. brightOffsets[5] = -0.5 * sV;
  58613. brightOffsets[6] = 0.5 * sU;
  58614. brightOffsets[7] = -0.5 * sV;
  58615. effect.setArray2("dsOffsets", brightOffsets);
  58616. effect.setFloat("brightThreshold", _this.brightThreshold);
  58617. };
  58618. // Add to pipeline
  58619. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58620. };
  58621. // Create blur H&V post-processes
  58622. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58623. var _this = this;
  58624. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58625. var engine = scene.getEngine();
  58626. 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);
  58627. 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);
  58628. blurX.onActivateObservable.add(function () {
  58629. var dw = blurX.width / engine.getRenderWidth();
  58630. blurX.kernel = _this[blurWidthKey] * dw;
  58631. });
  58632. blurY.onActivateObservable.add(function () {
  58633. var dw = blurY.height / engine.getRenderHeight();
  58634. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58635. });
  58636. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58637. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58638. this.blurHPostProcesses.push(blurX);
  58639. this.blurVPostProcesses.push(blurY);
  58640. };
  58641. // Create texture adder post-process
  58642. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58643. var _this = this;
  58644. 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);
  58645. this.textureAdderPostProcess.onApply = function (effect) {
  58646. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58647. effect.setTexture("lensSampler", _this.lensTexture);
  58648. effect.setFloat("exposure", _this.exposure);
  58649. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58650. };
  58651. // Add to pipeline
  58652. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58653. };
  58654. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58655. var _this = this;
  58656. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58657. geometryRenderer.enablePosition = true;
  58658. var geometry = geometryRenderer.getGBuffer();
  58659. // Base post-process
  58660. 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));
  58661. var depthValues = BABYLON.Vector2.Zero();
  58662. this.volumetricLightPostProcess.onApply = function (effect) {
  58663. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58664. var generator = _this.sourceLight.getShadowGenerator();
  58665. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58666. effect.setTexture("positionSampler", geometry.textures[2]);
  58667. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58668. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58669. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58670. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58671. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58672. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58673. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58674. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58675. effect.setVector2("depthValues", depthValues);
  58676. }
  58677. };
  58678. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  58679. // Smooth
  58680. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  58681. // Merge
  58682. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  58683. this.volumetricLightMergePostProces.onApply = function (effect) {
  58684. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  58685. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  58686. };
  58687. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  58688. };
  58689. // Create luminance
  58690. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  58691. var _this = this;
  58692. // Create luminance
  58693. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  58694. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  58695. var offsets = [];
  58696. this.luminancePostProcess.onApply = function (effect) {
  58697. var sU = (1.0 / _this.luminancePostProcess.width);
  58698. var sV = (1.0 / _this.luminancePostProcess.height);
  58699. offsets[0] = -0.5 * sU;
  58700. offsets[1] = 0.5 * sV;
  58701. offsets[2] = 0.5 * sU;
  58702. offsets[3] = 0.5 * sV;
  58703. offsets[4] = -0.5 * sU;
  58704. offsets[5] = -0.5 * sV;
  58705. offsets[6] = 0.5 * sU;
  58706. offsets[7] = -0.5 * sV;
  58707. effect.setArray2("lumOffsets", offsets);
  58708. };
  58709. // Add to pipeline
  58710. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  58711. // Create down sample luminance
  58712. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  58713. var size = Math.pow(3, i);
  58714. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  58715. if (i === 0) {
  58716. defines += "#define FINAL_DOWN_SAMPLER";
  58717. }
  58718. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  58719. this.luminanceDownSamplePostProcesses.push(postProcess);
  58720. }
  58721. // Create callbacks and add effects
  58722. var lastLuminance = this.luminancePostProcess;
  58723. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  58724. var downSampleOffsets = new Array(18);
  58725. pp.onApply = function (effect) {
  58726. if (!lastLuminance) {
  58727. return;
  58728. }
  58729. var id = 0;
  58730. for (var x = -1; x < 2; x++) {
  58731. for (var y = -1; y < 2; y++) {
  58732. downSampleOffsets[id] = x / lastLuminance.width;
  58733. downSampleOffsets[id + 1] = y / lastLuminance.height;
  58734. id += 2;
  58735. }
  58736. }
  58737. effect.setArray2("dsOffsets", downSampleOffsets);
  58738. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  58739. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58740. lastLuminance = _this.luminancePostProcess;
  58741. }
  58742. else {
  58743. lastLuminance = pp;
  58744. }
  58745. };
  58746. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58747. pp.onAfterRender = function (effect) {
  58748. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58749. 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);
  58750. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58751. };
  58752. }
  58753. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58754. });
  58755. };
  58756. // Create HDR post-process
  58757. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58758. var _this = this;
  58759. 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);
  58760. var outputLiminance = 1;
  58761. var time = 0;
  58762. var lastTime = 0;
  58763. this.hdrPostProcess.onApply = function (effect) {
  58764. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58765. time += scene.getEngine().getDeltaTime();
  58766. if (outputLiminance < 0) {
  58767. outputLiminance = _this._hdrCurrentLuminance;
  58768. }
  58769. else {
  58770. var dt = (lastTime - time) / 1000.0;
  58771. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58772. outputLiminance += _this.hdrDecreaseRate * dt;
  58773. }
  58774. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58775. outputLiminance -= _this.hdrIncreaseRate * dt;
  58776. }
  58777. else {
  58778. outputLiminance = _this._hdrCurrentLuminance;
  58779. }
  58780. }
  58781. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58782. effect.setFloat("averageLuminance", outputLiminance);
  58783. lastTime = time;
  58784. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58785. };
  58786. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58787. };
  58788. // Create lens flare post-process
  58789. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58790. var _this = this;
  58791. 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);
  58792. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58793. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58794. 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);
  58795. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58796. var resolution = new BABYLON.Vector2(0, 0);
  58797. // Lens flare
  58798. this.lensFlarePostProcess.onApply = function (effect) {
  58799. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58800. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58801. effect.setFloat("strength", _this.lensFlareStrength);
  58802. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58803. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58804. // Shift
  58805. resolution.x = _this.lensFlarePostProcess.width;
  58806. resolution.y = _this.lensFlarePostProcess.height;
  58807. effect.setVector2("resolution", resolution);
  58808. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58809. };
  58810. // Compose
  58811. 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);
  58812. 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);
  58813. this.lensFlareComposePostProcess.onApply = function (effect) {
  58814. if (!_this._scene.activeCamera) {
  58815. return;
  58816. }
  58817. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58818. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58819. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58820. // Lens start rotation matrix
  58821. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58822. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58823. 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));
  58824. camRot *= 4.0;
  58825. 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);
  58826. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58827. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58828. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58829. };
  58830. };
  58831. // Create depth-of-field post-process
  58832. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58833. var _this = this;
  58834. 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);
  58835. this.depthOfFieldPostProcess.onApply = function (effect) {
  58836. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58837. effect.setTexture("depthSampler", _this._getDepthTexture());
  58838. effect.setFloat("distance", _this.depthOfFieldDistance);
  58839. };
  58840. // Add to pipeline
  58841. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58842. };
  58843. // Create motion blur post-process
  58844. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58845. var _this = this;
  58846. 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);
  58847. var motionScale = 0;
  58848. var prevViewProjection = BABYLON.Matrix.Identity();
  58849. var invViewProjection = BABYLON.Matrix.Identity();
  58850. var viewProjection = BABYLON.Matrix.Identity();
  58851. var screenSize = BABYLON.Vector2.Zero();
  58852. this.motionBlurPostProcess.onApply = function (effect) {
  58853. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58854. viewProjection.invertToRef(invViewProjection);
  58855. effect.setMatrix("inverseViewProjection", invViewProjection);
  58856. effect.setMatrix("prevViewProjection", prevViewProjection);
  58857. prevViewProjection = viewProjection;
  58858. screenSize.x = _this.motionBlurPostProcess.width;
  58859. screenSize.y = _this.motionBlurPostProcess.height;
  58860. effect.setVector2("screenSize", screenSize);
  58861. motionScale = scene.getEngine().getFps() / 60.0;
  58862. effect.setFloat("motionScale", motionScale);
  58863. effect.setFloat("motionStrength", _this.motionStrength);
  58864. effect.setTexture("depthSampler", _this._getDepthTexture());
  58865. };
  58866. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58867. };
  58868. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58869. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58870. var renderer = this._scene.enableGeometryBufferRenderer();
  58871. return renderer.getGBuffer().textures[0];
  58872. }
  58873. return this._scene.enableDepthRenderer().getDepthMap();
  58874. };
  58875. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58876. for (var i = 0; i < this._cameras.length; i++) {
  58877. var camera = this._cameras[i];
  58878. if (this.originalPostProcess) {
  58879. this.originalPostProcess.dispose(camera);
  58880. }
  58881. if (this.downSampleX4PostProcess) {
  58882. this.downSampleX4PostProcess.dispose(camera);
  58883. }
  58884. if (this.brightPassPostProcess) {
  58885. this.brightPassPostProcess.dispose(camera);
  58886. }
  58887. if (this.textureAdderPostProcess) {
  58888. this.textureAdderPostProcess.dispose(camera);
  58889. }
  58890. if (this.textureAdderFinalPostProcess) {
  58891. this.textureAdderFinalPostProcess.dispose(camera);
  58892. }
  58893. if (this.volumetricLightPostProcess) {
  58894. this.volumetricLightPostProcess.dispose(camera);
  58895. }
  58896. if (this.volumetricLightSmoothXPostProcess) {
  58897. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58898. }
  58899. if (this.volumetricLightSmoothYPostProcess) {
  58900. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58901. }
  58902. if (this.volumetricLightMergePostProces) {
  58903. this.volumetricLightMergePostProces.dispose(camera);
  58904. }
  58905. if (this.volumetricLightFinalPostProcess) {
  58906. this.volumetricLightFinalPostProcess.dispose(camera);
  58907. }
  58908. if (this.lensFlarePostProcess) {
  58909. this.lensFlarePostProcess.dispose(camera);
  58910. }
  58911. if (this.lensFlareComposePostProcess) {
  58912. this.lensFlareComposePostProcess.dispose(camera);
  58913. }
  58914. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58915. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58916. }
  58917. if (this.luminancePostProcess) {
  58918. this.luminancePostProcess.dispose(camera);
  58919. }
  58920. if (this.hdrPostProcess) {
  58921. this.hdrPostProcess.dispose(camera);
  58922. }
  58923. if (this.hdrFinalPostProcess) {
  58924. this.hdrFinalPostProcess.dispose(camera);
  58925. }
  58926. if (this.depthOfFieldPostProcess) {
  58927. this.depthOfFieldPostProcess.dispose(camera);
  58928. }
  58929. if (this.motionBlurPostProcess) {
  58930. this.motionBlurPostProcess.dispose(camera);
  58931. }
  58932. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58933. this.blurHPostProcesses[j].dispose(camera);
  58934. }
  58935. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58936. this.blurVPostProcesses[j].dispose(camera);
  58937. }
  58938. }
  58939. this.originalPostProcess = null;
  58940. this.downSampleX4PostProcess = null;
  58941. this.brightPassPostProcess = null;
  58942. this.textureAdderPostProcess = null;
  58943. this.textureAdderFinalPostProcess = null;
  58944. this.volumetricLightPostProcess = null;
  58945. this.volumetricLightSmoothXPostProcess = null;
  58946. this.volumetricLightSmoothYPostProcess = null;
  58947. this.volumetricLightMergePostProces = null;
  58948. this.volumetricLightFinalPostProcess = null;
  58949. this.lensFlarePostProcess = null;
  58950. this.lensFlareComposePostProcess = null;
  58951. this.luminancePostProcess = null;
  58952. this.hdrPostProcess = null;
  58953. this.hdrFinalPostProcess = null;
  58954. this.depthOfFieldPostProcess = null;
  58955. this.motionBlurPostProcess = null;
  58956. this.luminanceDownSamplePostProcesses = [];
  58957. this.blurHPostProcesses = [];
  58958. this.blurVPostProcesses = [];
  58959. };
  58960. // Dispose
  58961. StandardRenderingPipeline.prototype.dispose = function () {
  58962. this._disposePostProcesses();
  58963. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58964. _super.prototype.dispose.call(this);
  58965. };
  58966. // Serialize rendering pipeline
  58967. StandardRenderingPipeline.prototype.serialize = function () {
  58968. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58969. serializationObject.customType = "StandardRenderingPipeline";
  58970. return serializationObject;
  58971. };
  58972. /**
  58973. * Static members
  58974. */
  58975. // Parse serialized pipeline
  58976. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58977. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58978. };
  58979. // Luminance steps
  58980. StandardRenderingPipeline.LuminanceSteps = 6;
  58981. __decorate([
  58982. BABYLON.serialize()
  58983. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58984. __decorate([
  58985. BABYLON.serialize()
  58986. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58987. __decorate([
  58988. BABYLON.serialize()
  58989. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58990. __decorate([
  58991. BABYLON.serialize()
  58992. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58993. __decorate([
  58994. BABYLON.serializeAsTexture("lensTexture")
  58995. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58996. __decorate([
  58997. BABYLON.serialize()
  58998. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58999. __decorate([
  59000. BABYLON.serialize()
  59001. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  59002. __decorate([
  59003. BABYLON.serialize()
  59004. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  59005. __decorate([
  59006. BABYLON.serialize()
  59007. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  59008. __decorate([
  59009. BABYLON.serialize()
  59010. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  59011. __decorate([
  59012. BABYLON.serialize()
  59013. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  59014. __decorate([
  59015. BABYLON.serializeAsTexture("lensColorTexture")
  59016. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59017. __decorate([
  59018. BABYLON.serialize()
  59019. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59020. __decorate([
  59021. BABYLON.serialize()
  59022. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59023. __decorate([
  59024. BABYLON.serialize()
  59025. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59026. __decorate([
  59027. BABYLON.serialize()
  59028. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59029. __decorate([
  59030. BABYLON.serializeAsTexture("lensStarTexture")
  59031. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59032. __decorate([
  59033. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59034. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59035. __decorate([
  59036. BABYLON.serialize()
  59037. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59038. __decorate([
  59039. BABYLON.serialize()
  59040. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59041. __decorate([
  59042. BABYLON.serialize()
  59043. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  59044. __decorate([
  59045. BABYLON.serialize()
  59046. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  59047. __decorate([
  59048. BABYLON.serialize()
  59049. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  59050. __decorate([
  59051. BABYLON.serialize()
  59052. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  59053. __decorate([
  59054. BABYLON.serialize()
  59055. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  59056. __decorate([
  59057. BABYLON.serialize()
  59058. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  59059. __decorate([
  59060. BABYLON.serialize()
  59061. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  59062. __decorate([
  59063. BABYLON.serialize()
  59064. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  59065. __decorate([
  59066. BABYLON.serialize()
  59067. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  59068. return StandardRenderingPipeline;
  59069. }(BABYLON.PostProcessRenderPipeline));
  59070. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59071. })(BABYLON || (BABYLON = {}));
  59072. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59073. var BABYLON;
  59074. (function (BABYLON) {
  59075. var FxaaPostProcess = /** @class */ (function (_super) {
  59076. __extends(FxaaPostProcess, _super);
  59077. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59078. if (camera === void 0) { camera = null; }
  59079. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59080. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  59081. _this.onApplyObservable.add(function (effect) {
  59082. var texelSize = _this.texelSize;
  59083. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  59084. });
  59085. return _this;
  59086. }
  59087. return FxaaPostProcess;
  59088. }(BABYLON.PostProcess));
  59089. BABYLON.FxaaPostProcess = FxaaPostProcess;
  59090. })(BABYLON || (BABYLON = {}));
  59091. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  59092. var BABYLON;
  59093. (function (BABYLON) {
  59094. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  59095. __extends(DefaultRenderingPipeline, _super);
  59096. /**
  59097. * @constructor
  59098. * @param {string} name - The rendering pipeline name
  59099. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59100. * @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)
  59101. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59102. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  59103. */
  59104. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  59105. if (automaticBuild === void 0) { automaticBuild = true; }
  59106. var _this = _super.call(this, scene.getEngine(), name) || this;
  59107. _this.PassPostProcessId = "PassPostProcessEffect";
  59108. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  59109. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  59110. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  59111. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  59112. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  59113. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  59114. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  59115. // IAnimatable
  59116. _this.animations = [];
  59117. // Values
  59118. _this._bloomEnabled = false;
  59119. _this._fxaaEnabled = false;
  59120. _this._imageProcessingEnabled = true;
  59121. _this._bloomScale = 0.6;
  59122. _this._buildAllowed = true;
  59123. /**
  59124. * Specifies the size of the bloom blur kernel, relative to the final output size
  59125. */
  59126. _this.bloomKernel = 64;
  59127. /**
  59128. * Specifies the weight of the bloom in the final rendering
  59129. */
  59130. _this._bloomWeight = 0.15;
  59131. _this._cameras = cameras || [];
  59132. _this._buildAllowed = automaticBuild;
  59133. // Initialize
  59134. _this._scene = scene;
  59135. var caps = _this._scene.getEngine().getCaps();
  59136. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  59137. // Misc
  59138. if (_this._hdr) {
  59139. if (caps.textureHalfFloatRender) {
  59140. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59141. }
  59142. else if (caps.textureFloatRender) {
  59143. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59144. }
  59145. }
  59146. else {
  59147. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59148. }
  59149. // Attach
  59150. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59151. _this._buildPipeline();
  59152. return _this;
  59153. }
  59154. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  59155. get: function () {
  59156. return this._bloomWeight;
  59157. },
  59158. set: function (value) {
  59159. if (this._bloomWeight === value) {
  59160. return;
  59161. }
  59162. this._bloomWeight = value;
  59163. if (this._hdr && this.copyBack) {
  59164. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  59165. }
  59166. },
  59167. enumerable: true,
  59168. configurable: true
  59169. });
  59170. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  59171. get: function () {
  59172. return this._bloomScale;
  59173. },
  59174. set: function (value) {
  59175. if (this._bloomScale === value) {
  59176. return;
  59177. }
  59178. this._bloomScale = value;
  59179. this._buildPipeline();
  59180. },
  59181. enumerable: true,
  59182. configurable: true
  59183. });
  59184. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  59185. get: function () {
  59186. return this._bloomEnabled;
  59187. },
  59188. set: function (enabled) {
  59189. if (this._bloomEnabled === enabled) {
  59190. return;
  59191. }
  59192. this._bloomEnabled = enabled;
  59193. this._buildPipeline();
  59194. },
  59195. enumerable: true,
  59196. configurable: true
  59197. });
  59198. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  59199. get: function () {
  59200. return this._fxaaEnabled;
  59201. },
  59202. set: function (enabled) {
  59203. if (this._fxaaEnabled === enabled) {
  59204. return;
  59205. }
  59206. this._fxaaEnabled = enabled;
  59207. this._buildPipeline();
  59208. },
  59209. enumerable: true,
  59210. configurable: true
  59211. });
  59212. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  59213. get: function () {
  59214. return this._imageProcessingEnabled;
  59215. },
  59216. set: function (enabled) {
  59217. if (this._imageProcessingEnabled === enabled) {
  59218. return;
  59219. }
  59220. this._imageProcessingEnabled = enabled;
  59221. this._buildPipeline();
  59222. },
  59223. enumerable: true,
  59224. configurable: true
  59225. });
  59226. /**
  59227. * Force the compilation of the entire pipeline.
  59228. */
  59229. DefaultRenderingPipeline.prototype.prepare = function () {
  59230. var previousState = this._buildAllowed;
  59231. this._buildAllowed = true;
  59232. this._buildPipeline();
  59233. this._buildAllowed = previousState;
  59234. };
  59235. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  59236. var _this = this;
  59237. if (!this._buildAllowed) {
  59238. return;
  59239. }
  59240. var engine = this._scene.getEngine();
  59241. this._disposePostProcesses();
  59242. this._reset();
  59243. if (this.bloomEnabled) {
  59244. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59245. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  59246. if (!this._hdr) {
  59247. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59248. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  59249. this.highlights.autoClear = false;
  59250. this.highlights.alwaysForcePOT = true;
  59251. }
  59252. 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);
  59253. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  59254. this.blurX.alwaysForcePOT = true;
  59255. this.blurX.autoClear = false;
  59256. this.blurX.onActivateObservable.add(function () {
  59257. var dw = _this.blurX.width / engine.getRenderWidth(true);
  59258. _this.blurX.kernel = _this.bloomKernel * dw;
  59259. });
  59260. 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);
  59261. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  59262. this.blurY.alwaysForcePOT = true;
  59263. this.blurY.autoClear = false;
  59264. this.blurY.onActivateObservable.add(function () {
  59265. var dh = _this.blurY.height / engine.getRenderHeight(true);
  59266. _this.blurY.kernel = _this.bloomKernel * dh;
  59267. });
  59268. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59269. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  59270. this.copyBack.alwaysForcePOT = true;
  59271. if (this._hdr) {
  59272. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  59273. var w = this.bloomWeight;
  59274. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  59275. }
  59276. else {
  59277. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  59278. }
  59279. this.copyBack.autoClear = false;
  59280. }
  59281. if (this._imageProcessingEnabled) {
  59282. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59283. if (this._hdr) {
  59284. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  59285. }
  59286. else {
  59287. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  59288. }
  59289. }
  59290. if (this.fxaaEnabled) {
  59291. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59292. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  59293. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59294. }
  59295. else {
  59296. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59297. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  59298. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59299. }
  59300. if (this.bloomEnabled) {
  59301. if (this._hdr) {
  59302. this.copyBack.shareOutputWith(this.blurX);
  59303. if (this.imageProcessing) {
  59304. this.imageProcessing.shareOutputWith(this.pass);
  59305. this.imageProcessing.autoClear = false;
  59306. }
  59307. else if (this.fxaa) {
  59308. this.fxaa.shareOutputWith(this.pass);
  59309. }
  59310. else {
  59311. this.finalMerge.shareOutputWith(this.pass);
  59312. }
  59313. }
  59314. else {
  59315. if (this.fxaa) {
  59316. this.fxaa.shareOutputWith(this.pass);
  59317. }
  59318. else {
  59319. this.finalMerge.shareOutputWith(this.pass);
  59320. }
  59321. }
  59322. }
  59323. if (this._cameras !== null) {
  59324. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59325. }
  59326. };
  59327. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  59328. for (var i = 0; i < this._cameras.length; i++) {
  59329. var camera = this._cameras[i];
  59330. if (this.pass) {
  59331. this.pass.dispose(camera);
  59332. }
  59333. if (this.highlights) {
  59334. this.highlights.dispose(camera);
  59335. }
  59336. if (this.blurX) {
  59337. this.blurX.dispose(camera);
  59338. }
  59339. if (this.blurY) {
  59340. this.blurY.dispose(camera);
  59341. }
  59342. if (this.copyBack) {
  59343. this.copyBack.dispose(camera);
  59344. }
  59345. if (this.imageProcessing) {
  59346. this.imageProcessing.dispose(camera);
  59347. }
  59348. if (this.fxaa) {
  59349. this.fxaa.dispose(camera);
  59350. }
  59351. if (this.finalMerge) {
  59352. this.finalMerge.dispose(camera);
  59353. }
  59354. }
  59355. this.pass = null;
  59356. this.highlights = null;
  59357. this.blurX = null;
  59358. this.blurY = null;
  59359. this.copyBack = null;
  59360. this.imageProcessing = null;
  59361. this.fxaa = null;
  59362. this.finalMerge = null;
  59363. };
  59364. // Dispose
  59365. DefaultRenderingPipeline.prototype.dispose = function () {
  59366. this._disposePostProcesses();
  59367. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59368. _super.prototype.dispose.call(this);
  59369. };
  59370. // Serialize rendering pipeline
  59371. DefaultRenderingPipeline.prototype.serialize = function () {
  59372. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59373. serializationObject.customType = "DefaultRenderingPipeline";
  59374. return serializationObject;
  59375. };
  59376. // Parse serialized pipeline
  59377. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59378. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  59379. };
  59380. __decorate([
  59381. BABYLON.serialize()
  59382. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  59383. __decorate([
  59384. BABYLON.serialize()
  59385. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  59386. __decorate([
  59387. BABYLON.serialize()
  59388. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  59389. __decorate([
  59390. BABYLON.serialize()
  59391. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  59392. __decorate([
  59393. BABYLON.serialize()
  59394. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  59395. __decorate([
  59396. BABYLON.serialize()
  59397. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  59398. __decorate([
  59399. BABYLON.serialize()
  59400. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  59401. __decorate([
  59402. BABYLON.serialize()
  59403. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  59404. return DefaultRenderingPipeline;
  59405. }(BABYLON.PostProcessRenderPipeline));
  59406. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  59407. })(BABYLON || (BABYLON = {}));
  59408. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  59409. var BABYLON;
  59410. (function (BABYLON) {
  59411. var GeometryBufferRenderer = /** @class */ (function () {
  59412. function GeometryBufferRenderer(scene, ratio) {
  59413. if (ratio === void 0) { ratio = 1; }
  59414. this._enablePosition = false;
  59415. this._scene = scene;
  59416. this._ratio = ratio;
  59417. // Render target
  59418. this._createRenderTargets();
  59419. }
  59420. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  59421. set: function (meshes) {
  59422. this._multiRenderTarget.renderList = meshes;
  59423. },
  59424. enumerable: true,
  59425. configurable: true
  59426. });
  59427. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  59428. get: function () {
  59429. return this._multiRenderTarget.isSupported;
  59430. },
  59431. enumerable: true,
  59432. configurable: true
  59433. });
  59434. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  59435. get: function () {
  59436. return this._enablePosition;
  59437. },
  59438. set: function (enable) {
  59439. this._enablePosition = enable;
  59440. this.dispose();
  59441. this._createRenderTargets();
  59442. },
  59443. enumerable: true,
  59444. configurable: true
  59445. });
  59446. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  59447. var material = subMesh.getMaterial();
  59448. if (material && material.disableDepthWrite) {
  59449. return false;
  59450. }
  59451. var defines = [];
  59452. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59453. var mesh = subMesh.getMesh();
  59454. // Alpha test
  59455. if (material && material.needAlphaTesting()) {
  59456. defines.push("#define ALPHATEST");
  59457. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59458. attribs.push(BABYLON.VertexBuffer.UVKind);
  59459. defines.push("#define UV1");
  59460. }
  59461. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59462. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59463. defines.push("#define UV2");
  59464. }
  59465. }
  59466. // Buffers
  59467. if (this._enablePosition) {
  59468. defines.push("#define POSITION");
  59469. }
  59470. // Bones
  59471. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59472. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59473. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59474. if (mesh.numBoneInfluencers > 4) {
  59475. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59476. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59477. }
  59478. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59479. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59480. }
  59481. else {
  59482. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59483. }
  59484. // Instances
  59485. if (useInstances) {
  59486. defines.push("#define INSTANCES");
  59487. attribs.push("world0");
  59488. attribs.push("world1");
  59489. attribs.push("world2");
  59490. attribs.push("world3");
  59491. }
  59492. // Get correct effect
  59493. var join = defines.join("\n");
  59494. if (this._cachedDefines !== join) {
  59495. this._cachedDefines = join;
  59496. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  59497. }
  59498. return this._effect.isReady();
  59499. };
  59500. GeometryBufferRenderer.prototype.getGBuffer = function () {
  59501. return this._multiRenderTarget;
  59502. };
  59503. // Methods
  59504. GeometryBufferRenderer.prototype.dispose = function () {
  59505. this.getGBuffer().dispose();
  59506. };
  59507. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  59508. var _this = this;
  59509. var engine = this._scene.getEngine();
  59510. var count = this._enablePosition ? 3 : 2;
  59511. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  59512. if (!this.isSupported) {
  59513. return;
  59514. }
  59515. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59516. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59517. this._multiRenderTarget.refreshRate = 1;
  59518. this._multiRenderTarget.renderParticles = false;
  59519. this._multiRenderTarget.renderList = null;
  59520. // set default depth value to 1.0 (far away)
  59521. this._multiRenderTarget.onClearObservable.add(function (engine) {
  59522. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  59523. });
  59524. // Custom render function
  59525. var renderSubMesh = function (subMesh) {
  59526. var mesh = subMesh.getRenderingMesh();
  59527. var scene = _this._scene;
  59528. var engine = scene.getEngine();
  59529. var material = subMesh.getMaterial();
  59530. if (!material) {
  59531. return;
  59532. }
  59533. // Culling
  59534. engine.setState(material.backFaceCulling);
  59535. // Managing instances
  59536. var batch = mesh._getInstancesRenderList(subMesh._id);
  59537. if (batch.mustReturn) {
  59538. return;
  59539. }
  59540. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59541. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59542. engine.enableEffect(_this._effect);
  59543. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59544. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59545. _this._effect.setMatrix("view", scene.getViewMatrix());
  59546. // Alpha test
  59547. if (material && material.needAlphaTesting()) {
  59548. var alphaTexture = material.getAlphaTestTexture();
  59549. if (alphaTexture) {
  59550. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59551. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59552. }
  59553. }
  59554. // Bones
  59555. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59556. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59557. }
  59558. // Draw
  59559. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59560. }
  59561. };
  59562. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59563. var index;
  59564. if (depthOnlySubMeshes.length) {
  59565. engine.setColorWrite(false);
  59566. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59567. renderSubMesh(depthOnlySubMeshes.data[index]);
  59568. }
  59569. engine.setColorWrite(true);
  59570. }
  59571. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59572. renderSubMesh(opaqueSubMeshes.data[index]);
  59573. }
  59574. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59575. renderSubMesh(alphaTestSubMeshes.data[index]);
  59576. }
  59577. };
  59578. };
  59579. return GeometryBufferRenderer;
  59580. }());
  59581. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59582. })(BABYLON || (BABYLON = {}));
  59583. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59584. var BABYLON;
  59585. (function (BABYLON) {
  59586. var RefractionPostProcess = /** @class */ (function (_super) {
  59587. __extends(RefractionPostProcess, _super);
  59588. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59589. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59590. _this.color = color;
  59591. _this.depth = depth;
  59592. _this.colorLevel = colorLevel;
  59593. _this.onActivateObservable.add(function (cam) {
  59594. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59595. });
  59596. _this.onApplyObservable.add(function (effect) {
  59597. effect.setColor3("baseColor", _this.color);
  59598. effect.setFloat("depth", _this.depth);
  59599. effect.setFloat("colorLevel", _this.colorLevel);
  59600. effect.setTexture("refractionSampler", _this._refRexture);
  59601. });
  59602. return _this;
  59603. }
  59604. // Methods
  59605. RefractionPostProcess.prototype.dispose = function (camera) {
  59606. if (this._refRexture) {
  59607. this._refRexture.dispose();
  59608. }
  59609. _super.prototype.dispose.call(this, camera);
  59610. };
  59611. return RefractionPostProcess;
  59612. }(BABYLON.PostProcess));
  59613. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59614. })(BABYLON || (BABYLON = {}));
  59615. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59616. var BABYLON;
  59617. (function (BABYLON) {
  59618. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59619. __extends(BlackAndWhitePostProcess, _super);
  59620. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59621. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59622. _this.degree = 1;
  59623. _this.onApplyObservable.add(function (effect) {
  59624. effect.setFloat("degree", _this.degree);
  59625. });
  59626. return _this;
  59627. }
  59628. return BlackAndWhitePostProcess;
  59629. }(BABYLON.PostProcess));
  59630. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59631. })(BABYLON || (BABYLON = {}));
  59632. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59633. var BABYLON;
  59634. (function (BABYLON) {
  59635. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59636. __extends(ConvolutionPostProcess, _super);
  59637. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59638. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59639. _this.kernel = kernel;
  59640. _this.onApply = function (effect) {
  59641. effect.setFloat2("screenSize", _this.width, _this.height);
  59642. effect.setArray("kernel", _this.kernel);
  59643. };
  59644. return _this;
  59645. }
  59646. // Statics
  59647. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59648. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59649. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59650. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59651. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59652. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59653. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59654. return ConvolutionPostProcess;
  59655. }(BABYLON.PostProcess));
  59656. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59657. })(BABYLON || (BABYLON = {}));
  59658. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59659. var BABYLON;
  59660. (function (BABYLON) {
  59661. var FilterPostProcess = /** @class */ (function (_super) {
  59662. __extends(FilterPostProcess, _super);
  59663. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59664. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59665. _this.kernelMatrix = kernelMatrix;
  59666. _this.onApply = function (effect) {
  59667. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59668. };
  59669. return _this;
  59670. }
  59671. return FilterPostProcess;
  59672. }(BABYLON.PostProcess));
  59673. BABYLON.FilterPostProcess = FilterPostProcess;
  59674. })(BABYLON || (BABYLON = {}));
  59675. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59676. var BABYLON;
  59677. (function (BABYLON) {
  59678. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  59679. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  59680. __extends(VolumetricLightScatteringPostProcess, _super);
  59681. /**
  59682. * @constructor
  59683. * @param {string} name - The post-process name
  59684. * @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)
  59685. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  59686. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  59687. * @param {number} samples - The post-process quality, default 100
  59688. * @param {number} samplingMode - The post-process filtering mode
  59689. * @param {BABYLON.Engine} engine - The babylon engine
  59690. * @param {boolean} reusable - If the post-process is reusable
  59691. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  59692. */
  59693. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  59694. if (samples === void 0) { samples = 100; }
  59695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59696. 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;
  59697. _this._screenCoordinates = BABYLON.Vector2.Zero();
  59698. /**
  59699. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  59700. * @type {Vector3}
  59701. */
  59702. _this.customMeshPosition = BABYLON.Vector3.Zero();
  59703. /**
  59704. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  59705. * @type {boolean}
  59706. */
  59707. _this.useCustomMeshPosition = false;
  59708. /**
  59709. * If the post-process should inverse the light scattering direction
  59710. * @type {boolean}
  59711. */
  59712. _this.invert = true;
  59713. /**
  59714. * Array containing the excluded meshes not rendered in the internal pass
  59715. */
  59716. _this.excludedMeshes = new Array();
  59717. /**
  59718. * Controls the overall intensity of the post-process
  59719. * @type {number}
  59720. */
  59721. _this.exposure = 0.3;
  59722. /**
  59723. * Dissipates each sample's contribution in range [0, 1]
  59724. * @type {number}
  59725. */
  59726. _this.decay = 0.96815;
  59727. /**
  59728. * Controls the overall intensity of each sample
  59729. * @type {number}
  59730. */
  59731. _this.weight = 0.58767;
  59732. /**
  59733. * Controls the density of each sample
  59734. * @type {number}
  59735. */
  59736. _this.density = 0.926;
  59737. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  59738. engine = scene.getEngine();
  59739. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59740. // Configure mesh
  59741. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59742. // Configure
  59743. _this._createPass(scene, ratio.passRatio || ratio);
  59744. _this.onActivate = function (camera) {
  59745. if (!_this.isSupported) {
  59746. _this.dispose(camera);
  59747. }
  59748. _this.onActivate = null;
  59749. };
  59750. _this.onApplyObservable.add(function (effect) {
  59751. _this._updateMeshScreenCoordinates(scene);
  59752. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59753. effect.setFloat("exposure", _this.exposure);
  59754. effect.setFloat("decay", _this.decay);
  59755. effect.setFloat("weight", _this.weight);
  59756. effect.setFloat("density", _this.density);
  59757. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59758. });
  59759. return _this;
  59760. }
  59761. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59762. get: function () {
  59763. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59764. return false;
  59765. },
  59766. set: function (useDiffuseColor) {
  59767. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59768. },
  59769. enumerable: true,
  59770. configurable: true
  59771. });
  59772. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59773. return "VolumetricLightScatteringPostProcess";
  59774. };
  59775. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59776. var mesh = subMesh.getMesh();
  59777. // Render this.mesh as default
  59778. if (mesh === this.mesh && mesh.material) {
  59779. return mesh.material.isReady(mesh);
  59780. }
  59781. var defines = [];
  59782. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59783. var material = subMesh.getMaterial();
  59784. // Alpha test
  59785. if (material) {
  59786. if (material.needAlphaTesting()) {
  59787. defines.push("#define ALPHATEST");
  59788. }
  59789. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59790. attribs.push(BABYLON.VertexBuffer.UVKind);
  59791. defines.push("#define UV1");
  59792. }
  59793. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59794. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59795. defines.push("#define UV2");
  59796. }
  59797. }
  59798. // Bones
  59799. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59800. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59801. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59802. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59803. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59804. }
  59805. else {
  59806. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59807. }
  59808. // Instances
  59809. if (useInstances) {
  59810. defines.push("#define INSTANCES");
  59811. attribs.push("world0");
  59812. attribs.push("world1");
  59813. attribs.push("world2");
  59814. attribs.push("world3");
  59815. }
  59816. // Get correct effect
  59817. var join = defines.join("\n");
  59818. if (this._cachedDefines !== join) {
  59819. this._cachedDefines = join;
  59820. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59821. }
  59822. return this._volumetricLightScatteringPass.isReady();
  59823. };
  59824. /**
  59825. * Sets the new light position for light scattering effect
  59826. * @param {BABYLON.Vector3} The new custom light position
  59827. */
  59828. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59829. this.customMeshPosition = position;
  59830. };
  59831. /**
  59832. * Returns the light position for light scattering effect
  59833. * @return {BABYLON.Vector3} The custom light position
  59834. */
  59835. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59836. return this.customMeshPosition;
  59837. };
  59838. /**
  59839. * Disposes the internal assets and detaches the post-process from the camera
  59840. */
  59841. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59842. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59843. if (rttIndex !== -1) {
  59844. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59845. }
  59846. this._volumetricLightScatteringRTT.dispose();
  59847. _super.prototype.dispose.call(this, camera);
  59848. };
  59849. /**
  59850. * Returns the render target texture used by the post-process
  59851. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59852. */
  59853. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59854. return this._volumetricLightScatteringRTT;
  59855. };
  59856. // Private methods
  59857. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59858. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59859. return true;
  59860. }
  59861. return false;
  59862. };
  59863. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59864. var _this = this;
  59865. var engine = scene.getEngine();
  59866. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59867. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59868. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59869. this._volumetricLightScatteringRTT.renderList = null;
  59870. this._volumetricLightScatteringRTT.renderParticles = false;
  59871. var camera = this.getCamera();
  59872. if (camera) {
  59873. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59874. }
  59875. else {
  59876. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59877. }
  59878. // Custom render function for submeshes
  59879. var renderSubMesh = function (subMesh) {
  59880. var mesh = subMesh.getRenderingMesh();
  59881. if (_this._meshExcluded(mesh)) {
  59882. return;
  59883. }
  59884. var material = subMesh.getMaterial();
  59885. if (!material) {
  59886. return;
  59887. }
  59888. var scene = mesh.getScene();
  59889. var engine = scene.getEngine();
  59890. // Culling
  59891. engine.setState(material.backFaceCulling);
  59892. // Managing instances
  59893. var batch = mesh._getInstancesRenderList(subMesh._id);
  59894. if (batch.mustReturn) {
  59895. return;
  59896. }
  59897. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59898. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59899. var effect = _this._volumetricLightScatteringPass;
  59900. if (mesh === _this.mesh) {
  59901. if (subMesh.effect) {
  59902. effect = subMesh.effect;
  59903. }
  59904. else {
  59905. effect = material.getEffect();
  59906. }
  59907. }
  59908. engine.enableEffect(effect);
  59909. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59910. if (mesh === _this.mesh) {
  59911. material.bind(mesh.getWorldMatrix(), mesh);
  59912. }
  59913. else {
  59914. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59915. // Alpha test
  59916. if (material && material.needAlphaTesting()) {
  59917. var alphaTexture = material.getAlphaTestTexture();
  59918. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59919. if (alphaTexture) {
  59920. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59921. }
  59922. }
  59923. // Bones
  59924. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59925. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59926. }
  59927. }
  59928. // Draw
  59929. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59930. }
  59931. };
  59932. // Render target texture callbacks
  59933. var savedSceneClearColor;
  59934. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59935. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59936. savedSceneClearColor = scene.clearColor;
  59937. scene.clearColor = sceneClearColor;
  59938. });
  59939. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59940. scene.clearColor = savedSceneClearColor;
  59941. });
  59942. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59943. var engine = scene.getEngine();
  59944. var index;
  59945. if (depthOnlySubMeshes.length) {
  59946. engine.setColorWrite(false);
  59947. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59948. renderSubMesh(depthOnlySubMeshes.data[index]);
  59949. }
  59950. engine.setColorWrite(true);
  59951. }
  59952. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59953. renderSubMesh(opaqueSubMeshes.data[index]);
  59954. }
  59955. engine.setAlphaTesting(true);
  59956. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59957. renderSubMesh(alphaTestSubMeshes.data[index]);
  59958. }
  59959. engine.setAlphaTesting(false);
  59960. if (transparentSubMeshes.length) {
  59961. // Sort sub meshes
  59962. for (index = 0; index < transparentSubMeshes.length; index++) {
  59963. var submesh = transparentSubMeshes.data[index];
  59964. var boundingInfo = submesh.getBoundingInfo();
  59965. if (boundingInfo && scene.activeCamera) {
  59966. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59967. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59968. }
  59969. }
  59970. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59971. sortedArray.sort(function (a, b) {
  59972. // Alpha index first
  59973. if (a._alphaIndex > b._alphaIndex) {
  59974. return 1;
  59975. }
  59976. if (a._alphaIndex < b._alphaIndex) {
  59977. return -1;
  59978. }
  59979. // Then distance to camera
  59980. if (a._distanceToCamera < b._distanceToCamera) {
  59981. return 1;
  59982. }
  59983. if (a._distanceToCamera > b._distanceToCamera) {
  59984. return -1;
  59985. }
  59986. return 0;
  59987. });
  59988. // Render sub meshes
  59989. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59990. for (index = 0; index < sortedArray.length; index++) {
  59991. renderSubMesh(sortedArray[index]);
  59992. }
  59993. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59994. }
  59995. };
  59996. };
  59997. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59998. var transform = scene.getTransformMatrix();
  59999. var meshPosition;
  60000. if (this.useCustomMeshPosition) {
  60001. meshPosition = this.customMeshPosition;
  60002. }
  60003. else if (this.attachedNode) {
  60004. meshPosition = this.attachedNode.position;
  60005. }
  60006. else {
  60007. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  60008. }
  60009. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  60010. this._screenCoordinates.x = pos.x / this._viewPort.width;
  60011. this._screenCoordinates.y = pos.y / this._viewPort.height;
  60012. if (this.invert)
  60013. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  60014. };
  60015. // Static methods
  60016. /**
  60017. * Creates a default mesh for the Volumeric Light Scattering post-process
  60018. * @param {string} The mesh name
  60019. * @param {BABYLON.Scene} The scene where to create the mesh
  60020. * @return {BABYLON.Mesh} the default mesh
  60021. */
  60022. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  60023. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  60024. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  60025. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  60026. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  60027. mesh.material = material;
  60028. return mesh;
  60029. };
  60030. __decorate([
  60031. BABYLON.serializeAsVector3()
  60032. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  60033. __decorate([
  60034. BABYLON.serialize()
  60035. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  60036. __decorate([
  60037. BABYLON.serialize()
  60038. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  60039. __decorate([
  60040. BABYLON.serializeAsMeshReference()
  60041. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  60042. __decorate([
  60043. BABYLON.serialize()
  60044. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  60045. __decorate([
  60046. BABYLON.serialize()
  60047. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  60048. __decorate([
  60049. BABYLON.serialize()
  60050. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  60051. __decorate([
  60052. BABYLON.serialize()
  60053. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  60054. __decorate([
  60055. BABYLON.serialize()
  60056. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  60057. return VolumetricLightScatteringPostProcess;
  60058. }(BABYLON.PostProcess));
  60059. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  60060. })(BABYLON || (BABYLON = {}));
  60061. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  60062. //
  60063. // This post-process allows the modification of rendered colors by using
  60064. // a 'look-up table' (LUT). This effect is also called Color Grading.
  60065. //
  60066. // The object needs to be provided an url to a texture containing the color
  60067. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  60068. // Use an image editing software to tweak the LUT to match your needs.
  60069. //
  60070. // For an example of a color LUT, see here:
  60071. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  60072. // For explanations on color grading, see here:
  60073. // http://udn.epicgames.com/Three/ColorGrading.html
  60074. //
  60075. var BABYLON;
  60076. (function (BABYLON) {
  60077. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  60078. __extends(ColorCorrectionPostProcess, _super);
  60079. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  60080. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  60081. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60082. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  60083. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60084. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60085. _this.onApply = function (effect) {
  60086. effect.setTexture("colorTable", _this._colorTableTexture);
  60087. };
  60088. return _this;
  60089. }
  60090. return ColorCorrectionPostProcess;
  60091. }(BABYLON.PostProcess));
  60092. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  60093. })(BABYLON || (BABYLON = {}));
  60094. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  60095. var BABYLON;
  60096. (function (BABYLON) {
  60097. var TonemappingOperator;
  60098. (function (TonemappingOperator) {
  60099. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  60100. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  60101. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  60102. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  60103. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  60104. ;
  60105. var TonemapPostProcess = /** @class */ (function (_super) {
  60106. __extends(TonemapPostProcess, _super);
  60107. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  60108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60109. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60110. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  60111. _this._operator = _operator;
  60112. _this.exposureAdjustment = exposureAdjustment;
  60113. var defines = "#define ";
  60114. if (_this._operator === TonemappingOperator.Hable)
  60115. defines += "HABLE_TONEMAPPING";
  60116. else if (_this._operator === TonemappingOperator.Reinhard)
  60117. defines += "REINHARD_TONEMAPPING";
  60118. else if (_this._operator === TonemappingOperator.HejiDawson)
  60119. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  60120. else if (_this._operator === TonemappingOperator.Photographic)
  60121. defines += "PHOTOGRAPHIC_TONEMAPPING";
  60122. //sadly a second call to create the effect.
  60123. _this.updateEffect(defines);
  60124. _this.onApply = function (effect) {
  60125. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  60126. };
  60127. return _this;
  60128. }
  60129. return TonemapPostProcess;
  60130. }(BABYLON.PostProcess));
  60131. BABYLON.TonemapPostProcess = TonemapPostProcess;
  60132. })(BABYLON || (BABYLON = {}));
  60133. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  60134. var BABYLON;
  60135. (function (BABYLON) {
  60136. var DisplayPassPostProcess = /** @class */ (function (_super) {
  60137. __extends(DisplayPassPostProcess, _super);
  60138. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  60139. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  60140. }
  60141. return DisplayPassPostProcess;
  60142. }(BABYLON.PostProcess));
  60143. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  60144. })(BABYLON || (BABYLON = {}));
  60145. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  60146. var BABYLON;
  60147. (function (BABYLON) {
  60148. var HighlightsPostProcess = /** @class */ (function (_super) {
  60149. __extends(HighlightsPostProcess, _super);
  60150. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60151. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60152. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  60153. }
  60154. return HighlightsPostProcess;
  60155. }(BABYLON.PostProcess));
  60156. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  60157. })(BABYLON || (BABYLON = {}));
  60158. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  60159. var BABYLON;
  60160. (function (BABYLON) {
  60161. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  60162. __extends(ImageProcessingPostProcess, _super);
  60163. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60164. if (camera === void 0) { camera = null; }
  60165. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60166. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  60167. _this._fromLinearSpace = true;
  60168. /**
  60169. * Defines cache preventing GC.
  60170. */
  60171. _this._defines = {
  60172. IMAGEPROCESSING: false,
  60173. VIGNETTE: false,
  60174. VIGNETTEBLENDMODEMULTIPLY: false,
  60175. VIGNETTEBLENDMODEOPAQUE: false,
  60176. TONEMAPPING: false,
  60177. CONTRAST: false,
  60178. COLORCURVES: false,
  60179. COLORGRADING: false,
  60180. COLORGRADING3D: false,
  60181. FROMLINEARSPACE: false,
  60182. SAMPLER3DGREENDEPTH: false,
  60183. SAMPLER3DBGRMAP: false,
  60184. IMAGEPROCESSINGPOSTPROCESS: false,
  60185. EXPOSURE: false,
  60186. };
  60187. // Setup the default processing configuration to the scene.
  60188. _this._attachImageProcessingConfiguration(null, true);
  60189. _this.imageProcessingConfiguration.applyByPostProcess = true;
  60190. _this.onApply = function (effect) {
  60191. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  60192. };
  60193. return _this;
  60194. }
  60195. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  60196. /**
  60197. * Gets the image processing configuration used either in this material.
  60198. */
  60199. get: function () {
  60200. return this._imageProcessingConfiguration;
  60201. },
  60202. /**
  60203. * Sets the Default image processing configuration used either in the this material.
  60204. *
  60205. * If sets to null, the scene one is in use.
  60206. */
  60207. set: function (value) {
  60208. this._attachImageProcessingConfiguration(value);
  60209. },
  60210. enumerable: true,
  60211. configurable: true
  60212. });
  60213. /**
  60214. * Attaches a new image processing configuration to the PBR Material.
  60215. * @param configuration
  60216. */
  60217. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  60218. var _this = this;
  60219. if (doNotBuild === void 0) { doNotBuild = false; }
  60220. if (configuration === this._imageProcessingConfiguration) {
  60221. return;
  60222. }
  60223. // Detaches observer.
  60224. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60225. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60226. }
  60227. // Pick the scene configuration if needed.
  60228. if (!configuration) {
  60229. var scene = null;
  60230. var engine = this.getEngine();
  60231. var camera = this.getCamera();
  60232. if (camera) {
  60233. scene = camera.getScene();
  60234. }
  60235. else if (engine && engine.scenes) {
  60236. var scenes = engine.scenes;
  60237. scene = scenes[scenes.length - 1];
  60238. }
  60239. else {
  60240. scene = BABYLON.Engine.LastCreatedScene;
  60241. }
  60242. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  60243. }
  60244. else {
  60245. this._imageProcessingConfiguration = configuration;
  60246. }
  60247. // Attaches observer.
  60248. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  60249. _this._updateParameters();
  60250. });
  60251. // Ensure the effect will be rebuilt.
  60252. if (!doNotBuild) {
  60253. this._updateParameters();
  60254. }
  60255. };
  60256. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  60257. /**
  60258. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60259. */
  60260. get: function () {
  60261. return this.imageProcessingConfiguration.colorCurves;
  60262. },
  60263. /**
  60264. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60265. */
  60266. set: function (value) {
  60267. this.imageProcessingConfiguration.colorCurves = value;
  60268. },
  60269. enumerable: true,
  60270. configurable: true
  60271. });
  60272. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  60273. /**
  60274. * Gets wether the color curves effect is enabled.
  60275. */
  60276. get: function () {
  60277. return this.imageProcessingConfiguration.colorCurvesEnabled;
  60278. },
  60279. /**
  60280. * Sets wether the color curves effect is enabled.
  60281. */
  60282. set: function (value) {
  60283. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  60284. },
  60285. enumerable: true,
  60286. configurable: true
  60287. });
  60288. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  60289. /**
  60290. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60291. */
  60292. get: function () {
  60293. return this.imageProcessingConfiguration.colorGradingTexture;
  60294. },
  60295. /**
  60296. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60297. */
  60298. set: function (value) {
  60299. this.imageProcessingConfiguration.colorGradingTexture = value;
  60300. },
  60301. enumerable: true,
  60302. configurable: true
  60303. });
  60304. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  60305. /**
  60306. * Gets wether the color grading effect is enabled.
  60307. */
  60308. get: function () {
  60309. return this.imageProcessingConfiguration.colorGradingEnabled;
  60310. },
  60311. /**
  60312. * Gets wether the color grading effect is enabled.
  60313. */
  60314. set: function (value) {
  60315. this.imageProcessingConfiguration.colorGradingEnabled = value;
  60316. },
  60317. enumerable: true,
  60318. configurable: true
  60319. });
  60320. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  60321. /**
  60322. * Gets exposure used in the effect.
  60323. */
  60324. get: function () {
  60325. return this.imageProcessingConfiguration.exposure;
  60326. },
  60327. /**
  60328. * Sets exposure used in the effect.
  60329. */
  60330. set: function (value) {
  60331. this.imageProcessingConfiguration.exposure = value;
  60332. },
  60333. enumerable: true,
  60334. configurable: true
  60335. });
  60336. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  60337. /**
  60338. * Gets wether tonemapping is enabled or not.
  60339. */
  60340. get: function () {
  60341. return this._imageProcessingConfiguration.toneMappingEnabled;
  60342. },
  60343. /**
  60344. * Sets wether tonemapping is enabled or not
  60345. */
  60346. set: function (value) {
  60347. this._imageProcessingConfiguration.toneMappingEnabled = value;
  60348. },
  60349. enumerable: true,
  60350. configurable: true
  60351. });
  60352. ;
  60353. ;
  60354. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  60355. /**
  60356. * Gets contrast used in the effect.
  60357. */
  60358. get: function () {
  60359. return this.imageProcessingConfiguration.contrast;
  60360. },
  60361. /**
  60362. * Sets contrast used in the effect.
  60363. */
  60364. set: function (value) {
  60365. this.imageProcessingConfiguration.contrast = value;
  60366. },
  60367. enumerable: true,
  60368. configurable: true
  60369. });
  60370. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  60371. /**
  60372. * Gets Vignette stretch size.
  60373. */
  60374. get: function () {
  60375. return this.imageProcessingConfiguration.vignetteStretch;
  60376. },
  60377. /**
  60378. * Sets Vignette stretch size.
  60379. */
  60380. set: function (value) {
  60381. this.imageProcessingConfiguration.vignetteStretch = value;
  60382. },
  60383. enumerable: true,
  60384. configurable: true
  60385. });
  60386. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  60387. /**
  60388. * Gets Vignette centre X Offset.
  60389. */
  60390. get: function () {
  60391. return this.imageProcessingConfiguration.vignetteCentreX;
  60392. },
  60393. /**
  60394. * Sets Vignette centre X Offset.
  60395. */
  60396. set: function (value) {
  60397. this.imageProcessingConfiguration.vignetteCentreX = value;
  60398. },
  60399. enumerable: true,
  60400. configurable: true
  60401. });
  60402. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  60403. /**
  60404. * Gets Vignette centre Y Offset.
  60405. */
  60406. get: function () {
  60407. return this.imageProcessingConfiguration.vignetteCentreY;
  60408. },
  60409. /**
  60410. * Sets Vignette centre Y Offset.
  60411. */
  60412. set: function (value) {
  60413. this.imageProcessingConfiguration.vignetteCentreY = value;
  60414. },
  60415. enumerable: true,
  60416. configurable: true
  60417. });
  60418. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  60419. /**
  60420. * Gets Vignette weight or intensity of the vignette effect.
  60421. */
  60422. get: function () {
  60423. return this.imageProcessingConfiguration.vignetteWeight;
  60424. },
  60425. /**
  60426. * Sets Vignette weight or intensity of the vignette effect.
  60427. */
  60428. set: function (value) {
  60429. this.imageProcessingConfiguration.vignetteWeight = value;
  60430. },
  60431. enumerable: true,
  60432. configurable: true
  60433. });
  60434. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  60435. /**
  60436. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60437. * if vignetteEnabled is set to true.
  60438. */
  60439. get: function () {
  60440. return this.imageProcessingConfiguration.vignetteColor;
  60441. },
  60442. /**
  60443. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60444. * if vignetteEnabled is set to true.
  60445. */
  60446. set: function (value) {
  60447. this.imageProcessingConfiguration.vignetteColor = value;
  60448. },
  60449. enumerable: true,
  60450. configurable: true
  60451. });
  60452. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  60453. /**
  60454. * Gets Camera field of view used by the Vignette effect.
  60455. */
  60456. get: function () {
  60457. return this.imageProcessingConfiguration.vignetteCameraFov;
  60458. },
  60459. /**
  60460. * Sets Camera field of view used by the Vignette effect.
  60461. */
  60462. set: function (value) {
  60463. this.imageProcessingConfiguration.vignetteCameraFov = value;
  60464. },
  60465. enumerable: true,
  60466. configurable: true
  60467. });
  60468. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  60469. /**
  60470. * Gets the vignette blend mode allowing different kind of effect.
  60471. */
  60472. get: function () {
  60473. return this.imageProcessingConfiguration.vignetteBlendMode;
  60474. },
  60475. /**
  60476. * Sets the vignette blend mode allowing different kind of effect.
  60477. */
  60478. set: function (value) {
  60479. this.imageProcessingConfiguration.vignetteBlendMode = value;
  60480. },
  60481. enumerable: true,
  60482. configurable: true
  60483. });
  60484. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  60485. /**
  60486. * Gets wether the vignette effect is enabled.
  60487. */
  60488. get: function () {
  60489. return this.imageProcessingConfiguration.vignetteEnabled;
  60490. },
  60491. /**
  60492. * Sets wether the vignette effect is enabled.
  60493. */
  60494. set: function (value) {
  60495. this.imageProcessingConfiguration.vignetteEnabled = value;
  60496. },
  60497. enumerable: true,
  60498. configurable: true
  60499. });
  60500. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  60501. /**
  60502. * Gets wether the input of the processing is in Gamma or Linear Space.
  60503. */
  60504. get: function () {
  60505. return this._fromLinearSpace;
  60506. },
  60507. /**
  60508. * Sets wether the input of the processing is in Gamma or Linear Space.
  60509. */
  60510. set: function (value) {
  60511. if (this._fromLinearSpace === value) {
  60512. return;
  60513. }
  60514. this._fromLinearSpace = value;
  60515. this._updateParameters();
  60516. },
  60517. enumerable: true,
  60518. configurable: true
  60519. });
  60520. ImageProcessingPostProcess.prototype.getClassName = function () {
  60521. return "ImageProcessingPostProcess";
  60522. };
  60523. ImageProcessingPostProcess.prototype._updateParameters = function () {
  60524. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  60525. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  60526. var defines = "";
  60527. for (var define in this._defines) {
  60528. if (this._defines[define]) {
  60529. defines += "#define " + define + ";\r\n";
  60530. }
  60531. }
  60532. var samplers = ["textureSampler"];
  60533. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  60534. var uniforms = ["scale"];
  60535. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  60536. this.updateEffect(defines, uniforms, samplers);
  60537. };
  60538. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  60539. _super.prototype.dispose.call(this, camera);
  60540. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60541. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60542. }
  60543. this.imageProcessingConfiguration.applyByPostProcess = false;
  60544. };
  60545. __decorate([
  60546. BABYLON.serialize()
  60547. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  60548. return ImageProcessingPostProcess;
  60549. }(BABYLON.PostProcess));
  60550. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  60551. })(BABYLON || (BABYLON = {}));
  60552. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  60553. var BABYLON;
  60554. (function (BABYLON) {
  60555. var BlurPostProcess = /** @class */ (function (_super) {
  60556. __extends(BlurPostProcess, _super);
  60557. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  60558. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60559. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60560. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  60561. _this.direction = direction;
  60562. _this._packedFloat = false;
  60563. _this.onApplyObservable.add(function (effect) {
  60564. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  60565. });
  60566. _this.kernel = kernel;
  60567. return _this;
  60568. }
  60569. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  60570. /**
  60571. * Gets the length in pixels of the blur sample region
  60572. */
  60573. get: function () {
  60574. return this._idealKernel;
  60575. },
  60576. /**
  60577. * Sets the length in pixels of the blur sample region
  60578. */
  60579. set: function (v) {
  60580. if (this._idealKernel === v) {
  60581. return;
  60582. }
  60583. v = Math.max(v, 1);
  60584. this._idealKernel = v;
  60585. this._kernel = this._nearestBestKernel(v);
  60586. this._updateParameters();
  60587. },
  60588. enumerable: true,
  60589. configurable: true
  60590. });
  60591. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60592. /**
  60593. * Gets wether or not the blur is unpacking/repacking floats
  60594. */
  60595. get: function () {
  60596. return this._packedFloat;
  60597. },
  60598. /**
  60599. * Sets wether or not the blur needs to unpack/repack floats
  60600. */
  60601. set: function (v) {
  60602. if (this._packedFloat === v) {
  60603. return;
  60604. }
  60605. this._packedFloat = v;
  60606. this._updateParameters();
  60607. },
  60608. enumerable: true,
  60609. configurable: true
  60610. });
  60611. BlurPostProcess.prototype._updateParameters = function () {
  60612. // Generate sampling offsets and weights
  60613. var N = this._kernel;
  60614. var centerIndex = (N - 1) / 2;
  60615. // Generate Gaussian sampling weights over kernel
  60616. var offsets = [];
  60617. var weights = [];
  60618. var totalWeight = 0;
  60619. for (var i = 0; i < N; i++) {
  60620. var u = i / (N - 1);
  60621. var w = this._gaussianWeight(u * 2.0 - 1);
  60622. offsets[i] = (i - centerIndex);
  60623. weights[i] = w;
  60624. totalWeight += w;
  60625. }
  60626. // Normalize weights
  60627. for (var i = 0; i < weights.length; i++) {
  60628. weights[i] /= totalWeight;
  60629. }
  60630. // Optimize: combine samples to take advantage of hardware linear sampling
  60631. // Walk from left to center, combining pairs (symmetrically)
  60632. var linearSamplingWeights = [];
  60633. var linearSamplingOffsets = [];
  60634. var linearSamplingMap = [];
  60635. for (var i = 0; i <= centerIndex; i += 2) {
  60636. var j = Math.min(i + 1, Math.floor(centerIndex));
  60637. var singleCenterSample = i === j;
  60638. if (singleCenterSample) {
  60639. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60640. }
  60641. else {
  60642. var sharedCell = j === centerIndex;
  60643. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60644. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60645. if (offsetLinear === 0) {
  60646. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60647. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60648. }
  60649. else {
  60650. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60651. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60652. }
  60653. }
  60654. }
  60655. for (var i = 0; i < linearSamplingMap.length; i++) {
  60656. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60657. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60658. }
  60659. // Replace with optimized
  60660. offsets = linearSamplingOffsets;
  60661. weights = linearSamplingWeights;
  60662. // Generate shaders
  60663. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60664. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60665. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60666. var defines = "";
  60667. for (var i = 0; i < varyingCount; i++) {
  60668. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60669. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60670. }
  60671. var depCount = 0;
  60672. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60673. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60674. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60675. depCount++;
  60676. }
  60677. if (this.packedFloat) {
  60678. defines += "#define PACKEDFLOAT 1";
  60679. }
  60680. this.updateEffect(defines, null, null, {
  60681. varyingCount: varyingCount,
  60682. depCount: depCount
  60683. });
  60684. };
  60685. /**
  60686. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  60687. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  60688. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  60689. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  60690. * The gaps between physical kernels are compensated for in the weighting of the samples
  60691. * @param idealKernel Ideal blur kernel.
  60692. * @return Nearest best kernel.
  60693. */
  60694. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  60695. var v = Math.round(idealKernel);
  60696. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  60697. var k = _a[_i];
  60698. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  60699. return Math.max(k, 3);
  60700. }
  60701. }
  60702. return Math.max(v, 3);
  60703. };
  60704. /**
  60705. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  60706. * @param x The point on the Gaussian distribution to sample.
  60707. * @return the value of the Gaussian function at x.
  60708. */
  60709. BlurPostProcess.prototype._gaussianWeight = function (x) {
  60710. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  60711. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  60712. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  60713. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  60714. // truncated at around 1.3% of peak strength.
  60715. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  60716. var sigma = (1 / 3);
  60717. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  60718. var exponent = -((x * x) / (2.0 * sigma * sigma));
  60719. var weight = (1.0 / denominator) * Math.exp(exponent);
  60720. return weight;
  60721. };
  60722. /**
  60723. * Generates a string that can be used as a floating point number in GLSL.
  60724. * @param x Value to print.
  60725. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  60726. * @return GLSL float string.
  60727. */
  60728. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  60729. if (decimalFigures === void 0) { decimalFigures = 8; }
  60730. return x.toFixed(decimalFigures).replace(/0+$/, '');
  60731. };
  60732. return BlurPostProcess;
  60733. }(BABYLON.PostProcess));
  60734. BABYLON.BlurPostProcess = BlurPostProcess;
  60735. })(BABYLON || (BABYLON = {}));
  60736. //# sourceMappingURL=babylon.blurPostProcess.js.map
  60737. var BABYLON;
  60738. (function (BABYLON) {
  60739. var Bone = /** @class */ (function (_super) {
  60740. __extends(Bone, _super);
  60741. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60742. if (parentBone === void 0) { parentBone = null; }
  60743. if (localMatrix === void 0) { localMatrix = null; }
  60744. if (restPose === void 0) { restPose = null; }
  60745. if (baseMatrix === void 0) { baseMatrix = null; }
  60746. if (index === void 0) { index = null; }
  60747. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60748. _this.name = name;
  60749. _this.children = new Array();
  60750. _this.animations = new Array();
  60751. // Set this value to map this bone to a different index in the transform matrices.
  60752. // Set this value to -1 to exclude the bone from the transform matrices.
  60753. _this._index = null;
  60754. _this._worldTransform = new BABYLON.Matrix();
  60755. _this._absoluteTransform = new BABYLON.Matrix();
  60756. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60757. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60758. _this._scaleVector = BABYLON.Vector3.One();
  60759. _this._negateScaleChildren = BABYLON.Vector3.One();
  60760. _this._scalingDeterminant = 1;
  60761. _this._skeleton = skeleton;
  60762. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60763. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60764. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60765. _this._index = index;
  60766. skeleton.bones.push(_this);
  60767. _this.setParent(parentBone, false);
  60768. _this._updateDifferenceMatrix();
  60769. return _this;
  60770. }
  60771. Object.defineProperty(Bone.prototype, "_matrix", {
  60772. get: function () {
  60773. return this._localMatrix;
  60774. },
  60775. set: function (val) {
  60776. if (this._localMatrix) {
  60777. this._localMatrix.copyFrom(val);
  60778. }
  60779. else {
  60780. this._localMatrix = val;
  60781. }
  60782. },
  60783. enumerable: true,
  60784. configurable: true
  60785. });
  60786. // Members
  60787. Bone.prototype.getSkeleton = function () {
  60788. return this._skeleton;
  60789. };
  60790. Bone.prototype.getParent = function () {
  60791. return this._parent;
  60792. };
  60793. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60794. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60795. if (this._parent === parent) {
  60796. return;
  60797. }
  60798. if (this._parent) {
  60799. var index = this._parent.children.indexOf(this);
  60800. if (index !== -1) {
  60801. this._parent.children.splice(index, 1);
  60802. }
  60803. }
  60804. this._parent = parent;
  60805. if (this._parent) {
  60806. this._parent.children.push(this);
  60807. }
  60808. if (updateDifferenceMatrix) {
  60809. this._updateDifferenceMatrix();
  60810. }
  60811. };
  60812. Bone.prototype.getLocalMatrix = function () {
  60813. return this._localMatrix;
  60814. };
  60815. Bone.prototype.getBaseMatrix = function () {
  60816. return this._baseMatrix;
  60817. };
  60818. Bone.prototype.getRestPose = function () {
  60819. return this._restPose;
  60820. };
  60821. Bone.prototype.returnToRest = function () {
  60822. this.updateMatrix(this._restPose.clone());
  60823. };
  60824. Bone.prototype.getWorldMatrix = function () {
  60825. return this._worldTransform;
  60826. };
  60827. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60828. return this._invertedAbsoluteTransform;
  60829. };
  60830. Bone.prototype.getAbsoluteTransform = function () {
  60831. return this._absoluteTransform;
  60832. };
  60833. Object.defineProperty(Bone.prototype, "position", {
  60834. // Properties (matches AbstractMesh properties)
  60835. get: function () {
  60836. return this.getPosition();
  60837. },
  60838. set: function (newPosition) {
  60839. this.setPosition(newPosition);
  60840. },
  60841. enumerable: true,
  60842. configurable: true
  60843. });
  60844. Object.defineProperty(Bone.prototype, "rotation", {
  60845. get: function () {
  60846. return this.getRotation();
  60847. },
  60848. set: function (newRotation) {
  60849. this.setRotation(newRotation);
  60850. },
  60851. enumerable: true,
  60852. configurable: true
  60853. });
  60854. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60855. get: function () {
  60856. return this.getRotationQuaternion();
  60857. },
  60858. set: function (newRotation) {
  60859. this.setRotationQuaternion(newRotation);
  60860. },
  60861. enumerable: true,
  60862. configurable: true
  60863. });
  60864. Object.defineProperty(Bone.prototype, "scaling", {
  60865. get: function () {
  60866. return this.getScale();
  60867. },
  60868. set: function (newScaling) {
  60869. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60870. },
  60871. enumerable: true,
  60872. configurable: true
  60873. });
  60874. // Methods
  60875. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60876. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60877. this._baseMatrix = matrix.clone();
  60878. this._localMatrix = matrix.clone();
  60879. this._skeleton._markAsDirty();
  60880. if (updateDifferenceMatrix) {
  60881. this._updateDifferenceMatrix();
  60882. }
  60883. };
  60884. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60885. if (!rootMatrix) {
  60886. rootMatrix = this._baseMatrix;
  60887. }
  60888. if (this._parent) {
  60889. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60890. }
  60891. else {
  60892. this._absoluteTransform.copyFrom(rootMatrix);
  60893. }
  60894. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60895. for (var index = 0; index < this.children.length; index++) {
  60896. this.children[index]._updateDifferenceMatrix();
  60897. }
  60898. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60899. };
  60900. Bone.prototype.markAsDirty = function () {
  60901. this._currentRenderId++;
  60902. this._skeleton._markAsDirty();
  60903. };
  60904. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60905. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60906. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60907. // all animation may be coming from a library skeleton, so may need to create animation
  60908. if (this.animations.length === 0) {
  60909. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60910. this.animations[0].setKeys([]);
  60911. }
  60912. // get animation info / verify there is such a range from the source bone
  60913. var sourceRange = source.animations[0].getRange(rangeName);
  60914. if (!sourceRange) {
  60915. return false;
  60916. }
  60917. var from = sourceRange.from;
  60918. var to = sourceRange.to;
  60919. var sourceKeys = source.animations[0].getKeys();
  60920. // rescaling prep
  60921. var sourceBoneLength = source.length;
  60922. var sourceParent = source.getParent();
  60923. var parent = this.getParent();
  60924. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60925. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60926. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60927. var destKeys = this.animations[0].getKeys();
  60928. // loop vars declaration
  60929. var orig;
  60930. var origTranslation;
  60931. var mat;
  60932. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60933. orig = sourceKeys[key];
  60934. if (orig.frame >= from && orig.frame <= to) {
  60935. if (rescaleAsRequired) {
  60936. mat = orig.value.clone();
  60937. // scale based on parent ratio, when bone has parent
  60938. if (parentScalingReqd) {
  60939. origTranslation = mat.getTranslation();
  60940. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60941. // scale based on skeleton dimension ratio when root bone, and value is passed
  60942. }
  60943. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60944. origTranslation = mat.getTranslation();
  60945. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60946. // use original when root bone, and no data for skelDimensionsRatio
  60947. }
  60948. else {
  60949. mat = orig.value;
  60950. }
  60951. }
  60952. else {
  60953. mat = orig.value;
  60954. }
  60955. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60956. }
  60957. }
  60958. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60959. return true;
  60960. };
  60961. /**
  60962. * Translate the bone in local or world space.
  60963. * @param vec The amount to translate the bone.
  60964. * @param space The space that the translation is in.
  60965. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60966. */
  60967. Bone.prototype.translate = function (vec, space, mesh) {
  60968. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60969. var lm = this.getLocalMatrix();
  60970. if (space == BABYLON.Space.LOCAL) {
  60971. lm.m[12] += vec.x;
  60972. lm.m[13] += vec.y;
  60973. lm.m[14] += vec.z;
  60974. }
  60975. else {
  60976. var wm = null;
  60977. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60978. if (mesh) {
  60979. wm = mesh.getWorldMatrix();
  60980. }
  60981. this._skeleton.computeAbsoluteTransforms();
  60982. var tmat = Bone._tmpMats[0];
  60983. var tvec = Bone._tmpVecs[0];
  60984. if (this._parent) {
  60985. if (mesh && wm) {
  60986. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60987. tmat.multiplyToRef(wm, tmat);
  60988. }
  60989. else {
  60990. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60991. }
  60992. }
  60993. tmat.m[12] = 0;
  60994. tmat.m[13] = 0;
  60995. tmat.m[14] = 0;
  60996. tmat.invert();
  60997. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60998. lm.m[12] += tvec.x;
  60999. lm.m[13] += tvec.y;
  61000. lm.m[14] += tvec.z;
  61001. }
  61002. this.markAsDirty();
  61003. };
  61004. /**
  61005. * Set the postion of the bone in local or world space.
  61006. * @param position The position to set the bone.
  61007. * @param space The space that the position is in.
  61008. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61009. */
  61010. Bone.prototype.setPosition = function (position, space, mesh) {
  61011. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61012. var lm = this.getLocalMatrix();
  61013. if (space == BABYLON.Space.LOCAL) {
  61014. lm.m[12] = position.x;
  61015. lm.m[13] = position.y;
  61016. lm.m[14] = position.z;
  61017. }
  61018. else {
  61019. var wm = null;
  61020. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61021. if (mesh) {
  61022. wm = mesh.getWorldMatrix();
  61023. }
  61024. this._skeleton.computeAbsoluteTransforms();
  61025. var tmat = Bone._tmpMats[0];
  61026. var vec = Bone._tmpVecs[0];
  61027. if (this._parent) {
  61028. if (mesh && wm) {
  61029. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61030. tmat.multiplyToRef(wm, tmat);
  61031. }
  61032. else {
  61033. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61034. }
  61035. }
  61036. tmat.invert();
  61037. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  61038. lm.m[12] = vec.x;
  61039. lm.m[13] = vec.y;
  61040. lm.m[14] = vec.z;
  61041. }
  61042. this.markAsDirty();
  61043. };
  61044. /**
  61045. * Set the absolute postion of the bone (world space).
  61046. * @param position The position to set the bone.
  61047. * @param mesh The mesh that this bone is attached to.
  61048. */
  61049. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  61050. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  61051. };
  61052. /**
  61053. * Set the scale of the bone on the x, y and z axes.
  61054. * @param x The scale of the bone on the x axis.
  61055. * @param x The scale of the bone on the y axis.
  61056. * @param z The scale of the bone on the z axis.
  61057. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61058. */
  61059. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  61060. if (scaleChildren === void 0) { scaleChildren = false; }
  61061. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  61062. if (!scaleChildren) {
  61063. this._negateScaleChildren.x = 1 / x;
  61064. this._negateScaleChildren.y = 1 / y;
  61065. this._negateScaleChildren.z = 1 / z;
  61066. }
  61067. this._syncScaleVector();
  61068. }
  61069. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  61070. };
  61071. /**
  61072. * Scale the bone on the x, y and z axes.
  61073. * @param x The amount to scale the bone on the x axis.
  61074. * @param x The amount to scale the bone on the y axis.
  61075. * @param z The amount to scale the bone on the z axis.
  61076. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61077. */
  61078. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  61079. if (scaleChildren === void 0) { scaleChildren = false; }
  61080. var locMat = this.getLocalMatrix();
  61081. var origLocMat = Bone._tmpMats[0];
  61082. origLocMat.copyFrom(locMat);
  61083. var origLocMatInv = Bone._tmpMats[1];
  61084. origLocMatInv.copyFrom(origLocMat);
  61085. origLocMatInv.invert();
  61086. var scaleMat = Bone._tmpMats[2];
  61087. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  61088. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  61089. this._scaleVector.x *= x;
  61090. this._scaleVector.y *= y;
  61091. this._scaleVector.z *= z;
  61092. locMat.multiplyToRef(origLocMatInv, locMat);
  61093. locMat.multiplyToRef(scaleMat, locMat);
  61094. locMat.multiplyToRef(origLocMat, locMat);
  61095. var parent = this.getParent();
  61096. if (parent) {
  61097. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  61098. }
  61099. else {
  61100. this.getAbsoluteTransform().copyFrom(locMat);
  61101. }
  61102. var len = this.children.length;
  61103. scaleMat.invert();
  61104. for (var i = 0; i < len; i++) {
  61105. var child = this.children[i];
  61106. var cm = child.getLocalMatrix();
  61107. cm.multiplyToRef(scaleMat, cm);
  61108. var lm = child.getLocalMatrix();
  61109. lm.m[12] *= x;
  61110. lm.m[13] *= y;
  61111. lm.m[14] *= z;
  61112. }
  61113. this.computeAbsoluteTransforms();
  61114. if (scaleChildren) {
  61115. for (var i = 0; i < len; i++) {
  61116. this.children[i].scale(x, y, z, scaleChildren);
  61117. }
  61118. }
  61119. this.markAsDirty();
  61120. };
  61121. /**
  61122. * Set the yaw, pitch, and roll of the bone in local or world space.
  61123. * @param yaw The rotation of the bone on the y axis.
  61124. * @param pitch The rotation of the bone on the x axis.
  61125. * @param roll The rotation of the bone on the z axis.
  61126. * @param space The space that the axes of rotation are in.
  61127. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61128. */
  61129. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  61130. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61131. var rotMat = Bone._tmpMats[0];
  61132. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  61133. var rotMatInv = Bone._tmpMats[1];
  61134. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61135. rotMatInv.multiplyToRef(rotMat, rotMat);
  61136. this._rotateWithMatrix(rotMat, space, mesh);
  61137. };
  61138. /**
  61139. * Rotate the bone on an axis in local or world space.
  61140. * @param axis The axis to rotate the bone on.
  61141. * @param amount The amount to rotate the bone.
  61142. * @param space The space that the axis is in.
  61143. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61144. */
  61145. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  61146. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61147. var rmat = Bone._tmpMats[0];
  61148. rmat.m[12] = 0;
  61149. rmat.m[13] = 0;
  61150. rmat.m[14] = 0;
  61151. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  61152. this._rotateWithMatrix(rmat, space, mesh);
  61153. };
  61154. /**
  61155. * Set the rotation of the bone to a particular axis angle in local or world space.
  61156. * @param axis The axis to rotate the bone on.
  61157. * @param angle The angle that the bone should be rotated to.
  61158. * @param space The space that the axis is in.
  61159. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61160. */
  61161. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  61162. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61163. var rotMat = Bone._tmpMats[0];
  61164. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  61165. var rotMatInv = Bone._tmpMats[1];
  61166. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61167. rotMatInv.multiplyToRef(rotMat, rotMat);
  61168. this._rotateWithMatrix(rotMat, space, mesh);
  61169. };
  61170. /**
  61171. * Set the euler rotation of the bone in local of world space.
  61172. * @param rotation The euler rotation that the bone should be set to.
  61173. * @param space The space that the rotation is in.
  61174. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61175. */
  61176. Bone.prototype.setRotation = function (rotation, space, mesh) {
  61177. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61178. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  61179. };
  61180. /**
  61181. * Set the quaternion rotation of the bone in local of world space.
  61182. * @param quat The quaternion rotation that the bone should be set to.
  61183. * @param space The space that the rotation is in.
  61184. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61185. */
  61186. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  61187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61188. var rotMatInv = Bone._tmpMats[0];
  61189. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61190. var rotMat = Bone._tmpMats[1];
  61191. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  61192. rotMatInv.multiplyToRef(rotMat, rotMat);
  61193. this._rotateWithMatrix(rotMat, space, mesh);
  61194. };
  61195. /**
  61196. * Set the rotation matrix of the bone in local of world space.
  61197. * @param rotMat The rotation matrix that the bone should be set to.
  61198. * @param space The space that the rotation is in.
  61199. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61200. */
  61201. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  61202. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61203. var rotMatInv = Bone._tmpMats[0];
  61204. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61205. var rotMat2 = Bone._tmpMats[1];
  61206. rotMat2.copyFrom(rotMat);
  61207. rotMatInv.multiplyToRef(rotMat, rotMat2);
  61208. this._rotateWithMatrix(rotMat2, space, mesh);
  61209. };
  61210. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  61211. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61212. var lmat = this.getLocalMatrix();
  61213. var lx = lmat.m[12];
  61214. var ly = lmat.m[13];
  61215. var lz = lmat.m[14];
  61216. var parent = this.getParent();
  61217. var parentScale = Bone._tmpMats[3];
  61218. var parentScaleInv = Bone._tmpMats[4];
  61219. if (parent) {
  61220. if (space == BABYLON.Space.WORLD) {
  61221. if (mesh) {
  61222. parentScale.copyFrom(mesh.getWorldMatrix());
  61223. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  61224. }
  61225. else {
  61226. parentScale.copyFrom(parent.getAbsoluteTransform());
  61227. }
  61228. }
  61229. else {
  61230. parentScale = parent._scaleMatrix;
  61231. }
  61232. parentScaleInv.copyFrom(parentScale);
  61233. parentScaleInv.invert();
  61234. lmat.multiplyToRef(parentScale, lmat);
  61235. lmat.multiplyToRef(rmat, lmat);
  61236. lmat.multiplyToRef(parentScaleInv, lmat);
  61237. }
  61238. else {
  61239. if (space == BABYLON.Space.WORLD && mesh) {
  61240. parentScale.copyFrom(mesh.getWorldMatrix());
  61241. parentScaleInv.copyFrom(parentScale);
  61242. parentScaleInv.invert();
  61243. lmat.multiplyToRef(parentScale, lmat);
  61244. lmat.multiplyToRef(rmat, lmat);
  61245. lmat.multiplyToRef(parentScaleInv, lmat);
  61246. }
  61247. else {
  61248. lmat.multiplyToRef(rmat, lmat);
  61249. }
  61250. }
  61251. lmat.m[12] = lx;
  61252. lmat.m[13] = ly;
  61253. lmat.m[14] = lz;
  61254. this.computeAbsoluteTransforms();
  61255. this.markAsDirty();
  61256. };
  61257. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  61258. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61259. if (space == BABYLON.Space.WORLD) {
  61260. var scaleMatrix = Bone._tmpMats[2];
  61261. scaleMatrix.copyFrom(this._scaleMatrix);
  61262. rotMatInv.copyFrom(this.getAbsoluteTransform());
  61263. if (mesh) {
  61264. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  61265. var meshScale = Bone._tmpMats[3];
  61266. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  61267. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  61268. }
  61269. rotMatInv.invert();
  61270. scaleMatrix.m[0] *= this._scalingDeterminant;
  61271. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61272. }
  61273. else {
  61274. rotMatInv.copyFrom(this.getLocalMatrix());
  61275. rotMatInv.invert();
  61276. var scaleMatrix = Bone._tmpMats[2];
  61277. scaleMatrix.copyFrom(this._scaleMatrix);
  61278. if (this._parent) {
  61279. var pscaleMatrix = Bone._tmpMats[3];
  61280. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  61281. pscaleMatrix.invert();
  61282. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  61283. }
  61284. else {
  61285. scaleMatrix.m[0] *= this._scalingDeterminant;
  61286. }
  61287. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61288. }
  61289. };
  61290. /**
  61291. * Get the scale of the bone
  61292. * @returns the scale of the bone
  61293. */
  61294. Bone.prototype.getScale = function () {
  61295. return this._scaleVector.clone();
  61296. };
  61297. /**
  61298. * Copy the scale of the bone to a vector3.
  61299. * @param result The vector3 to copy the scale to
  61300. */
  61301. Bone.prototype.getScaleToRef = function (result) {
  61302. result.copyFrom(this._scaleVector);
  61303. };
  61304. /**
  61305. * Get the position of the bone in local or world space.
  61306. * @param space The space that the returned position is in.
  61307. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61308. * @returns The position of the bone
  61309. */
  61310. Bone.prototype.getPosition = function (space, mesh) {
  61311. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61312. if (mesh === void 0) { mesh = null; }
  61313. var pos = BABYLON.Vector3.Zero();
  61314. this.getPositionToRef(space, mesh, pos);
  61315. return pos;
  61316. };
  61317. /**
  61318. * Copy the position of the bone to a vector3 in local or world space.
  61319. * @param space The space that the returned position is in.
  61320. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61321. * @param result The vector3 to copy the position to.
  61322. */
  61323. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  61324. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61325. if (space == BABYLON.Space.LOCAL) {
  61326. var lm = this.getLocalMatrix();
  61327. result.x = lm.m[12];
  61328. result.y = lm.m[13];
  61329. result.z = lm.m[14];
  61330. }
  61331. else {
  61332. var wm = null;
  61333. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61334. if (mesh) {
  61335. wm = mesh.getWorldMatrix();
  61336. }
  61337. this._skeleton.computeAbsoluteTransforms();
  61338. var tmat = Bone._tmpMats[0];
  61339. if (mesh && wm) {
  61340. tmat.copyFrom(this.getAbsoluteTransform());
  61341. tmat.multiplyToRef(wm, tmat);
  61342. }
  61343. else {
  61344. tmat = this.getAbsoluteTransform();
  61345. }
  61346. result.x = tmat.m[12];
  61347. result.y = tmat.m[13];
  61348. result.z = tmat.m[14];
  61349. }
  61350. };
  61351. /**
  61352. * Get the absolute position of the bone (world space).
  61353. * @param mesh The mesh that this bone is attached to.
  61354. * @returns The absolute position of the bone
  61355. */
  61356. Bone.prototype.getAbsolutePosition = function (mesh) {
  61357. if (mesh === void 0) { mesh = null; }
  61358. var pos = BABYLON.Vector3.Zero();
  61359. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  61360. return pos;
  61361. };
  61362. /**
  61363. * Copy the absolute position of the bone (world space) to the result param.
  61364. * @param mesh The mesh that this bone is attached to.
  61365. * @param result The vector3 to copy the absolute position to.
  61366. */
  61367. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  61368. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  61369. };
  61370. /**
  61371. * Compute the absolute transforms of this bone and its children.
  61372. */
  61373. Bone.prototype.computeAbsoluteTransforms = function () {
  61374. if (this._parent) {
  61375. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61376. }
  61377. else {
  61378. this._absoluteTransform.copyFrom(this._localMatrix);
  61379. var poseMatrix = this._skeleton.getPoseMatrix();
  61380. if (poseMatrix) {
  61381. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  61382. }
  61383. }
  61384. var children = this.children;
  61385. var len = children.length;
  61386. for (var i = 0; i < len; i++) {
  61387. children[i].computeAbsoluteTransforms();
  61388. }
  61389. };
  61390. Bone.prototype._syncScaleVector = function () {
  61391. var lm = this.getLocalMatrix();
  61392. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  61393. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  61394. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  61395. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  61396. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  61397. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  61398. this._scaleVector.x = xs * Math.sqrt(xsq);
  61399. this._scaleVector.y = ys * Math.sqrt(ysq);
  61400. this._scaleVector.z = zs * Math.sqrt(zsq);
  61401. if (this._parent) {
  61402. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  61403. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  61404. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  61405. }
  61406. 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);
  61407. };
  61408. /**
  61409. * Get the world direction from an axis that is in the local space of the bone.
  61410. * @param localAxis The local direction that is used to compute the world direction.
  61411. * @param mesh The mesh that this bone is attached to.
  61412. * @returns The world direction
  61413. */
  61414. Bone.prototype.getDirection = function (localAxis, mesh) {
  61415. if (mesh === void 0) { mesh = null; }
  61416. var result = BABYLON.Vector3.Zero();
  61417. this.getDirectionToRef(localAxis, mesh, result);
  61418. return result;
  61419. };
  61420. /**
  61421. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  61422. * @param localAxis The local direction that is used to compute the world direction.
  61423. * @param mesh The mesh that this bone is attached to.
  61424. * @param result The vector3 that the world direction will be copied to.
  61425. */
  61426. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  61427. if (mesh === void 0) { mesh = null; }
  61428. var wm = null;
  61429. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61430. if (mesh) {
  61431. wm = mesh.getWorldMatrix();
  61432. }
  61433. this._skeleton.computeAbsoluteTransforms();
  61434. var mat = Bone._tmpMats[0];
  61435. mat.copyFrom(this.getAbsoluteTransform());
  61436. if (mesh && wm) {
  61437. mat.multiplyToRef(wm, mat);
  61438. }
  61439. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  61440. result.normalize();
  61441. };
  61442. /**
  61443. * Get the euler rotation of the bone in local or world space.
  61444. * @param space The space that the rotation should be in.
  61445. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61446. * @returns The euler rotation
  61447. */
  61448. Bone.prototype.getRotation = function (space, mesh) {
  61449. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61450. if (mesh === void 0) { mesh = null; }
  61451. var result = BABYLON.Vector3.Zero();
  61452. this.getRotationToRef(space, mesh, result);
  61453. return result;
  61454. };
  61455. /**
  61456. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  61457. * @param space The space that the rotation should be in.
  61458. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61459. * @param result The vector3 that the rotation should be copied to.
  61460. */
  61461. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  61462. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61463. if (mesh === void 0) { mesh = null; }
  61464. var quat = Bone._tmpQuat;
  61465. this.getRotationQuaternionToRef(space, mesh, quat);
  61466. quat.toEulerAnglesToRef(result);
  61467. };
  61468. /**
  61469. * Get the quaternion rotation of the bone in either local or world space.
  61470. * @param space The space that the rotation should be in.
  61471. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61472. * @returns The quaternion rotation
  61473. */
  61474. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  61475. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61476. if (mesh === void 0) { mesh = null; }
  61477. var result = BABYLON.Quaternion.Identity();
  61478. this.getRotationQuaternionToRef(space, mesh, result);
  61479. return result;
  61480. };
  61481. /**
  61482. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  61483. * @param space The space that the rotation should be in.
  61484. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61485. * @param result The quaternion that the rotation should be copied to.
  61486. */
  61487. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  61488. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61489. if (mesh === void 0) { mesh = null; }
  61490. if (space == BABYLON.Space.LOCAL) {
  61491. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61492. }
  61493. else {
  61494. var mat = Bone._tmpMats[0];
  61495. var amat = this.getAbsoluteTransform();
  61496. if (mesh) {
  61497. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61498. }
  61499. else {
  61500. mat.copyFrom(amat);
  61501. }
  61502. mat.m[0] *= this._scalingDeterminant;
  61503. mat.m[1] *= this._scalingDeterminant;
  61504. mat.m[2] *= this._scalingDeterminant;
  61505. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61506. }
  61507. };
  61508. /**
  61509. * Get the rotation matrix of the bone in local or world space.
  61510. * @param space The space that the rotation should be in.
  61511. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61512. * @returns The rotation matrix
  61513. */
  61514. Bone.prototype.getRotationMatrix = function (space, mesh) {
  61515. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61516. var result = BABYLON.Matrix.Identity();
  61517. this.getRotationMatrixToRef(space, mesh, result);
  61518. return result;
  61519. };
  61520. /**
  61521. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  61522. * @param space The space that the rotation should be in.
  61523. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61524. * @param result The quaternion that the rotation should be copied to.
  61525. */
  61526. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  61527. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61528. if (space == BABYLON.Space.LOCAL) {
  61529. this.getLocalMatrix().getRotationMatrixToRef(result);
  61530. }
  61531. else {
  61532. var mat = Bone._tmpMats[0];
  61533. var amat = this.getAbsoluteTransform();
  61534. if (mesh) {
  61535. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61536. }
  61537. else {
  61538. mat.copyFrom(amat);
  61539. }
  61540. mat.m[0] *= this._scalingDeterminant;
  61541. mat.m[1] *= this._scalingDeterminant;
  61542. mat.m[2] *= this._scalingDeterminant;
  61543. mat.getRotationMatrixToRef(result);
  61544. }
  61545. };
  61546. /**
  61547. * Get the world position of a point that is in the local space of the bone.
  61548. * @param position The local position
  61549. * @param mesh The mesh that this bone is attached to.
  61550. * @returns The world position
  61551. */
  61552. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  61553. if (mesh === void 0) { mesh = null; }
  61554. var result = BABYLON.Vector3.Zero();
  61555. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  61556. return result;
  61557. };
  61558. /**
  61559. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  61560. * @param position The local position
  61561. * @param mesh The mesh that this bone is attached to.
  61562. * @param result The vector3 that the world position should be copied to.
  61563. */
  61564. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  61565. if (mesh === void 0) { mesh = null; }
  61566. var wm = null;
  61567. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61568. if (mesh) {
  61569. wm = mesh.getWorldMatrix();
  61570. }
  61571. this._skeleton.computeAbsoluteTransforms();
  61572. var tmat = Bone._tmpMats[0];
  61573. if (mesh && wm) {
  61574. tmat.copyFrom(this.getAbsoluteTransform());
  61575. tmat.multiplyToRef(wm, tmat);
  61576. }
  61577. else {
  61578. tmat = this.getAbsoluteTransform();
  61579. }
  61580. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61581. };
  61582. /**
  61583. * Get the local position of a point that is in world space.
  61584. * @param position The world position
  61585. * @param mesh The mesh that this bone is attached to.
  61586. * @returns The local position
  61587. */
  61588. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61589. if (mesh === void 0) { mesh = null; }
  61590. var result = BABYLON.Vector3.Zero();
  61591. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61592. return result;
  61593. };
  61594. /**
  61595. * Get the local position of a point that is in world space and copy it to the result param.
  61596. * @param position The world position
  61597. * @param mesh The mesh that this bone is attached to.
  61598. * @param result The vector3 that the local position should be copied to.
  61599. */
  61600. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61601. if (mesh === void 0) { mesh = null; }
  61602. var wm = null;
  61603. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61604. if (mesh) {
  61605. wm = mesh.getWorldMatrix();
  61606. }
  61607. this._skeleton.computeAbsoluteTransforms();
  61608. var tmat = Bone._tmpMats[0];
  61609. tmat.copyFrom(this.getAbsoluteTransform());
  61610. if (mesh && wm) {
  61611. tmat.multiplyToRef(wm, tmat);
  61612. }
  61613. tmat.invert();
  61614. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61615. };
  61616. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61617. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61618. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61619. return Bone;
  61620. }(BABYLON.Node));
  61621. BABYLON.Bone = Bone;
  61622. })(BABYLON || (BABYLON = {}));
  61623. //# sourceMappingURL=babylon.bone.js.map
  61624. var BABYLON;
  61625. (function (BABYLON) {
  61626. var BoneIKController = /** @class */ (function () {
  61627. function BoneIKController(mesh, bone, options) {
  61628. this.targetPosition = BABYLON.Vector3.Zero();
  61629. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61630. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61631. this.poleAngle = 0;
  61632. this.slerpAmount = 1;
  61633. this._bone1Quat = BABYLON.Quaternion.Identity();
  61634. this._bone1Mat = BABYLON.Matrix.Identity();
  61635. this._bone2Ang = Math.PI;
  61636. this._maxAngle = Math.PI;
  61637. this._rightHandedSystem = false;
  61638. this._bendAxis = BABYLON.Vector3.Right();
  61639. this._slerping = false;
  61640. this._adjustRoll = 0;
  61641. this._bone2 = bone;
  61642. this._bone1 = bone.getParent();
  61643. if (!this._bone1) {
  61644. return;
  61645. }
  61646. this.mesh = mesh;
  61647. var bonePos = bone.getPosition();
  61648. if (bone.getAbsoluteTransform().determinant() > 0) {
  61649. this._rightHandedSystem = true;
  61650. this._bendAxis.x = 0;
  61651. this._bendAxis.y = 0;
  61652. this._bendAxis.z = -1;
  61653. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61654. this._adjustRoll = Math.PI * .5;
  61655. this._bendAxis.z = 1;
  61656. }
  61657. }
  61658. if (this._bone1.length) {
  61659. var boneScale1 = this._bone1.getScale();
  61660. var boneScale2 = this._bone2.getScale();
  61661. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61662. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61663. }
  61664. else if (this._bone1.children[0]) {
  61665. mesh.computeWorldMatrix(true);
  61666. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61667. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61668. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61669. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61670. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61671. }
  61672. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61673. this.maxAngle = Math.PI;
  61674. if (options) {
  61675. if (options.targetMesh) {
  61676. this.targetMesh = options.targetMesh;
  61677. this.targetMesh.computeWorldMatrix(true);
  61678. }
  61679. if (options.poleTargetMesh) {
  61680. this.poleTargetMesh = options.poleTargetMesh;
  61681. this.poleTargetMesh.computeWorldMatrix(true);
  61682. }
  61683. else if (options.poleTargetBone) {
  61684. this.poleTargetBone = options.poleTargetBone;
  61685. }
  61686. else if (this._bone1.getParent()) {
  61687. this.poleTargetBone = this._bone1.getParent();
  61688. }
  61689. if (options.poleTargetLocalOffset) {
  61690. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  61691. }
  61692. if (options.poleAngle) {
  61693. this.poleAngle = options.poleAngle;
  61694. }
  61695. if (options.bendAxis) {
  61696. this._bendAxis.copyFrom(options.bendAxis);
  61697. }
  61698. if (options.maxAngle) {
  61699. this.maxAngle = options.maxAngle;
  61700. }
  61701. if (options.slerpAmount) {
  61702. this.slerpAmount = options.slerpAmount;
  61703. }
  61704. }
  61705. }
  61706. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  61707. get: function () {
  61708. return this._maxAngle;
  61709. },
  61710. set: function (value) {
  61711. this._setMaxAngle(value);
  61712. },
  61713. enumerable: true,
  61714. configurable: true
  61715. });
  61716. BoneIKController.prototype._setMaxAngle = function (ang) {
  61717. if (ang < 0) {
  61718. ang = 0;
  61719. }
  61720. if (ang > Math.PI || ang == undefined) {
  61721. ang = Math.PI;
  61722. }
  61723. this._maxAngle = ang;
  61724. var a = this._bone1Length;
  61725. var b = this._bone2Length;
  61726. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  61727. };
  61728. BoneIKController.prototype.update = function () {
  61729. var bone1 = this._bone1;
  61730. if (!bone1) {
  61731. return;
  61732. }
  61733. var target = this.targetPosition;
  61734. var poleTarget = this.poleTargetPosition;
  61735. var mat1 = BoneIKController._tmpMats[0];
  61736. var mat2 = BoneIKController._tmpMats[1];
  61737. if (this.targetMesh) {
  61738. target.copyFrom(this.targetMesh.getAbsolutePosition());
  61739. }
  61740. if (this.poleTargetBone) {
  61741. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61742. }
  61743. else if (this.poleTargetMesh) {
  61744. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61745. }
  61746. var bonePos = BoneIKController._tmpVecs[0];
  61747. var zaxis = BoneIKController._tmpVecs[1];
  61748. var xaxis = BoneIKController._tmpVecs[2];
  61749. var yaxis = BoneIKController._tmpVecs[3];
  61750. var upAxis = BoneIKController._tmpVecs[4];
  61751. var _tmpQuat = BoneIKController._tmpQuat;
  61752. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61753. poleTarget.subtractToRef(bonePos, upAxis);
  61754. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61755. upAxis.y = 1;
  61756. }
  61757. else {
  61758. upAxis.normalize();
  61759. }
  61760. target.subtractToRef(bonePos, yaxis);
  61761. yaxis.normalize();
  61762. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61763. zaxis.normalize();
  61764. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61765. xaxis.normalize();
  61766. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61767. var a = this._bone1Length;
  61768. var b = this._bone2Length;
  61769. var c = BABYLON.Vector3.Distance(bonePos, target);
  61770. if (this._maxReach > 0) {
  61771. c = Math.min(this._maxReach, c);
  61772. }
  61773. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61774. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61775. if (acosa > 1) {
  61776. acosa = 1;
  61777. }
  61778. if (acosb > 1) {
  61779. acosb = 1;
  61780. }
  61781. if (acosa < -1) {
  61782. acosa = -1;
  61783. }
  61784. if (acosb < -1) {
  61785. acosb = -1;
  61786. }
  61787. var angA = Math.acos(acosa);
  61788. var angB = Math.acos(acosb);
  61789. var angC = -angA - angB;
  61790. if (this._rightHandedSystem) {
  61791. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61792. mat2.multiplyToRef(mat1, mat1);
  61793. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61794. mat2.multiplyToRef(mat1, mat1);
  61795. }
  61796. else {
  61797. var _tmpVec = BoneIKController._tmpVecs[5];
  61798. _tmpVec.copyFrom(this._bendAxis);
  61799. _tmpVec.x *= -1;
  61800. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61801. mat2.multiplyToRef(mat1, mat1);
  61802. }
  61803. if (this.poleAngle) {
  61804. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61805. mat1.multiplyToRef(mat2, mat1);
  61806. }
  61807. if (this._bone1) {
  61808. if (this.slerpAmount < 1) {
  61809. if (!this._slerping) {
  61810. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61811. }
  61812. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61813. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61814. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61815. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61816. this._slerping = true;
  61817. }
  61818. else {
  61819. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61820. this._bone1Mat.copyFrom(mat1);
  61821. this._slerping = false;
  61822. }
  61823. }
  61824. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61825. this._bone2Ang = angC;
  61826. };
  61827. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61828. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61829. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61830. return BoneIKController;
  61831. }());
  61832. BABYLON.BoneIKController = BoneIKController;
  61833. })(BABYLON || (BABYLON = {}));
  61834. //# sourceMappingURL=babylon.boneIKController.js.map
  61835. var BABYLON;
  61836. (function (BABYLON) {
  61837. var BoneLookController = /** @class */ (function () {
  61838. /**
  61839. * Create a BoneLookController
  61840. * @param mesh the mesh that the bone belongs to
  61841. * @param bone the bone that will be looking to the target
  61842. * @param target the target Vector3 to look at
  61843. * @param settings optional settings:
  61844. * - maxYaw: the maximum angle the bone will yaw to
  61845. * - minYaw: the minimum angle the bone will yaw to
  61846. * - maxPitch: the maximum angle the bone will pitch to
  61847. * - minPitch: the minimum angle the bone will yaw to
  61848. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61849. * - upAxis: the up axis of the coordinate system
  61850. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61851. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61852. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61853. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61854. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61855. * - adjustRoll: used to make an adjustment to the roll of the bone
  61856. **/
  61857. function BoneLookController(mesh, bone, target, options) {
  61858. /**
  61859. * The up axis of the coordinate system that is used when the bone is rotated.
  61860. */
  61861. this.upAxis = BABYLON.Vector3.Up();
  61862. /**
  61863. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61864. */
  61865. this.upAxisSpace = BABYLON.Space.LOCAL;
  61866. /**
  61867. * Used to make an adjustment to the yaw of the bone.
  61868. */
  61869. this.adjustYaw = 0;
  61870. /**
  61871. * Used to make an adjustment to the pitch of the bone.
  61872. */
  61873. this.adjustPitch = 0;
  61874. /**
  61875. * Used to make an adjustment to the roll of the bone.
  61876. */
  61877. this.adjustRoll = 0;
  61878. /**
  61879. * 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).
  61880. */
  61881. this.slerpAmount = 1;
  61882. this._boneQuat = BABYLON.Quaternion.Identity();
  61883. this._slerping = false;
  61884. this._firstFrameSkipped = false;
  61885. this._fowardAxis = BABYLON.Vector3.Forward();
  61886. this.mesh = mesh;
  61887. this.bone = bone;
  61888. this.target = target;
  61889. if (options) {
  61890. if (options.adjustYaw) {
  61891. this.adjustYaw = options.adjustYaw;
  61892. }
  61893. if (options.adjustPitch) {
  61894. this.adjustPitch = options.adjustPitch;
  61895. }
  61896. if (options.adjustRoll) {
  61897. this.adjustRoll = options.adjustRoll;
  61898. }
  61899. if (options.maxYaw != null) {
  61900. this.maxYaw = options.maxYaw;
  61901. }
  61902. else {
  61903. this.maxYaw = Math.PI;
  61904. }
  61905. if (options.minYaw != null) {
  61906. this.minYaw = options.minYaw;
  61907. }
  61908. else {
  61909. this.minYaw = -Math.PI;
  61910. }
  61911. if (options.maxPitch != null) {
  61912. this.maxPitch = options.maxPitch;
  61913. }
  61914. else {
  61915. this.maxPitch = Math.PI;
  61916. }
  61917. if (options.minPitch != null) {
  61918. this.minPitch = options.minPitch;
  61919. }
  61920. else {
  61921. this.minPitch = -Math.PI;
  61922. }
  61923. if (options.slerpAmount != null) {
  61924. this.slerpAmount = options.slerpAmount;
  61925. }
  61926. if (options.upAxis != null) {
  61927. this.upAxis = options.upAxis;
  61928. }
  61929. if (options.upAxisSpace != null) {
  61930. this.upAxisSpace = options.upAxisSpace;
  61931. }
  61932. if (options.yawAxis != null || options.pitchAxis != null) {
  61933. var newYawAxis = BABYLON.Axis.Y;
  61934. var newPitchAxis = BABYLON.Axis.X;
  61935. if (options.yawAxis != null) {
  61936. newYawAxis = options.yawAxis.clone();
  61937. newYawAxis.normalize();
  61938. }
  61939. if (options.pitchAxis != null) {
  61940. newPitchAxis = options.pitchAxis.clone();
  61941. newPitchAxis.normalize();
  61942. }
  61943. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61944. this._transformYawPitch = BABYLON.Matrix.Identity();
  61945. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61946. this._transformYawPitchInv = this._transformYawPitch.clone();
  61947. this._transformYawPitch.invert();
  61948. }
  61949. }
  61950. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61951. this.upAxisSpace = BABYLON.Space.LOCAL;
  61952. }
  61953. }
  61954. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61955. /**
  61956. * Get/set the minimum yaw angle that the bone can look to.
  61957. */
  61958. get: function () {
  61959. return this._minYaw;
  61960. },
  61961. set: function (value) {
  61962. this._minYaw = value;
  61963. this._minYawSin = Math.sin(value);
  61964. this._minYawCos = Math.cos(value);
  61965. if (this._maxYaw != null) {
  61966. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61967. this._yawRange = this._maxYaw - this._minYaw;
  61968. }
  61969. },
  61970. enumerable: true,
  61971. configurable: true
  61972. });
  61973. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61974. /**
  61975. * Get/set the maximum yaw angle that the bone can look to.
  61976. */
  61977. get: function () {
  61978. return this._maxYaw;
  61979. },
  61980. set: function (value) {
  61981. this._maxYaw = value;
  61982. this._maxYawSin = Math.sin(value);
  61983. this._maxYawCos = Math.cos(value);
  61984. if (this._minYaw != null) {
  61985. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61986. this._yawRange = this._maxYaw - this._minYaw;
  61987. }
  61988. },
  61989. enumerable: true,
  61990. configurable: true
  61991. });
  61992. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61993. /**
  61994. * Get/set the minimum pitch angle that the bone can look to.
  61995. */
  61996. get: function () {
  61997. return this._minPitch;
  61998. },
  61999. set: function (value) {
  62000. this._minPitch = value;
  62001. this._minPitchTan = Math.tan(value);
  62002. },
  62003. enumerable: true,
  62004. configurable: true
  62005. });
  62006. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  62007. /**
  62008. * Get/set the maximum pitch angle that the bone can look to.
  62009. */
  62010. get: function () {
  62011. return this._maxPitch;
  62012. },
  62013. set: function (value) {
  62014. this._maxPitch = value;
  62015. this._maxPitchTan = Math.tan(value);
  62016. },
  62017. enumerable: true,
  62018. configurable: true
  62019. });
  62020. /**
  62021. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  62022. */
  62023. BoneLookController.prototype.update = function () {
  62024. //skip the first frame when slerping so that the mesh rotation is correct
  62025. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  62026. this._firstFrameSkipped = true;
  62027. return;
  62028. }
  62029. var bone = this.bone;
  62030. var bonePos = BoneLookController._tmpVecs[0];
  62031. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  62032. var target = this.target;
  62033. var _tmpMat1 = BoneLookController._tmpMats[0];
  62034. var _tmpMat2 = BoneLookController._tmpMats[1];
  62035. var mesh = this.mesh;
  62036. var parentBone = bone.getParent();
  62037. var upAxis = BoneLookController._tmpVecs[1];
  62038. upAxis.copyFrom(this.upAxis);
  62039. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  62040. if (this._transformYawPitch) {
  62041. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  62042. }
  62043. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  62044. }
  62045. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  62046. mesh.getDirectionToRef(upAxis, upAxis);
  62047. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  62048. upAxis.normalize();
  62049. }
  62050. }
  62051. var checkYaw = false;
  62052. var checkPitch = false;
  62053. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  62054. checkYaw = true;
  62055. }
  62056. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  62057. checkPitch = true;
  62058. }
  62059. if (checkYaw || checkPitch) {
  62060. var spaceMat = BoneLookController._tmpMats[2];
  62061. var spaceMatInv = BoneLookController._tmpMats[3];
  62062. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  62063. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  62064. }
  62065. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  62066. spaceMat.copyFrom(mesh.getWorldMatrix());
  62067. }
  62068. else {
  62069. var forwardAxis = BoneLookController._tmpVecs[2];
  62070. forwardAxis.copyFrom(this._fowardAxis);
  62071. if (this._transformYawPitch) {
  62072. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  62073. }
  62074. if (parentBone) {
  62075. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  62076. }
  62077. else {
  62078. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  62079. }
  62080. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  62081. rightAxis.normalize();
  62082. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  62083. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  62084. }
  62085. spaceMat.invertToRef(spaceMatInv);
  62086. var xzlen = null;
  62087. if (checkPitch) {
  62088. var localTarget = BoneLookController._tmpVecs[3];
  62089. target.subtractToRef(bonePos, localTarget);
  62090. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62091. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62092. var pitch = Math.atan2(localTarget.y, xzlen);
  62093. var newPitch = pitch;
  62094. if (pitch > this._maxPitch) {
  62095. localTarget.y = this._maxPitchTan * xzlen;
  62096. newPitch = this._maxPitch;
  62097. }
  62098. else if (pitch < this._minPitch) {
  62099. localTarget.y = this._minPitchTan * xzlen;
  62100. newPitch = this._minPitch;
  62101. }
  62102. if (pitch != newPitch) {
  62103. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62104. localTarget.addInPlace(bonePos);
  62105. target = localTarget;
  62106. }
  62107. }
  62108. if (checkYaw) {
  62109. var localTarget = BoneLookController._tmpVecs[4];
  62110. target.subtractToRef(bonePos, localTarget);
  62111. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62112. var yaw = Math.atan2(localTarget.x, localTarget.z);
  62113. var newYaw = yaw;
  62114. if (yaw > this._maxYaw || yaw < this._minYaw) {
  62115. if (xzlen == null) {
  62116. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62117. }
  62118. if (this._yawRange > Math.PI) {
  62119. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  62120. localTarget.z = this._maxYawCos * xzlen;
  62121. localTarget.x = this._maxYawSin * xzlen;
  62122. newYaw = this._maxYaw;
  62123. }
  62124. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  62125. localTarget.z = this._minYawCos * xzlen;
  62126. localTarget.x = this._minYawSin * xzlen;
  62127. newYaw = this._minYaw;
  62128. }
  62129. }
  62130. else {
  62131. if (yaw > this._maxYaw) {
  62132. localTarget.z = this._maxYawCos * xzlen;
  62133. localTarget.x = this._maxYawSin * xzlen;
  62134. newYaw = this._maxYaw;
  62135. }
  62136. else if (yaw < this._minYaw) {
  62137. localTarget.z = this._minYawCos * xzlen;
  62138. localTarget.x = this._minYawSin * xzlen;
  62139. newYaw = this._minYaw;
  62140. }
  62141. }
  62142. }
  62143. if (this._slerping && this._yawRange > Math.PI) {
  62144. //are we going to be crossing into the min/max region?
  62145. var boneFwd = BoneLookController._tmpVecs[8];
  62146. boneFwd.copyFrom(BABYLON.Axis.Z);
  62147. if (this._transformYawPitch) {
  62148. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  62149. }
  62150. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  62151. this._boneQuat.toRotationMatrix(boneRotMat);
  62152. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  62153. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  62154. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  62155. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  62156. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  62157. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  62158. if (angBtwTar > angBtwMidYaw) {
  62159. if (xzlen == null) {
  62160. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62161. }
  62162. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  62163. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  62164. if (angBtwMin < angBtwMax) {
  62165. newYaw = boneYaw + Math.PI * .75;
  62166. localTarget.z = Math.cos(newYaw) * xzlen;
  62167. localTarget.x = Math.sin(newYaw) * xzlen;
  62168. }
  62169. else {
  62170. newYaw = boneYaw - Math.PI * .75;
  62171. localTarget.z = Math.cos(newYaw) * xzlen;
  62172. localTarget.x = Math.sin(newYaw) * xzlen;
  62173. }
  62174. }
  62175. }
  62176. if (yaw != newYaw) {
  62177. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62178. localTarget.addInPlace(bonePos);
  62179. target = localTarget;
  62180. }
  62181. }
  62182. }
  62183. var zaxis = BoneLookController._tmpVecs[5];
  62184. var xaxis = BoneLookController._tmpVecs[6];
  62185. var yaxis = BoneLookController._tmpVecs[7];
  62186. var _tmpQuat = BoneLookController._tmpQuat;
  62187. target.subtractToRef(bonePos, zaxis);
  62188. zaxis.normalize();
  62189. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  62190. xaxis.normalize();
  62191. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  62192. yaxis.normalize();
  62193. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  62194. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  62195. return;
  62196. }
  62197. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  62198. return;
  62199. }
  62200. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  62201. return;
  62202. }
  62203. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  62204. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  62205. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  62206. }
  62207. if (this.slerpAmount < 1) {
  62208. if (!this._slerping) {
  62209. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  62210. }
  62211. if (this._transformYawPitch) {
  62212. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62213. }
  62214. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  62215. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  62216. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  62217. this._slerping = true;
  62218. }
  62219. else {
  62220. if (this._transformYawPitch) {
  62221. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62222. }
  62223. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  62224. this._slerping = false;
  62225. }
  62226. };
  62227. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  62228. var angDiff = ang2 - ang1;
  62229. angDiff %= Math.PI * 2;
  62230. if (angDiff > Math.PI) {
  62231. angDiff -= Math.PI * 2;
  62232. }
  62233. else if (angDiff < -Math.PI) {
  62234. angDiff += Math.PI * 2;
  62235. }
  62236. return angDiff;
  62237. };
  62238. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  62239. ang1 %= (2 * Math.PI);
  62240. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62241. ang2 %= (2 * Math.PI);
  62242. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62243. var ab = 0;
  62244. if (ang1 < ang2) {
  62245. ab = ang2 - ang1;
  62246. }
  62247. else {
  62248. ab = ang1 - ang2;
  62249. }
  62250. if (ab > Math.PI) {
  62251. ab = Math.PI * 2 - ab;
  62252. }
  62253. return ab;
  62254. };
  62255. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  62256. ang %= (2 * Math.PI);
  62257. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  62258. ang1 %= (2 * Math.PI);
  62259. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62260. ang2 %= (2 * Math.PI);
  62261. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62262. if (ang1 < ang2) {
  62263. if (ang > ang1 && ang < ang2) {
  62264. return true;
  62265. }
  62266. }
  62267. else {
  62268. if (ang > ang2 && ang < ang1) {
  62269. return true;
  62270. }
  62271. }
  62272. return false;
  62273. };
  62274. 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()];
  62275. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  62276. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62277. return BoneLookController;
  62278. }());
  62279. BABYLON.BoneLookController = BoneLookController;
  62280. })(BABYLON || (BABYLON = {}));
  62281. //# sourceMappingURL=babylon.boneLookController.js.map
  62282. var BABYLON;
  62283. (function (BABYLON) {
  62284. var Skeleton = /** @class */ (function () {
  62285. function Skeleton(name, id, scene) {
  62286. this.name = name;
  62287. this.id = id;
  62288. this.bones = new Array();
  62289. this.needInitialSkinMatrix = false;
  62290. this._isDirty = true;
  62291. this._meshesWithPoseMatrix = new Array();
  62292. this._identity = BABYLON.Matrix.Identity();
  62293. this._ranges = {};
  62294. this._lastAbsoluteTransformsUpdateId = -1;
  62295. // Events
  62296. /**
  62297. * An event triggered before computing the skeleton's matrices
  62298. * @type {BABYLON.Observable}
  62299. */
  62300. this.onBeforeComputeObservable = new BABYLON.Observable();
  62301. this.bones = [];
  62302. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62303. scene.skeletons.push(this);
  62304. //make sure it will recalculate the matrix next time prepare is called.
  62305. this._isDirty = true;
  62306. }
  62307. // Members
  62308. Skeleton.prototype.getTransformMatrices = function (mesh) {
  62309. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  62310. return mesh._bonesTransformMatrices;
  62311. }
  62312. if (!this._transformMatrices) {
  62313. this.prepare();
  62314. }
  62315. return this._transformMatrices;
  62316. };
  62317. Skeleton.prototype.getScene = function () {
  62318. return this._scene;
  62319. };
  62320. // Methods
  62321. /**
  62322. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  62323. */
  62324. Skeleton.prototype.toString = function (fullDetails) {
  62325. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  62326. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  62327. if (fullDetails) {
  62328. ret += ", Ranges: {";
  62329. var first = true;
  62330. for (var name_1 in this._ranges) {
  62331. if (first) {
  62332. ret += ", ";
  62333. first = false;
  62334. }
  62335. ret += name_1;
  62336. }
  62337. ret += "}";
  62338. }
  62339. return ret;
  62340. };
  62341. /**
  62342. * Get bone's index searching by name
  62343. * @param {string} name is bone's name to search for
  62344. * @return {number} Indice of the bone. Returns -1 if not found
  62345. */
  62346. Skeleton.prototype.getBoneIndexByName = function (name) {
  62347. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  62348. if (this.bones[boneIndex].name === name) {
  62349. return boneIndex;
  62350. }
  62351. }
  62352. return -1;
  62353. };
  62354. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  62355. // check name not already in use
  62356. if (!this._ranges[name]) {
  62357. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  62358. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62359. if (this.bones[i].animations[0]) {
  62360. this.bones[i].animations[0].createRange(name, from, to);
  62361. }
  62362. }
  62363. }
  62364. };
  62365. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  62366. if (deleteFrames === void 0) { deleteFrames = true; }
  62367. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62368. if (this.bones[i].animations[0]) {
  62369. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  62370. }
  62371. }
  62372. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  62373. };
  62374. Skeleton.prototype.getAnimationRange = function (name) {
  62375. return this._ranges[name];
  62376. };
  62377. /**
  62378. * Returns as an Array, all AnimationRanges defined on this skeleton
  62379. */
  62380. Skeleton.prototype.getAnimationRanges = function () {
  62381. var animationRanges = [];
  62382. var name;
  62383. var i = 0;
  62384. for (name in this._ranges) {
  62385. animationRanges[i] = this._ranges[name];
  62386. i++;
  62387. }
  62388. return animationRanges;
  62389. };
  62390. /**
  62391. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  62392. */
  62393. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  62394. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62395. if (this._ranges[name] || !source.getAnimationRange(name)) {
  62396. return false;
  62397. }
  62398. var ret = true;
  62399. var frameOffset = this._getHighestAnimationFrame() + 1;
  62400. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  62401. var boneDict = {};
  62402. var sourceBones = source.bones;
  62403. var nBones;
  62404. var i;
  62405. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  62406. boneDict[sourceBones[i].name] = sourceBones[i];
  62407. }
  62408. if (this.bones.length !== sourceBones.length) {
  62409. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  62410. ret = false;
  62411. }
  62412. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  62413. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  62414. var boneName = this.bones[i].name;
  62415. var sourceBone = boneDict[boneName];
  62416. if (sourceBone) {
  62417. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  62418. }
  62419. else {
  62420. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  62421. ret = false;
  62422. }
  62423. }
  62424. // do not call createAnimationRange(), since it also is done to bones, which was already done
  62425. var range = source.getAnimationRange(name);
  62426. if (range) {
  62427. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  62428. }
  62429. return ret;
  62430. };
  62431. Skeleton.prototype.returnToRest = function () {
  62432. for (var index = 0; index < this.bones.length; index++) {
  62433. this.bones[index].returnToRest();
  62434. }
  62435. };
  62436. Skeleton.prototype._getHighestAnimationFrame = function () {
  62437. var ret = 0;
  62438. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62439. if (this.bones[i].animations[0]) {
  62440. var highest = this.bones[i].animations[0].getHighestFrame();
  62441. if (ret < highest) {
  62442. ret = highest;
  62443. }
  62444. }
  62445. }
  62446. return ret;
  62447. };
  62448. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  62449. var range = this.getAnimationRange(name);
  62450. if (!range) {
  62451. return null;
  62452. }
  62453. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  62454. };
  62455. Skeleton.prototype._markAsDirty = function () {
  62456. this._isDirty = true;
  62457. };
  62458. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  62459. this._meshesWithPoseMatrix.push(mesh);
  62460. };
  62461. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  62462. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  62463. if (index > -1) {
  62464. this._meshesWithPoseMatrix.splice(index, 1);
  62465. }
  62466. };
  62467. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  62468. this.onBeforeComputeObservable.notifyObservers(this);
  62469. for (var index = 0; index < this.bones.length; index++) {
  62470. var bone = this.bones[index];
  62471. var parentBone = bone.getParent();
  62472. if (parentBone) {
  62473. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  62474. }
  62475. else {
  62476. if (initialSkinMatrix) {
  62477. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  62478. }
  62479. else {
  62480. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  62481. }
  62482. }
  62483. if (bone._index !== -1) {
  62484. var mappedIndex = bone._index === null ? index : bone._index;
  62485. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  62486. }
  62487. }
  62488. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  62489. };
  62490. Skeleton.prototype.prepare = function () {
  62491. if (!this._isDirty) {
  62492. return;
  62493. }
  62494. if (this.needInitialSkinMatrix) {
  62495. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  62496. var mesh = this._meshesWithPoseMatrix[index];
  62497. var poseMatrix = mesh.getPoseMatrix();
  62498. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  62499. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62500. }
  62501. if (this._synchronizedWithMesh !== mesh) {
  62502. this._synchronizedWithMesh = mesh;
  62503. // Prepare bones
  62504. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  62505. var bone = this.bones[boneIndex];
  62506. if (!bone.getParent()) {
  62507. var matrix = bone.getBaseMatrix();
  62508. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  62509. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  62510. }
  62511. }
  62512. }
  62513. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  62514. }
  62515. }
  62516. else {
  62517. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  62518. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62519. }
  62520. this._computeTransformMatrices(this._transformMatrices, null);
  62521. }
  62522. this._isDirty = false;
  62523. this._scene._activeBones.addCount(this.bones.length, false);
  62524. };
  62525. Skeleton.prototype.getAnimatables = function () {
  62526. if (!this._animatables || this._animatables.length !== this.bones.length) {
  62527. this._animatables = [];
  62528. for (var index = 0; index < this.bones.length; index++) {
  62529. this._animatables.push(this.bones[index]);
  62530. }
  62531. }
  62532. return this._animatables;
  62533. };
  62534. Skeleton.prototype.clone = function (name, id) {
  62535. var result = new Skeleton(name, id || name, this._scene);
  62536. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62537. for (var index = 0; index < this.bones.length; index++) {
  62538. var source = this.bones[index];
  62539. var parentBone = null;
  62540. var parent_1 = source.getParent();
  62541. if (parent_1) {
  62542. var parentIndex = this.bones.indexOf(parent_1);
  62543. parentBone = result.bones[parentIndex];
  62544. }
  62545. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  62546. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  62547. }
  62548. if (this._ranges) {
  62549. result._ranges = {};
  62550. for (var rangeName in this._ranges) {
  62551. var range = this._ranges[rangeName];
  62552. if (range) {
  62553. result._ranges[rangeName] = range.clone();
  62554. }
  62555. }
  62556. }
  62557. this._isDirty = true;
  62558. return result;
  62559. };
  62560. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  62561. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  62562. this.bones.forEach(function (bone) {
  62563. bone.animations.forEach(function (animation) {
  62564. animation.enableBlending = true;
  62565. animation.blendingSpeed = blendingSpeed;
  62566. });
  62567. });
  62568. };
  62569. Skeleton.prototype.dispose = function () {
  62570. this._meshesWithPoseMatrix = [];
  62571. // Animations
  62572. this.getScene().stopAnimation(this);
  62573. // Remove from scene
  62574. this.getScene().removeSkeleton(this);
  62575. };
  62576. Skeleton.prototype.serialize = function () {
  62577. var serializationObject = {};
  62578. serializationObject.name = this.name;
  62579. serializationObject.id = this.id;
  62580. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62581. serializationObject.bones = [];
  62582. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62583. for (var index = 0; index < this.bones.length; index++) {
  62584. var bone = this.bones[index];
  62585. var parent_2 = bone.getParent();
  62586. var serializedBone = {
  62587. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62588. name: bone.name,
  62589. matrix: bone.getBaseMatrix().toArray(),
  62590. rest: bone.getRestPose().toArray()
  62591. };
  62592. serializationObject.bones.push(serializedBone);
  62593. if (bone.length) {
  62594. serializedBone.length = bone.length;
  62595. }
  62596. if (bone.animations && bone.animations.length > 0) {
  62597. serializedBone.animation = bone.animations[0].serialize();
  62598. }
  62599. serializationObject.ranges = [];
  62600. for (var name in this._ranges) {
  62601. var source = this._ranges[name];
  62602. if (!source) {
  62603. continue;
  62604. }
  62605. var range = {};
  62606. range.name = name;
  62607. range.from = source.from;
  62608. range.to = source.to;
  62609. serializationObject.ranges.push(range);
  62610. }
  62611. }
  62612. return serializationObject;
  62613. };
  62614. Skeleton.Parse = function (parsedSkeleton, scene) {
  62615. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62616. if (parsedSkeleton.dimensionsAtRest) {
  62617. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62618. }
  62619. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62620. var index;
  62621. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62622. var parsedBone = parsedSkeleton.bones[index];
  62623. var parentBone = null;
  62624. if (parsedBone.parentBoneIndex > -1) {
  62625. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62626. }
  62627. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62628. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62629. if (parsedBone.length) {
  62630. bone.length = parsedBone.length;
  62631. }
  62632. if (parsedBone.animation) {
  62633. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62634. }
  62635. }
  62636. // placed after bones, so createAnimationRange can cascade down
  62637. if (parsedSkeleton.ranges) {
  62638. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62639. var data = parsedSkeleton.ranges[index];
  62640. skeleton.createAnimationRange(data.name, data.from, data.to);
  62641. }
  62642. }
  62643. return skeleton;
  62644. };
  62645. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62646. if (forceUpdate === void 0) { forceUpdate = false; }
  62647. var renderId = this._scene.getRenderId();
  62648. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62649. this.bones[0].computeAbsoluteTransforms();
  62650. this._lastAbsoluteTransformsUpdateId = renderId;
  62651. }
  62652. };
  62653. Skeleton.prototype.getPoseMatrix = function () {
  62654. var poseMatrix = null;
  62655. if (this._meshesWithPoseMatrix.length > 0) {
  62656. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62657. }
  62658. return poseMatrix;
  62659. };
  62660. Skeleton.prototype.sortBones = function () {
  62661. var bones = new Array();
  62662. var visited = new Array(this.bones.length);
  62663. for (var index = 0; index < this.bones.length; index++) {
  62664. this._sortBones(index, bones, visited);
  62665. }
  62666. this.bones = bones;
  62667. };
  62668. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62669. if (visited[index]) {
  62670. return;
  62671. }
  62672. visited[index] = true;
  62673. var bone = this.bones[index];
  62674. if (bone._index === undefined) {
  62675. bone._index = index;
  62676. }
  62677. var parentBone = bone.getParent();
  62678. if (parentBone) {
  62679. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  62680. }
  62681. bones.push(bone);
  62682. };
  62683. return Skeleton;
  62684. }());
  62685. BABYLON.Skeleton = Skeleton;
  62686. })(BABYLON || (BABYLON = {}));
  62687. //# sourceMappingURL=babylon.skeleton.js.map
  62688. var BABYLON;
  62689. (function (BABYLON) {
  62690. var SphericalPolynomial = /** @class */ (function () {
  62691. function SphericalPolynomial() {
  62692. this.x = BABYLON.Vector3.Zero();
  62693. this.y = BABYLON.Vector3.Zero();
  62694. this.z = BABYLON.Vector3.Zero();
  62695. this.xx = BABYLON.Vector3.Zero();
  62696. this.yy = BABYLON.Vector3.Zero();
  62697. this.zz = BABYLON.Vector3.Zero();
  62698. this.xy = BABYLON.Vector3.Zero();
  62699. this.yz = BABYLON.Vector3.Zero();
  62700. this.zx = BABYLON.Vector3.Zero();
  62701. }
  62702. SphericalPolynomial.prototype.addAmbient = function (color) {
  62703. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62704. this.xx = this.xx.add(colorVector);
  62705. this.yy = this.yy.add(colorVector);
  62706. this.zz = this.zz.add(colorVector);
  62707. };
  62708. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  62709. var result = new SphericalPolynomial();
  62710. result.x = harmonics.L11.scale(1.02333);
  62711. result.y = harmonics.L1_1.scale(1.02333);
  62712. result.z = harmonics.L10.scale(1.02333);
  62713. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  62714. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  62715. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  62716. result.yz = harmonics.L2_1.scale(0.858086);
  62717. result.zx = harmonics.L21.scale(0.858086);
  62718. result.xy = harmonics.L2_2.scale(0.858086);
  62719. result.scale(1.0 / Math.PI);
  62720. return result;
  62721. };
  62722. SphericalPolynomial.prototype.scale = function (scale) {
  62723. this.x = this.x.scale(scale);
  62724. this.y = this.y.scale(scale);
  62725. this.z = this.z.scale(scale);
  62726. this.xx = this.xx.scale(scale);
  62727. this.yy = this.yy.scale(scale);
  62728. this.zz = this.zz.scale(scale);
  62729. this.yz = this.yz.scale(scale);
  62730. this.zx = this.zx.scale(scale);
  62731. this.xy = this.xy.scale(scale);
  62732. };
  62733. return SphericalPolynomial;
  62734. }());
  62735. BABYLON.SphericalPolynomial = SphericalPolynomial;
  62736. var SphericalHarmonics = /** @class */ (function () {
  62737. function SphericalHarmonics() {
  62738. this.L00 = BABYLON.Vector3.Zero();
  62739. this.L1_1 = BABYLON.Vector3.Zero();
  62740. this.L10 = BABYLON.Vector3.Zero();
  62741. this.L11 = BABYLON.Vector3.Zero();
  62742. this.L2_2 = BABYLON.Vector3.Zero();
  62743. this.L2_1 = BABYLON.Vector3.Zero();
  62744. this.L20 = BABYLON.Vector3.Zero();
  62745. this.L21 = BABYLON.Vector3.Zero();
  62746. this.L22 = BABYLON.Vector3.Zero();
  62747. }
  62748. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62749. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62750. var c = colorVector.scale(deltaSolidAngle);
  62751. this.L00 = this.L00.add(c.scale(0.282095));
  62752. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62753. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62754. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62755. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62756. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62757. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62758. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62759. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62760. };
  62761. SphericalHarmonics.prototype.scale = function (scale) {
  62762. this.L00 = this.L00.scale(scale);
  62763. this.L1_1 = this.L1_1.scale(scale);
  62764. this.L10 = this.L10.scale(scale);
  62765. this.L11 = this.L11.scale(scale);
  62766. this.L2_2 = this.L2_2.scale(scale);
  62767. this.L2_1 = this.L2_1.scale(scale);
  62768. this.L20 = this.L20.scale(scale);
  62769. this.L21 = this.L21.scale(scale);
  62770. this.L22 = this.L22.scale(scale);
  62771. };
  62772. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62773. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62774. //
  62775. // E_lm = A_l * L_lm
  62776. //
  62777. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62778. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62779. // the scaling factors are given in equation 9.
  62780. // Constant (Band 0)
  62781. this.L00 = this.L00.scale(3.141593);
  62782. // Linear (Band 1)
  62783. this.L1_1 = this.L1_1.scale(2.094395);
  62784. this.L10 = this.L10.scale(2.094395);
  62785. this.L11 = this.L11.scale(2.094395);
  62786. // Quadratic (Band 2)
  62787. this.L2_2 = this.L2_2.scale(0.785398);
  62788. this.L2_1 = this.L2_1.scale(0.785398);
  62789. this.L20 = this.L20.scale(0.785398);
  62790. this.L21 = this.L21.scale(0.785398);
  62791. this.L22 = this.L22.scale(0.785398);
  62792. };
  62793. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62794. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62795. // L = (1/pi) * E * rho
  62796. //
  62797. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62798. this.scale(1.0 / Math.PI);
  62799. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62800. // (The pixel shader must apply albedo after texture fetches, etc).
  62801. };
  62802. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62803. var result = new SphericalHarmonics();
  62804. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62805. result.L1_1 = polynomial.y.scale(0.977204);
  62806. result.L10 = polynomial.z.scale(0.977204);
  62807. result.L11 = polynomial.x.scale(0.977204);
  62808. result.L2_2 = polynomial.xy.scale(1.16538);
  62809. result.L2_1 = polynomial.yz.scale(1.16538);
  62810. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62811. result.L21 = polynomial.zx.scale(1.16538);
  62812. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62813. result.scale(Math.PI);
  62814. return result;
  62815. };
  62816. return SphericalHarmonics;
  62817. }());
  62818. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62819. })(BABYLON || (BABYLON = {}));
  62820. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62821. var BABYLON;
  62822. (function (BABYLON) {
  62823. var Internals;
  62824. (function (Internals) {
  62825. var FileFaceOrientation = /** @class */ (function () {
  62826. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62827. this.name = name;
  62828. this.worldAxisForNormal = worldAxisForNormal;
  62829. this.worldAxisForFileX = worldAxisForFileX;
  62830. this.worldAxisForFileY = worldAxisForFileY;
  62831. }
  62832. return FileFaceOrientation;
  62833. }());
  62834. ;
  62835. /**
  62836. * Helper class dealing with the extraction of spherical polynomial dataArray
  62837. * from a cube map.
  62838. */
  62839. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62840. function CubeMapToSphericalPolynomialTools() {
  62841. }
  62842. /**
  62843. * Converts a texture to the according Spherical Polynomial data.
  62844. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62845. *
  62846. * @param texture The texture to extract the information from.
  62847. * @return The Spherical Polynomial data.
  62848. */
  62849. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62850. if (!texture.isCube) {
  62851. // Only supports cube Textures currently.
  62852. return null;
  62853. }
  62854. var size = texture.getSize().width;
  62855. var right = texture.readPixels(0);
  62856. var left = texture.readPixels(1);
  62857. var up;
  62858. var down;
  62859. if (texture.isRenderTarget) {
  62860. up = texture.readPixels(3);
  62861. down = texture.readPixels(2);
  62862. }
  62863. else {
  62864. up = texture.readPixels(2);
  62865. down = texture.readPixels(3);
  62866. }
  62867. var front = texture.readPixels(4);
  62868. var back = texture.readPixels(5);
  62869. var gammaSpace = texture.gammaSpace;
  62870. // Always read as RGBA.
  62871. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62872. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62873. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62874. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62875. }
  62876. var cubeInfo = {
  62877. size: size,
  62878. right: right,
  62879. left: left,
  62880. up: up,
  62881. down: down,
  62882. front: front,
  62883. back: back,
  62884. format: format,
  62885. type: type,
  62886. gammaSpace: gammaSpace,
  62887. };
  62888. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62889. };
  62890. /**
  62891. * Converts a cubemap to the according Spherical Polynomial data.
  62892. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62893. *
  62894. * @param cubeInfo The Cube map to extract the information from.
  62895. * @return The Spherical Polynomial data.
  62896. */
  62897. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62898. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62899. var totalSolidAngle = 0.0;
  62900. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62901. var du = 2.0 / cubeInfo.size;
  62902. var dv = du;
  62903. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62904. var minUV = du * 0.5 - 1.0;
  62905. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62906. var fileFace = this.FileFaces[faceIndex];
  62907. var dataArray = cubeInfo[fileFace.name];
  62908. var v = minUV;
  62909. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62910. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62911. // Because SP is still linear, so summation is fine in that basis.
  62912. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62913. for (var y = 0; y < cubeInfo.size; y++) {
  62914. var u = minUV;
  62915. for (var x = 0; x < cubeInfo.size; x++) {
  62916. // World direction (not normalised)
  62917. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62918. worldDirection.normalize();
  62919. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62920. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62921. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62922. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62923. // Handle Integer types.
  62924. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62925. r /= 255;
  62926. g /= 255;
  62927. b /= 255;
  62928. }
  62929. // Handle Gamma space textures.
  62930. if (cubeInfo.gammaSpace) {
  62931. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62932. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62933. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62934. }
  62935. var color = new BABYLON.Color3(r, g, b);
  62936. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62937. totalSolidAngle += deltaSolidAngle;
  62938. u += du;
  62939. }
  62940. v += dv;
  62941. }
  62942. }
  62943. // Solid angle for entire sphere is 4*pi
  62944. var sphereSolidAngle = 4.0 * Math.PI;
  62945. // Adjust the solid angle to allow for how many faces we processed.
  62946. var facesProcessed = 6.0;
  62947. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62948. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62949. // This is needed because the numerical integration over the cube uses a
  62950. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62951. // and also to compensate for accumulative error due to float precision in the summation.
  62952. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62953. sphericalHarmonics.scale(correctionFactor);
  62954. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62955. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62956. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62957. };
  62958. CubeMapToSphericalPolynomialTools.FileFaces = [
  62959. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62960. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62961. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62962. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62963. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62964. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62965. ];
  62966. return CubeMapToSphericalPolynomialTools;
  62967. }());
  62968. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62969. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62970. })(BABYLON || (BABYLON = {}));
  62971. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62972. var BABYLON;
  62973. (function (BABYLON) {
  62974. var Internals;
  62975. (function (Internals) {
  62976. /**
  62977. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62978. */
  62979. var PanoramaToCubeMapTools = /** @class */ (function () {
  62980. function PanoramaToCubeMapTools() {
  62981. }
  62982. /**
  62983. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62984. *
  62985. * @param float32Array The source data.
  62986. * @param inputWidth The width of the input panorama.
  62987. * @param inputhHeight The height of the input panorama.
  62988. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62989. * @return The cubemap data
  62990. */
  62991. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62992. if (!float32Array) {
  62993. throw "ConvertPanoramaToCubemap: input cannot be null";
  62994. }
  62995. if (float32Array.length != inputWidth * inputHeight * 3) {
  62996. throw "ConvertPanoramaToCubemap: input size is wrong";
  62997. }
  62998. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62999. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  63000. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  63001. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  63002. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  63003. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  63004. return {
  63005. front: textureFront,
  63006. back: textureBack,
  63007. left: textureLeft,
  63008. right: textureRight,
  63009. up: textureUp,
  63010. down: textureDown,
  63011. size: size,
  63012. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  63013. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  63014. gammaSpace: false,
  63015. };
  63016. };
  63017. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  63018. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  63019. var textureArray = new Float32Array(buffer);
  63020. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  63021. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  63022. var dy = 1 / texSize;
  63023. var fy = 0;
  63024. for (var y = 0; y < texSize; y++) {
  63025. var xv1 = faceData[0];
  63026. var xv2 = faceData[2];
  63027. for (var x = 0; x < texSize; x++) {
  63028. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  63029. v.normalize();
  63030. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  63031. // 3 channels per pixels
  63032. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  63033. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  63034. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  63035. xv1 = xv1.add(rotDX1);
  63036. xv2 = xv2.add(rotDX2);
  63037. }
  63038. fy += dy;
  63039. }
  63040. return textureArray;
  63041. };
  63042. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  63043. var theta = Math.atan2(vDir.z, vDir.x);
  63044. var phi = Math.acos(vDir.y);
  63045. while (theta < -Math.PI)
  63046. theta += 2 * Math.PI;
  63047. while (theta > Math.PI)
  63048. theta -= 2 * Math.PI;
  63049. var dx = theta / Math.PI;
  63050. var dy = phi / Math.PI;
  63051. // recenter.
  63052. dx = dx * 0.5 + 0.5;
  63053. var px = Math.round(dx * inputWidth);
  63054. if (px < 0)
  63055. px = 0;
  63056. else if (px >= inputWidth)
  63057. px = inputWidth - 1;
  63058. var py = Math.round(dy * inputHeight);
  63059. if (py < 0)
  63060. py = 0;
  63061. else if (py >= inputHeight)
  63062. py = inputHeight - 1;
  63063. var inputY = (inputHeight - py - 1);
  63064. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  63065. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  63066. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  63067. return {
  63068. r: r,
  63069. g: g,
  63070. b: b
  63071. };
  63072. };
  63073. PanoramaToCubeMapTools.FACE_FRONT = [
  63074. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63075. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63076. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63077. new BABYLON.Vector3(1.0, 1.0, -1.0)
  63078. ];
  63079. PanoramaToCubeMapTools.FACE_BACK = [
  63080. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63081. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63082. new BABYLON.Vector3(1.0, 1.0, 1.0),
  63083. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  63084. ];
  63085. PanoramaToCubeMapTools.FACE_RIGHT = [
  63086. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63087. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63088. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63089. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63090. ];
  63091. PanoramaToCubeMapTools.FACE_LEFT = [
  63092. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63093. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63094. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63095. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  63096. ];
  63097. PanoramaToCubeMapTools.FACE_DOWN = [
  63098. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63099. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63100. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63101. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63102. ];
  63103. PanoramaToCubeMapTools.FACE_UP = [
  63104. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63105. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63106. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63107. new BABYLON.Vector3(1.0, -1.0, -1.0)
  63108. ];
  63109. return PanoramaToCubeMapTools;
  63110. }());
  63111. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  63112. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63113. })(BABYLON || (BABYLON = {}));
  63114. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  63115. var BABYLON;
  63116. (function (BABYLON) {
  63117. var Internals;
  63118. (function (Internals) {
  63119. ;
  63120. /**
  63121. * This groups tools to convert HDR texture to native colors array.
  63122. */
  63123. var HDRTools = /** @class */ (function () {
  63124. function HDRTools() {
  63125. }
  63126. HDRTools.Ldexp = function (mantissa, exponent) {
  63127. if (exponent > 1023) {
  63128. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  63129. }
  63130. if (exponent < -1074) {
  63131. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  63132. }
  63133. return mantissa * Math.pow(2, exponent);
  63134. };
  63135. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  63136. if (exponent > 0) {
  63137. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  63138. float32array[index + 0] = red * exponent;
  63139. float32array[index + 1] = green * exponent;
  63140. float32array[index + 2] = blue * exponent;
  63141. }
  63142. else {
  63143. float32array[index + 0] = 0;
  63144. float32array[index + 1] = 0;
  63145. float32array[index + 2] = 0;
  63146. }
  63147. };
  63148. HDRTools.readStringLine = function (uint8array, startIndex) {
  63149. var line = "";
  63150. var character = "";
  63151. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  63152. character = String.fromCharCode(uint8array[i]);
  63153. if (character == "\n") {
  63154. break;
  63155. }
  63156. line += character;
  63157. }
  63158. return line;
  63159. };
  63160. /**
  63161. * Reads header information from an RGBE texture stored in a native array.
  63162. * More information on this format are available here:
  63163. * https://en.wikipedia.org/wiki/RGBE_image_format
  63164. *
  63165. * @param uint8array The binary file stored in native array.
  63166. * @return The header information.
  63167. */
  63168. HDRTools.RGBE_ReadHeader = function (uint8array) {
  63169. var height = 0;
  63170. var width = 0;
  63171. var line = this.readStringLine(uint8array, 0);
  63172. if (line[0] != '#' || line[1] != '?') {
  63173. throw "Bad HDR Format.";
  63174. }
  63175. var endOfHeader = false;
  63176. var findFormat = false;
  63177. var lineIndex = 0;
  63178. do {
  63179. lineIndex += (line.length + 1);
  63180. line = this.readStringLine(uint8array, lineIndex);
  63181. if (line == "FORMAT=32-bit_rle_rgbe") {
  63182. findFormat = true;
  63183. }
  63184. else if (line.length == 0) {
  63185. endOfHeader = true;
  63186. }
  63187. } while (!endOfHeader);
  63188. if (!findFormat) {
  63189. throw "HDR Bad header format, unsupported FORMAT";
  63190. }
  63191. lineIndex += (line.length + 1);
  63192. line = this.readStringLine(uint8array, lineIndex);
  63193. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  63194. var match = sizeRegexp.exec(line);
  63195. // TODO. Support +Y and -X if needed.
  63196. if (!match || match.length < 3) {
  63197. throw "HDR Bad header format, no size";
  63198. }
  63199. width = parseInt(match[2]);
  63200. height = parseInt(match[1]);
  63201. if (width < 8 || width > 0x7fff) {
  63202. throw "HDR Bad header format, unsupported size";
  63203. }
  63204. lineIndex += (line.length + 1);
  63205. return {
  63206. height: height,
  63207. width: width,
  63208. dataPosition: lineIndex
  63209. };
  63210. };
  63211. /**
  63212. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  63213. * This RGBE texture needs to store the information as a panorama.
  63214. *
  63215. * More information on this format are available here:
  63216. * https://en.wikipedia.org/wiki/RGBE_image_format
  63217. *
  63218. * @param buffer The binary file stored in an array buffer.
  63219. * @param size The expected size of the extracted cubemap.
  63220. * @return The Cube Map information.
  63221. */
  63222. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  63223. var uint8array = new Uint8Array(buffer);
  63224. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  63225. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63226. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  63227. return cubeMapData;
  63228. };
  63229. /**
  63230. * Returns the pixels data extracted from an RGBE texture.
  63231. * This pixels will be stored left to right up to down in the R G B order in one array.
  63232. *
  63233. * More information on this format are available here:
  63234. * https://en.wikipedia.org/wiki/RGBE_image_format
  63235. *
  63236. * @param uint8array The binary file stored in an array buffer.
  63237. * @param hdrInfo The header information of the file.
  63238. * @return The pixels data in RGB right to left up to down order.
  63239. */
  63240. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  63241. // Keep for multi format supports.
  63242. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63243. };
  63244. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  63245. var num_scanlines = hdrInfo.height;
  63246. var scanline_width = hdrInfo.width;
  63247. var a, b, c, d, count;
  63248. var dataIndex = hdrInfo.dataPosition;
  63249. var index = 0, endIndex = 0, i = 0;
  63250. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  63251. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  63252. // 3 channels of 4 bytes per pixel in float.
  63253. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  63254. var resultArray = new Float32Array(resultBuffer);
  63255. // read in each successive scanline
  63256. while (num_scanlines > 0) {
  63257. a = uint8array[dataIndex++];
  63258. b = uint8array[dataIndex++];
  63259. c = uint8array[dataIndex++];
  63260. d = uint8array[dataIndex++];
  63261. if (a != 2 || b != 2 || (c & 0x80)) {
  63262. // this file is not run length encoded
  63263. throw "HDR Bad header format, not RLE";
  63264. }
  63265. if (((c << 8) | d) != scanline_width) {
  63266. throw "HDR Bad header format, wrong scan line width";
  63267. }
  63268. index = 0;
  63269. // read each of the four channels for the scanline into the buffer
  63270. for (i = 0; i < 4; i++) {
  63271. endIndex = (i + 1) * scanline_width;
  63272. while (index < endIndex) {
  63273. a = uint8array[dataIndex++];
  63274. b = uint8array[dataIndex++];
  63275. if (a > 128) {
  63276. // a run of the same value
  63277. count = a - 128;
  63278. if ((count == 0) || (count > endIndex - index)) {
  63279. throw "HDR Bad Format, bad scanline data (run)";
  63280. }
  63281. while (count-- > 0) {
  63282. scanLineArray[index++] = b;
  63283. }
  63284. }
  63285. else {
  63286. // a non-run
  63287. count = a;
  63288. if ((count == 0) || (count > endIndex - index)) {
  63289. throw "HDR Bad Format, bad scanline data (non-run)";
  63290. }
  63291. scanLineArray[index++] = b;
  63292. if (--count > 0) {
  63293. for (var j = 0; j < count; j++) {
  63294. scanLineArray[index++] = uint8array[dataIndex++];
  63295. }
  63296. }
  63297. }
  63298. }
  63299. }
  63300. // now convert data from buffer into floats
  63301. for (i = 0; i < scanline_width; i++) {
  63302. a = scanLineArray[i];
  63303. b = scanLineArray[i + scanline_width];
  63304. c = scanLineArray[i + 2 * scanline_width];
  63305. d = scanLineArray[i + 3 * scanline_width];
  63306. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  63307. }
  63308. num_scanlines--;
  63309. }
  63310. return resultArray;
  63311. };
  63312. return HDRTools;
  63313. }());
  63314. Internals.HDRTools = HDRTools;
  63315. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63316. })(BABYLON || (BABYLON = {}));
  63317. //# sourceMappingURL=babylon.hdr.js.map
  63318. var BABYLON;
  63319. (function (BABYLON) {
  63320. /**
  63321. * This represents a texture coming from an HDR input.
  63322. *
  63323. * The only supported format is currently panorama picture stored in RGBE format.
  63324. * Example of such files can be found on HDRLib: http://hdrlib.com/
  63325. */
  63326. var HDRCubeTexture = /** @class */ (function (_super) {
  63327. __extends(HDRCubeTexture, _super);
  63328. /**
  63329. * Instantiates an HDRTexture from the following parameters.
  63330. *
  63331. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  63332. * @param scene The scene the texture will be used in
  63333. * @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.
  63334. * @param noMipmap Forces to not generate the mipmap if true
  63335. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  63336. * @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)
  63337. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  63338. */
  63339. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  63340. if (noMipmap === void 0) { noMipmap = false; }
  63341. if (generateHarmonics === void 0) { generateHarmonics = true; }
  63342. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  63343. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  63344. if (onLoad === void 0) { onLoad = null; }
  63345. if (onError === void 0) { onError = null; }
  63346. var _this = _super.call(this, scene) || this;
  63347. _this._useInGammaSpace = false;
  63348. _this._generateHarmonics = true;
  63349. _this._isBABYLONPreprocessed = false;
  63350. _this._onLoad = null;
  63351. _this._onError = null;
  63352. /**
  63353. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  63354. */
  63355. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63356. /**
  63357. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  63358. * This is usefull at run time to apply the good shader.
  63359. */
  63360. _this.isPMREM = false;
  63361. _this._isBlocking = true;
  63362. if (!url) {
  63363. return _this;
  63364. }
  63365. _this.name = url;
  63366. _this.url = url;
  63367. _this.hasAlpha = false;
  63368. _this.isCube = true;
  63369. _this._textureMatrix = BABYLON.Matrix.Identity();
  63370. _this._onLoad = onLoad;
  63371. _this._onError = onError;
  63372. _this.gammaSpace = false;
  63373. var caps = scene.getEngine().getCaps();
  63374. if (size) {
  63375. _this._isBABYLONPreprocessed = false;
  63376. _this._noMipmap = noMipmap;
  63377. _this._size = size;
  63378. _this._useInGammaSpace = useInGammaSpace;
  63379. _this._usePMREMGenerator = usePMREMGenerator &&
  63380. caps.textureLOD &&
  63381. caps.textureFloat &&
  63382. !_this._useInGammaSpace;
  63383. }
  63384. else {
  63385. _this._isBABYLONPreprocessed = true;
  63386. _this._noMipmap = false;
  63387. _this._useInGammaSpace = false;
  63388. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  63389. !_this._useInGammaSpace;
  63390. }
  63391. _this.isPMREM = _this._usePMREMGenerator;
  63392. _this._texture = _this._getFromCache(url, _this._noMipmap);
  63393. if (!_this._texture) {
  63394. if (!scene.useDelayedTextureLoading) {
  63395. _this.loadTexture();
  63396. }
  63397. else {
  63398. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63399. }
  63400. }
  63401. return _this;
  63402. }
  63403. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  63404. /**
  63405. * Gets wether or not the texture is blocking during loading.
  63406. */
  63407. get: function () {
  63408. return this._isBlocking;
  63409. },
  63410. /**
  63411. * Sets wether or not the texture is blocking during loading.
  63412. */
  63413. set: function (value) {
  63414. this._isBlocking = value;
  63415. },
  63416. enumerable: true,
  63417. configurable: true
  63418. });
  63419. /**
  63420. * Occurs when the file is a preprocessed .babylon.hdr file.
  63421. */
  63422. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  63423. var _this = this;
  63424. var mipLevels = 0;
  63425. var floatArrayView = null;
  63426. var scene = this.getScene();
  63427. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  63428. var mips = new Array();
  63429. if (!floatArrayView) {
  63430. return mips;
  63431. }
  63432. var startIndex = 30;
  63433. for (var level = 0; level < mipLevels; level++) {
  63434. mips.push([]);
  63435. // Fill each pixel of the mip level.
  63436. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  63437. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63438. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  63439. mips[level].push(faceData);
  63440. startIndex += faceSize;
  63441. }
  63442. }
  63443. return mips;
  63444. } : null;
  63445. var callback = function (buffer) {
  63446. var scene = _this.getScene();
  63447. if (!scene) {
  63448. return null;
  63449. }
  63450. // Create Native Array Views
  63451. var intArrayView = new Int32Array(buffer);
  63452. floatArrayView = new Float32Array(buffer);
  63453. // Fill header.
  63454. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  63455. _this._size = intArrayView[1]; // CubeMap max mip face size.
  63456. // Update Texture Information.
  63457. if (!_this._texture) {
  63458. return null;
  63459. }
  63460. _this._texture.updateSize(_this._size, _this._size);
  63461. // Fill polynomial information.
  63462. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  63463. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  63464. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  63465. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  63466. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  63467. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  63468. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  63469. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  63470. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  63471. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  63472. _this.sphericalPolynomial = sphericalPolynomial;
  63473. // Fill pixel data.
  63474. mipLevels = intArrayView[29]; // Number of mip levels.
  63475. var startIndex = 30;
  63476. var data = [];
  63477. var faceSize = Math.pow(_this._size, 2) * 3;
  63478. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63479. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  63480. startIndex += faceSize;
  63481. }
  63482. var results = [];
  63483. var byteArray = null;
  63484. // Push each faces.
  63485. for (var k = 0; k < 6; k++) {
  63486. var dataFace = null;
  63487. // To be deprecated.
  63488. if (version === 1) {
  63489. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  63490. dataFace = data[j];
  63491. }
  63492. // If special cases.
  63493. if (!mipmapGenerator && dataFace) {
  63494. if (!scene.getEngine().getCaps().textureFloat) {
  63495. // 3 channels of 1 bytes per pixel in bytes.
  63496. var byteBuffer = new ArrayBuffer(faceSize);
  63497. byteArray = new Uint8Array(byteBuffer);
  63498. }
  63499. for (var i = 0; i < _this._size * _this._size; i++) {
  63500. // Put in gamma space if requested.
  63501. if (_this._useInGammaSpace) {
  63502. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63503. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63504. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63505. }
  63506. // Convert to int texture for fallback.
  63507. if (byteArray) {
  63508. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63509. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63510. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63511. // May use luminance instead if the result is not accurate.
  63512. var max = Math.max(Math.max(r, g), b);
  63513. if (max > 255) {
  63514. var scale = 255 / max;
  63515. r *= scale;
  63516. g *= scale;
  63517. b *= scale;
  63518. }
  63519. byteArray[(i * 3) + 0] = r;
  63520. byteArray[(i * 3) + 1] = g;
  63521. byteArray[(i * 3) + 2] = b;
  63522. }
  63523. }
  63524. }
  63525. // Fill the array accordingly.
  63526. if (byteArray) {
  63527. results.push(byteArray);
  63528. }
  63529. else {
  63530. results.push(dataFace);
  63531. }
  63532. }
  63533. return results;
  63534. };
  63535. if (scene) {
  63536. 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);
  63537. }
  63538. };
  63539. /**
  63540. * Occurs when the file is raw .hdr file.
  63541. */
  63542. HDRCubeTexture.prototype.loadHDRTexture = function () {
  63543. var _this = this;
  63544. var callback = function (buffer) {
  63545. var scene = _this.getScene();
  63546. if (!scene) {
  63547. return null;
  63548. }
  63549. // Extract the raw linear data.
  63550. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  63551. // Generate harmonics if needed.
  63552. if (_this._generateHarmonics) {
  63553. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  63554. _this.sphericalPolynomial = sphericalPolynomial;
  63555. }
  63556. var results = [];
  63557. var byteArray = null;
  63558. // Push each faces.
  63559. for (var j = 0; j < 6; j++) {
  63560. // Create uintarray fallback.
  63561. if (!scene.getEngine().getCaps().textureFloat) {
  63562. // 3 channels of 1 bytes per pixel in bytes.
  63563. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  63564. byteArray = new Uint8Array(byteBuffer);
  63565. }
  63566. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  63567. // If special cases.
  63568. if (_this._useInGammaSpace || byteArray) {
  63569. for (var i = 0; i < _this._size * _this._size; i++) {
  63570. // Put in gamma space if requested.
  63571. if (_this._useInGammaSpace) {
  63572. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63573. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63574. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63575. }
  63576. // Convert to int texture for fallback.
  63577. if (byteArray) {
  63578. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63579. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63580. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63581. // May use luminance instead if the result is not accurate.
  63582. var max = Math.max(Math.max(r, g), b);
  63583. if (max > 255) {
  63584. var scale = 255 / max;
  63585. r *= scale;
  63586. g *= scale;
  63587. b *= scale;
  63588. }
  63589. byteArray[(i * 3) + 0] = r;
  63590. byteArray[(i * 3) + 1] = g;
  63591. byteArray[(i * 3) + 2] = b;
  63592. }
  63593. }
  63594. }
  63595. if (byteArray) {
  63596. results.push(byteArray);
  63597. }
  63598. else {
  63599. results.push(dataFace);
  63600. }
  63601. }
  63602. return results;
  63603. };
  63604. var mipmapGenerator = null;
  63605. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63606. // if (!this._noMipmap &&
  63607. // this._usePMREMGenerator) {
  63608. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63609. // // Custom setup of the generator matching with the PBR shader values.
  63610. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63611. // this._size,
  63612. // this._size,
  63613. // 0,
  63614. // 3,
  63615. // this.getScene().getEngine().getCaps().textureFloat,
  63616. // 2048,
  63617. // 0.25,
  63618. // false,
  63619. // true);
  63620. // return generator.filterCubeMap();
  63621. // };
  63622. // }
  63623. var scene = this.getScene();
  63624. if (scene) {
  63625. 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);
  63626. }
  63627. };
  63628. /**
  63629. * Starts the loading process of the texture.
  63630. */
  63631. HDRCubeTexture.prototype.loadTexture = function () {
  63632. if (this._isBABYLONPreprocessed) {
  63633. this.loadBabylonTexture();
  63634. }
  63635. else {
  63636. this.loadHDRTexture();
  63637. }
  63638. };
  63639. HDRCubeTexture.prototype.clone = function () {
  63640. var scene = this.getScene();
  63641. if (!scene) {
  63642. return this;
  63643. }
  63644. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63645. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63646. // Base texture
  63647. newTexture.level = this.level;
  63648. newTexture.wrapU = this.wrapU;
  63649. newTexture.wrapV = this.wrapV;
  63650. newTexture.coordinatesIndex = this.coordinatesIndex;
  63651. newTexture.coordinatesMode = this.coordinatesMode;
  63652. return newTexture;
  63653. };
  63654. // Methods
  63655. HDRCubeTexture.prototype.delayLoad = function () {
  63656. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63657. return;
  63658. }
  63659. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63660. this._texture = this._getFromCache(this.url, this._noMipmap);
  63661. if (!this._texture) {
  63662. this.loadTexture();
  63663. }
  63664. };
  63665. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63666. return this._textureMatrix;
  63667. };
  63668. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63669. this._textureMatrix = value;
  63670. };
  63671. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63672. var texture = null;
  63673. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63674. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63675. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63676. texture.name = parsedTexture.name;
  63677. texture.hasAlpha = parsedTexture.hasAlpha;
  63678. texture.level = parsedTexture.level;
  63679. texture.coordinatesMode = parsedTexture.coordinatesMode;
  63680. texture.isBlocking = parsedTexture.isBlocking;
  63681. }
  63682. return texture;
  63683. };
  63684. HDRCubeTexture.prototype.serialize = function () {
  63685. if (!this.name) {
  63686. return null;
  63687. }
  63688. var serializationObject = {};
  63689. serializationObject.name = this.name;
  63690. serializationObject.hasAlpha = this.hasAlpha;
  63691. serializationObject.isCube = true;
  63692. serializationObject.level = this.level;
  63693. serializationObject.size = this._size;
  63694. serializationObject.coordinatesMode = this.coordinatesMode;
  63695. serializationObject.useInGammaSpace = this._useInGammaSpace;
  63696. serializationObject.generateHarmonics = this._generateHarmonics;
  63697. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  63698. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  63699. serializationObject.customType = "BABYLON.HDRCubeTexture";
  63700. serializationObject.noMipmap = this._noMipmap;
  63701. serializationObject.isBlocking = this._isBlocking;
  63702. return serializationObject;
  63703. };
  63704. /**
  63705. * Saves as a file the data contained in the texture in a binary format.
  63706. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63707. * as the spherical used in the lighting.
  63708. * @param url The HDR file url.
  63709. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63710. * @param onError Method called if any error happens during download.
  63711. * @return The packed binary data.
  63712. */
  63713. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  63714. if (onError === void 0) { onError = null; }
  63715. var callback = function (buffer) {
  63716. var data = new Blob([buffer], { type: 'application/octet-stream' });
  63717. // Returns a URL you can use as a href.
  63718. var objUrl = window.URL.createObjectURL(data);
  63719. // Simulates a link to it and click to dowload.
  63720. var a = document.createElement("a");
  63721. document.body.appendChild(a);
  63722. a.style.display = "none";
  63723. a.href = objUrl;
  63724. a.download = "envmap.babylon.hdr";
  63725. a.click();
  63726. };
  63727. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  63728. };
  63729. /**
  63730. * Serializes the data contained in the texture in a binary format.
  63731. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63732. * as the spherical used in the lighting.
  63733. * @param url The HDR file url.
  63734. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63735. * @param onError Method called if any error happens during download.
  63736. * @return The packed binary data.
  63737. */
  63738. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  63739. if (onError === void 0) { onError = null; }
  63740. // Needs the url tho create the texture.
  63741. if (!url) {
  63742. return;
  63743. }
  63744. // Check Power of two size.
  63745. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63746. return;
  63747. }
  63748. // Coming Back in 3.x.
  63749. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63750. };
  63751. HDRCubeTexture._facesMapping = [
  63752. "right",
  63753. "left",
  63754. "up",
  63755. "down",
  63756. "front",
  63757. "back"
  63758. ];
  63759. return HDRCubeTexture;
  63760. }(BABYLON.BaseTexture));
  63761. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63762. })(BABYLON || (BABYLON = {}));
  63763. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63764. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63765. // Huge respect for a such great lib.
  63766. // Earcut license:
  63767. // Copyright (c) 2016, Mapbox
  63768. //
  63769. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63770. // with or without fee is hereby granted, provided that the above copyright notice
  63771. // and this permission notice appear in all copies.
  63772. //
  63773. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63774. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63775. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63776. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63777. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63778. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63779. // THIS SOFTWARE.
  63780. var Earcut;
  63781. (function (Earcut) {
  63782. /**
  63783. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63784. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63785. * @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).
  63786. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63787. */
  63788. function earcut(data, holeIndices, dim) {
  63789. dim = dim || 2;
  63790. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63791. if (!outerNode)
  63792. return triangles;
  63793. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63794. if (hasHoles)
  63795. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63796. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63797. if (data.length > 80 * dim) {
  63798. minX = maxX = data[0];
  63799. minY = maxY = data[1];
  63800. for (var i = dim; i < outerLen; i += dim) {
  63801. x = data[i];
  63802. y = data[i + 1];
  63803. if (x < minX)
  63804. minX = x;
  63805. if (y < minY)
  63806. minY = y;
  63807. if (x > maxX)
  63808. maxX = x;
  63809. if (y > maxY)
  63810. maxY = y;
  63811. }
  63812. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63813. size = Math.max(maxX - minX, maxY - minY);
  63814. }
  63815. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63816. return triangles;
  63817. }
  63818. Earcut.earcut = earcut;
  63819. var Node = /** @class */ (function () {
  63820. function Node(i, x, y) {
  63821. this.i = i;
  63822. this.x = x;
  63823. this.y = y;
  63824. this.prev = null;
  63825. this.next = null;
  63826. this.z = null;
  63827. this.prevZ = null;
  63828. this.nextZ = null;
  63829. this.steiner = false;
  63830. }
  63831. return Node;
  63832. }());
  63833. // create a circular doubly linked list from polygon points in the specified winding order
  63834. function linkedList(data, start, end, dim, clockwise) {
  63835. var i, last = null;
  63836. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63837. for (i = start; i < end; i += dim)
  63838. last = insertNode(i, data[i], data[i + 1], last);
  63839. }
  63840. else {
  63841. for (i = end - dim; i >= start; i -= dim)
  63842. last = insertNode(i, data[i], data[i + 1], last);
  63843. }
  63844. if (last && equals(last, last.next)) {
  63845. removeNode(last);
  63846. last = last.next;
  63847. }
  63848. return last;
  63849. }
  63850. // eliminate colinear or duplicate points
  63851. function filterPoints(start, end) {
  63852. if (!start)
  63853. return start;
  63854. if (!end)
  63855. end = start;
  63856. var p = start, again;
  63857. do {
  63858. again = false;
  63859. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63860. removeNode(p);
  63861. p = end = p.prev;
  63862. if (p === p.next)
  63863. return undefined;
  63864. again = true;
  63865. }
  63866. else {
  63867. p = p.next;
  63868. }
  63869. } while (again || p !== end);
  63870. return end;
  63871. }
  63872. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63873. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63874. if (!ear)
  63875. return;
  63876. // interlink polygon nodes in z-order
  63877. if (!pass && size)
  63878. indexCurve(ear, minX, minY, size);
  63879. var stop = ear, prev, next;
  63880. // iterate through ears, slicing them one by one
  63881. while (ear.prev !== ear.next) {
  63882. prev = ear.prev;
  63883. next = ear.next;
  63884. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63885. // cut off the triangle
  63886. triangles.push(prev.i / dim);
  63887. triangles.push(ear.i / dim);
  63888. triangles.push(next.i / dim);
  63889. removeNode(ear);
  63890. // skipping the next vertice leads to less sliver triangles
  63891. ear = next.next;
  63892. stop = next.next;
  63893. continue;
  63894. }
  63895. ear = next;
  63896. // if we looped through the whole remaining polygon and can't find any more ears
  63897. if (ear === stop) {
  63898. // try filtering points and slicing again
  63899. if (!pass) {
  63900. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63901. // if this didn't work, try curing all small self-intersections locally
  63902. }
  63903. else if (pass === 1) {
  63904. ear = cureLocalIntersections(ear, triangles, dim);
  63905. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63906. // as a last resort, try splitting the remaining polygon into two
  63907. }
  63908. else if (pass === 2) {
  63909. splitEarcut(ear, triangles, dim, minX, minY, size);
  63910. }
  63911. break;
  63912. }
  63913. }
  63914. }
  63915. // check whether a polygon node forms a valid ear with adjacent nodes
  63916. function isEar(ear) {
  63917. var a = ear.prev, b = ear, c = ear.next;
  63918. if (area(a, b, c) >= 0)
  63919. return false; // reflex, can't be an ear
  63920. // now make sure we don't have other points inside the potential ear
  63921. var p = ear.next.next;
  63922. while (p !== ear.prev) {
  63923. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63924. area(p.prev, p, p.next) >= 0)
  63925. return false;
  63926. p = p.next;
  63927. }
  63928. return true;
  63929. }
  63930. function isEarHashed(ear, minX, minY, size) {
  63931. var a = ear.prev, b = ear, c = ear.next;
  63932. if (area(a, b, c) >= 0)
  63933. return false; // reflex, can't be an ear
  63934. // triangle bbox; min & max are calculated like this for speed
  63935. 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);
  63936. // z-order range for the current triangle bbox;
  63937. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63938. // first look for points inside the triangle in increasing z-order
  63939. var p = ear.nextZ;
  63940. while (p && p.z <= maxZ) {
  63941. if (p !== ear.prev &&
  63942. p !== ear.next &&
  63943. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63944. area(p.prev, p, p.next) >= 0)
  63945. return false;
  63946. p = p.nextZ;
  63947. }
  63948. // then look for points in decreasing z-order
  63949. p = ear.prevZ;
  63950. while (p && p.z >= minZ) {
  63951. if (p !== ear.prev &&
  63952. p !== ear.next &&
  63953. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63954. area(p.prev, p, p.next) >= 0)
  63955. return false;
  63956. p = p.prevZ;
  63957. }
  63958. return true;
  63959. }
  63960. // go through all polygon nodes and cure small local self-intersections
  63961. function cureLocalIntersections(start, triangles, dim) {
  63962. var p = start;
  63963. do {
  63964. var a = p.prev, b = p.next.next;
  63965. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63966. triangles.push(a.i / dim);
  63967. triangles.push(p.i / dim);
  63968. triangles.push(b.i / dim);
  63969. // remove two nodes involved
  63970. removeNode(p);
  63971. removeNode(p.next);
  63972. p = start = b;
  63973. }
  63974. p = p.next;
  63975. } while (p !== start);
  63976. return p;
  63977. }
  63978. // try splitting polygon into two and triangulate them independently
  63979. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63980. // look for a valid diagonal that divides the polygon into two
  63981. var a = start;
  63982. do {
  63983. var b = a.next.next;
  63984. while (b !== a.prev) {
  63985. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63986. // split the polygon in two by the diagonal
  63987. var c = splitPolygon(a, b);
  63988. // filter colinear points around the cuts
  63989. a = filterPoints(a, a.next);
  63990. c = filterPoints(c, c.next);
  63991. // run earcut on each half
  63992. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63993. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63994. return;
  63995. }
  63996. b = b.next;
  63997. }
  63998. a = a.next;
  63999. } while (a !== start);
  64000. }
  64001. // link every hole into the outer loop, producing a single-ring polygon without holes
  64002. function eliminateHoles(data, holeIndices, outerNode, dim) {
  64003. var queue = [], i, len, start, end, list;
  64004. for (i = 0, len = holeIndices.length; i < len; i++) {
  64005. start = holeIndices[i] * dim;
  64006. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64007. list = linkedList(data, start, end, dim, false);
  64008. if (list === list.next)
  64009. list.steiner = true;
  64010. queue.push(getLeftmost(list));
  64011. }
  64012. queue.sort(compareX);
  64013. // process holes from left to right
  64014. for (i = 0; i < queue.length; i++) {
  64015. eliminateHole(queue[i], outerNode);
  64016. outerNode = filterPoints(outerNode, outerNode.next);
  64017. }
  64018. return outerNode;
  64019. }
  64020. function compareX(a, b) {
  64021. return a.x - b.x;
  64022. }
  64023. // find a bridge between vertices that connects hole with an outer ring and and link it
  64024. function eliminateHole(hole, outerNode) {
  64025. outerNode = findHoleBridge(hole, outerNode);
  64026. if (outerNode) {
  64027. var b = splitPolygon(outerNode, hole);
  64028. filterPoints(b, b.next);
  64029. }
  64030. }
  64031. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  64032. function findHoleBridge(hole, outerNode) {
  64033. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  64034. // find a segment intersected by a ray from the hole's leftmost point to the left;
  64035. // segment's endpoint with lesser x will be potential connection point
  64036. do {
  64037. if (hy <= p.y && hy >= p.next.y) {
  64038. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  64039. if (x <= hx && x > qx) {
  64040. qx = x;
  64041. if (x === hx) {
  64042. if (hy === p.y)
  64043. return p;
  64044. if (hy === p.next.y)
  64045. return p.next;
  64046. }
  64047. m = p.x < p.next.x ? p : p.next;
  64048. }
  64049. }
  64050. p = p.next;
  64051. } while (p !== outerNode);
  64052. if (!m)
  64053. return null;
  64054. if (hx === qx)
  64055. return m.prev; // hole touches outer segment; pick lower endpoint
  64056. // look for points inside the triangle of hole point, segment intersection and endpoint;
  64057. // if there are no points found, we have a valid connection;
  64058. // otherwise choose the point of the minimum angle with the ray as connection point
  64059. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  64060. p = m.next;
  64061. while (p !== stop) {
  64062. if (hx >= p.x &&
  64063. p.x >= mx &&
  64064. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  64065. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  64066. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  64067. m = p;
  64068. tanMin = tan;
  64069. }
  64070. }
  64071. p = p.next;
  64072. }
  64073. return m;
  64074. }
  64075. // interlink polygon nodes in z-order
  64076. function indexCurve(start, minX, minY, size) {
  64077. var p = start;
  64078. do {
  64079. if (p.z === null)
  64080. p.z = zOrder(p.x, p.y, minX, minY, size);
  64081. p.prevZ = p.prev;
  64082. p.nextZ = p.next;
  64083. p = p.next;
  64084. } while (p !== start);
  64085. p.prevZ.nextZ = null;
  64086. p.prevZ = null;
  64087. sortLinked(p);
  64088. }
  64089. // Simon Tatham's linked list merge sort algorithm
  64090. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  64091. function sortLinked(list) {
  64092. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  64093. do {
  64094. p = list;
  64095. list = null;
  64096. tail = null;
  64097. numMerges = 0;
  64098. while (p) {
  64099. numMerges++;
  64100. q = p;
  64101. pSize = 0;
  64102. for (i = 0; i < inSize; i++) {
  64103. pSize++;
  64104. q = q.nextZ;
  64105. if (!q)
  64106. break;
  64107. }
  64108. qSize = inSize;
  64109. while (pSize > 0 || (qSize > 0 && q)) {
  64110. if (pSize === 0) {
  64111. e = q;
  64112. q = q.nextZ;
  64113. qSize--;
  64114. }
  64115. else if (qSize === 0 || !q) {
  64116. e = p;
  64117. p = p.nextZ;
  64118. pSize--;
  64119. }
  64120. else if (p.z <= q.z) {
  64121. e = p;
  64122. p = p.nextZ;
  64123. pSize--;
  64124. }
  64125. else {
  64126. e = q;
  64127. q = q.nextZ;
  64128. qSize--;
  64129. }
  64130. if (tail)
  64131. tail.nextZ = e;
  64132. else
  64133. list = e;
  64134. e.prevZ = tail;
  64135. tail = e;
  64136. }
  64137. p = q;
  64138. }
  64139. tail.nextZ = null;
  64140. inSize *= 2;
  64141. } while (numMerges > 1);
  64142. return list;
  64143. }
  64144. // z-order of a point given coords and size of the data bounding box
  64145. function zOrder(x, y, minX, minY, size) {
  64146. // coords are transformed into non-negative 15-bit integer range
  64147. x = 32767 * (x - minX) / size;
  64148. y = 32767 * (y - minY) / size;
  64149. x = (x | (x << 8)) & 0x00FF00FF;
  64150. x = (x | (x << 4)) & 0x0F0F0F0F;
  64151. x = (x | (x << 2)) & 0x33333333;
  64152. x = (x | (x << 1)) & 0x55555555;
  64153. y = (y | (y << 8)) & 0x00FF00FF;
  64154. y = (y | (y << 4)) & 0x0F0F0F0F;
  64155. y = (y | (y << 2)) & 0x33333333;
  64156. y = (y | (y << 1)) & 0x55555555;
  64157. return x | (y << 1);
  64158. }
  64159. // find the leftmost node of a polygon ring
  64160. function getLeftmost(start) {
  64161. var p = start, leftmost = start;
  64162. do {
  64163. if (p.x < leftmost.x)
  64164. leftmost = p;
  64165. p = p.next;
  64166. } while (p !== start);
  64167. return leftmost;
  64168. }
  64169. // check if a point lies within a convex triangle
  64170. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  64171. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  64172. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  64173. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  64174. }
  64175. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  64176. function isValidDiagonal(a, b) {
  64177. return a.next.i !== b.i &&
  64178. a.prev.i !== b.i &&
  64179. !intersectsPolygon(a, b) &&
  64180. locallyInside(a, b) &&
  64181. locallyInside(b, a) &&
  64182. middleInside(a, b);
  64183. }
  64184. // signed area of a triangle
  64185. function area(p, q, r) {
  64186. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  64187. }
  64188. // check if two points are equal
  64189. function equals(p1, p2) {
  64190. return p1.x === p2.x && p1.y === p2.y;
  64191. }
  64192. // check if two segments intersect
  64193. function intersects(p1, q1, p2, q2) {
  64194. if ((equals(p1, q1) && equals(p2, q2)) ||
  64195. (equals(p1, q2) && equals(p2, q1)))
  64196. return true;
  64197. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  64198. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  64199. }
  64200. // check if a polygon diagonal intersects any polygon segments
  64201. function intersectsPolygon(a, b) {
  64202. var p = a;
  64203. do {
  64204. if (p.i !== a.i &&
  64205. p.next.i !== a.i &&
  64206. p.i !== b.i &&
  64207. p.next.i !== b.i &&
  64208. intersects(p, p.next, a, b))
  64209. return true;
  64210. p = p.next;
  64211. } while (p !== a);
  64212. return false;
  64213. }
  64214. // check if a polygon diagonal is locally inside the polygon
  64215. function locallyInside(a, b) {
  64216. return area(a.prev, a, a.next) < 0
  64217. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  64218. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  64219. }
  64220. // check if the middle point of a polygon diagonal is inside the polygon
  64221. function middleInside(a, b) {
  64222. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  64223. do {
  64224. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  64225. inside = !inside;
  64226. p = p.next;
  64227. } while (p !== a);
  64228. return inside;
  64229. }
  64230. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  64231. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  64232. function splitPolygon(a, b) {
  64233. 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;
  64234. a.next = b;
  64235. b.prev = a;
  64236. a2.next = an;
  64237. an.prev = a2;
  64238. b2.next = a2;
  64239. a2.prev = b2;
  64240. bp.next = b2;
  64241. b2.prev = bp;
  64242. return b2;
  64243. }
  64244. // create a node and optionally link it with previous one (in a circular doubly linked list)
  64245. function insertNode(i, x, y, last) {
  64246. var p = new Node(i, x, y);
  64247. if (!last) {
  64248. p.prev = p;
  64249. p.next = p;
  64250. }
  64251. else {
  64252. p.next = last.next;
  64253. p.prev = last;
  64254. last.next.prev = p;
  64255. last.next = p;
  64256. }
  64257. return p;
  64258. }
  64259. function removeNode(p) {
  64260. p.next.prev = p.prev;
  64261. p.prev.next = p.next;
  64262. if (p.prevZ)
  64263. p.prevZ.nextZ = p.nextZ;
  64264. if (p.nextZ)
  64265. p.nextZ.prevZ = p.prevZ;
  64266. }
  64267. /**
  64268. * return a percentage difference between the polygon area and its triangulation area;
  64269. * used to verify correctness of triangulation
  64270. */
  64271. function deviation(data, holeIndices, dim, triangles) {
  64272. var hasHoles = holeIndices && holeIndices.length;
  64273. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  64274. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  64275. if (hasHoles) {
  64276. for (var i = 0, len = holeIndices.length; i < len; i++) {
  64277. var start = holeIndices[i] * dim;
  64278. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64279. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  64280. }
  64281. }
  64282. var trianglesArea = 0;
  64283. for (i = 0; i < triangles.length; i += 3) {
  64284. var a = triangles[i] * dim;
  64285. var b = triangles[i + 1] * dim;
  64286. var c = triangles[i + 2] * dim;
  64287. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  64288. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  64289. }
  64290. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  64291. }
  64292. Earcut.deviation = deviation;
  64293. ;
  64294. function signedArea(data, start, end, dim) {
  64295. var sum = 0;
  64296. for (var i = start, j = end - dim; i < end; i += dim) {
  64297. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  64298. j = i;
  64299. }
  64300. return sum;
  64301. }
  64302. /**
  64303. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  64304. */
  64305. function flatten(data) {
  64306. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  64307. for (var i = 0; i < data.length; i++) {
  64308. for (var j = 0; j < data[i].length; j++) {
  64309. for (var d = 0; d < dim; d++)
  64310. result.vertices.push(data[i][j][d]);
  64311. }
  64312. if (i > 0) {
  64313. holeIndex += data[i - 1].length;
  64314. result.holes.push(holeIndex);
  64315. }
  64316. }
  64317. return result;
  64318. }
  64319. Earcut.flatten = flatten;
  64320. ;
  64321. })(Earcut || (Earcut = {}));
  64322. //# sourceMappingURL=babylon.earcut.js.map
  64323. var BABYLON;
  64324. (function (BABYLON) {
  64325. var IndexedVector2 = /** @class */ (function (_super) {
  64326. __extends(IndexedVector2, _super);
  64327. function IndexedVector2(original, index) {
  64328. var _this = _super.call(this, original.x, original.y) || this;
  64329. _this.index = index;
  64330. return _this;
  64331. }
  64332. return IndexedVector2;
  64333. }(BABYLON.Vector2));
  64334. var PolygonPoints = /** @class */ (function () {
  64335. function PolygonPoints() {
  64336. this.elements = new Array();
  64337. }
  64338. PolygonPoints.prototype.add = function (originalPoints) {
  64339. var _this = this;
  64340. var result = new Array();
  64341. originalPoints.forEach(function (point) {
  64342. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  64343. var newPoint = new IndexedVector2(point, _this.elements.length);
  64344. result.push(newPoint);
  64345. _this.elements.push(newPoint);
  64346. }
  64347. });
  64348. return result;
  64349. };
  64350. PolygonPoints.prototype.computeBounds = function () {
  64351. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64352. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64353. this.elements.forEach(function (point) {
  64354. // x
  64355. if (point.x < lmin.x) {
  64356. lmin.x = point.x;
  64357. }
  64358. else if (point.x > lmax.x) {
  64359. lmax.x = point.x;
  64360. }
  64361. // y
  64362. if (point.y < lmin.y) {
  64363. lmin.y = point.y;
  64364. }
  64365. else if (point.y > lmax.y) {
  64366. lmax.y = point.y;
  64367. }
  64368. });
  64369. return {
  64370. min: lmin,
  64371. max: lmax,
  64372. width: lmax.x - lmin.x,
  64373. height: lmax.y - lmin.y
  64374. };
  64375. };
  64376. return PolygonPoints;
  64377. }());
  64378. var Polygon = /** @class */ (function () {
  64379. function Polygon() {
  64380. }
  64381. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  64382. return [
  64383. new BABYLON.Vector2(xmin, ymin),
  64384. new BABYLON.Vector2(xmax, ymin),
  64385. new BABYLON.Vector2(xmax, ymax),
  64386. new BABYLON.Vector2(xmin, ymax)
  64387. ];
  64388. };
  64389. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  64390. if (cx === void 0) { cx = 0; }
  64391. if (cy === void 0) { cy = 0; }
  64392. if (numberOfSides === void 0) { numberOfSides = 32; }
  64393. var result = new Array();
  64394. var angle = 0;
  64395. var increment = (Math.PI * 2) / numberOfSides;
  64396. for (var i = 0; i < numberOfSides; i++) {
  64397. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  64398. angle -= increment;
  64399. }
  64400. return result;
  64401. };
  64402. Polygon.Parse = function (input) {
  64403. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  64404. var i, result = [];
  64405. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  64406. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  64407. }
  64408. return result;
  64409. };
  64410. Polygon.StartingAt = function (x, y) {
  64411. return BABYLON.Path2.StartingAt(x, y);
  64412. };
  64413. return Polygon;
  64414. }());
  64415. BABYLON.Polygon = Polygon;
  64416. var PolygonMeshBuilder = /** @class */ (function () {
  64417. function PolygonMeshBuilder(name, contours, scene) {
  64418. this._points = new PolygonPoints();
  64419. this._outlinepoints = new PolygonPoints();
  64420. this._holes = new Array();
  64421. this._epoints = new Array();
  64422. this._eholes = new Array();
  64423. this._name = name;
  64424. this._scene = scene;
  64425. var points;
  64426. if (contours instanceof BABYLON.Path2) {
  64427. points = contours.getPoints();
  64428. }
  64429. else {
  64430. points = contours;
  64431. }
  64432. this._addToepoint(points);
  64433. this._points.add(points);
  64434. this._outlinepoints.add(points);
  64435. }
  64436. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  64437. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  64438. var p = points_1[_i];
  64439. this._epoints.push(p.x, p.y);
  64440. }
  64441. };
  64442. PolygonMeshBuilder.prototype.addHole = function (hole) {
  64443. this._points.add(hole);
  64444. var holepoints = new PolygonPoints();
  64445. holepoints.add(hole);
  64446. this._holes.push(holepoints);
  64447. this._eholes.push(this._epoints.length / 2);
  64448. this._addToepoint(hole);
  64449. return this;
  64450. };
  64451. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  64452. var _this = this;
  64453. if (updatable === void 0) { updatable = false; }
  64454. if (depth === void 0) { depth = 0; }
  64455. var result = new BABYLON.Mesh(this._name, this._scene);
  64456. var normals = new Array();
  64457. var positions = new Array();
  64458. var uvs = new Array();
  64459. var bounds = this._points.computeBounds();
  64460. this._points.elements.forEach(function (p) {
  64461. normals.push(0, 1.0, 0);
  64462. positions.push(p.x, 0, p.y);
  64463. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  64464. });
  64465. var indices = new Array();
  64466. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  64467. for (var i = 0; i < res.length; i++) {
  64468. indices.push(res[i]);
  64469. }
  64470. if (depth > 0) {
  64471. var positionscount = (positions.length / 3); //get the current pointcount
  64472. this._points.elements.forEach(function (p) {
  64473. normals.push(0, -1.0, 0);
  64474. positions.push(p.x, -depth, p.y);
  64475. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  64476. });
  64477. var totalCount = indices.length;
  64478. for (var i = 0; i < totalCount; i += 3) {
  64479. var i0 = indices[i + 0];
  64480. var i1 = indices[i + 1];
  64481. var i2 = indices[i + 2];
  64482. indices.push(i2 + positionscount);
  64483. indices.push(i1 + positionscount);
  64484. indices.push(i0 + positionscount);
  64485. }
  64486. //Add the sides
  64487. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  64488. this._holes.forEach(function (hole) {
  64489. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  64490. });
  64491. }
  64492. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  64493. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  64494. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  64495. result.setIndices(indices);
  64496. return result;
  64497. };
  64498. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  64499. var StartIndex = positions.length / 3;
  64500. var ulength = 0;
  64501. for (var i = 0; i < points.elements.length; i++) {
  64502. var p = points.elements[i];
  64503. var p1;
  64504. if ((i + 1) > points.elements.length - 1) {
  64505. p1 = points.elements[0];
  64506. }
  64507. else {
  64508. p1 = points.elements[i + 1];
  64509. }
  64510. positions.push(p.x, 0, p.y);
  64511. positions.push(p.x, -depth, p.y);
  64512. positions.push(p1.x, 0, p1.y);
  64513. positions.push(p1.x, -depth, p1.y);
  64514. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  64515. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  64516. var v3 = v2.subtract(v1);
  64517. var v4 = new BABYLON.Vector3(0, 1, 0);
  64518. var vn = BABYLON.Vector3.Cross(v3, v4);
  64519. vn = vn.normalize();
  64520. uvs.push(ulength / bounds.width, 0);
  64521. uvs.push(ulength / bounds.width, 1);
  64522. ulength += v3.length();
  64523. uvs.push((ulength / bounds.width), 0);
  64524. uvs.push((ulength / bounds.width), 1);
  64525. if (!flip) {
  64526. normals.push(-vn.x, -vn.y, -vn.z);
  64527. normals.push(-vn.x, -vn.y, -vn.z);
  64528. normals.push(-vn.x, -vn.y, -vn.z);
  64529. normals.push(-vn.x, -vn.y, -vn.z);
  64530. indices.push(StartIndex);
  64531. indices.push(StartIndex + 1);
  64532. indices.push(StartIndex + 2);
  64533. indices.push(StartIndex + 1);
  64534. indices.push(StartIndex + 3);
  64535. indices.push(StartIndex + 2);
  64536. }
  64537. else {
  64538. normals.push(vn.x, vn.y, vn.z);
  64539. normals.push(vn.x, vn.y, vn.z);
  64540. normals.push(vn.x, vn.y, vn.z);
  64541. normals.push(vn.x, vn.y, vn.z);
  64542. indices.push(StartIndex);
  64543. indices.push(StartIndex + 2);
  64544. indices.push(StartIndex + 1);
  64545. indices.push(StartIndex + 1);
  64546. indices.push(StartIndex + 2);
  64547. indices.push(StartIndex + 3);
  64548. }
  64549. StartIndex += 4;
  64550. }
  64551. ;
  64552. };
  64553. return PolygonMeshBuilder;
  64554. }());
  64555. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  64556. })(BABYLON || (BABYLON = {}));
  64557. //# sourceMappingURL=babylon.polygonMesh.js.map
  64558. var BABYLON;
  64559. (function (BABYLON) {
  64560. // Unique ID when we import meshes from Babylon to CSG
  64561. var currentCSGMeshId = 0;
  64562. // # class Vertex
  64563. // Represents a vertex of a polygon. Use your own vertex class instead of this
  64564. // one to provide additional features like texture coordinates and vertex
  64565. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  64566. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  64567. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  64568. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  64569. // is not used anywhere else.
  64570. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  64571. var Vertex = /** @class */ (function () {
  64572. function Vertex(pos, normal, uv) {
  64573. this.pos = pos;
  64574. this.normal = normal;
  64575. this.uv = uv;
  64576. }
  64577. Vertex.prototype.clone = function () {
  64578. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64579. };
  64580. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64581. // orientation of a polygon is flipped.
  64582. Vertex.prototype.flip = function () {
  64583. this.normal = this.normal.scale(-1);
  64584. };
  64585. // Create a new vertex between this vertex and `other` by linearly
  64586. // interpolating all properties using a parameter of `t`. Subclasses should
  64587. // override this to interpolate additional properties.
  64588. Vertex.prototype.interpolate = function (other, t) {
  64589. 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));
  64590. };
  64591. return Vertex;
  64592. }());
  64593. // # class Plane
  64594. // Represents a plane in 3D space.
  64595. var Plane = /** @class */ (function () {
  64596. function Plane(normal, w) {
  64597. this.normal = normal;
  64598. this.w = w;
  64599. }
  64600. Plane.FromPoints = function (a, b, c) {
  64601. var v0 = c.subtract(a);
  64602. var v1 = b.subtract(a);
  64603. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64604. return null;
  64605. }
  64606. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64607. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64608. };
  64609. Plane.prototype.clone = function () {
  64610. return new Plane(this.normal.clone(), this.w);
  64611. };
  64612. Plane.prototype.flip = function () {
  64613. this.normal.scaleInPlace(-1);
  64614. this.w = -this.w;
  64615. };
  64616. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64617. // fragments in the appropriate lists. Coplanar polygons go into either
  64618. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64619. // respect to this plane. Polygons in front or in back of this plane go into
  64620. // either `front` or `back`.
  64621. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64622. var COPLANAR = 0;
  64623. var FRONT = 1;
  64624. var BACK = 2;
  64625. var SPANNING = 3;
  64626. // Classify each point as well as the entire polygon into one of the above
  64627. // four classes.
  64628. var polygonType = 0;
  64629. var types = [];
  64630. var i;
  64631. var t;
  64632. for (i = 0; i < polygon.vertices.length; i++) {
  64633. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64634. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64635. polygonType |= type;
  64636. types.push(type);
  64637. }
  64638. // Put the polygon in the correct list, splitting it when necessary.
  64639. switch (polygonType) {
  64640. case COPLANAR:
  64641. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64642. break;
  64643. case FRONT:
  64644. front.push(polygon);
  64645. break;
  64646. case BACK:
  64647. back.push(polygon);
  64648. break;
  64649. case SPANNING:
  64650. var f = [], b = [];
  64651. for (i = 0; i < polygon.vertices.length; i++) {
  64652. var j = (i + 1) % polygon.vertices.length;
  64653. var ti = types[i], tj = types[j];
  64654. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64655. if (ti !== BACK)
  64656. f.push(vi);
  64657. if (ti !== FRONT)
  64658. b.push(ti !== BACK ? vi.clone() : vi);
  64659. if ((ti | tj) === SPANNING) {
  64660. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64661. var v = vi.interpolate(vj, t);
  64662. f.push(v);
  64663. b.push(v.clone());
  64664. }
  64665. }
  64666. var poly;
  64667. if (f.length >= 3) {
  64668. poly = new Polygon(f, polygon.shared);
  64669. if (poly.plane)
  64670. front.push(poly);
  64671. }
  64672. if (b.length >= 3) {
  64673. poly = new Polygon(b, polygon.shared);
  64674. if (poly.plane)
  64675. back.push(poly);
  64676. }
  64677. break;
  64678. }
  64679. };
  64680. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  64681. // point is on the plane.
  64682. Plane.EPSILON = 1e-5;
  64683. return Plane;
  64684. }());
  64685. // # class Polygon
  64686. // Represents a convex polygon. The vertices used to initialize a polygon must
  64687. // be coplanar and form a convex loop.
  64688. //
  64689. // Each convex polygon has a `shared` property, which is shared between all
  64690. // polygons that are clones of each other or were split from the same polygon.
  64691. // This can be used to define per-polygon properties (such as surface color).
  64692. var Polygon = /** @class */ (function () {
  64693. function Polygon(vertices, shared) {
  64694. this.vertices = vertices;
  64695. this.shared = shared;
  64696. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  64697. }
  64698. Polygon.prototype.clone = function () {
  64699. var vertices = this.vertices.map(function (v) { return v.clone(); });
  64700. return new Polygon(vertices, this.shared);
  64701. };
  64702. Polygon.prototype.flip = function () {
  64703. this.vertices.reverse().map(function (v) { v.flip(); });
  64704. this.plane.flip();
  64705. };
  64706. return Polygon;
  64707. }());
  64708. // # class Node
  64709. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  64710. // by picking a polygon to split along. That polygon (and all other coplanar
  64711. // polygons) are added directly to that node and the other polygons are added to
  64712. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  64713. // no distinction between internal and leaf nodes.
  64714. var Node = /** @class */ (function () {
  64715. function Node(polygons) {
  64716. this.plane = null;
  64717. this.front = null;
  64718. this.back = null;
  64719. this.polygons = new Array();
  64720. if (polygons) {
  64721. this.build(polygons);
  64722. }
  64723. }
  64724. Node.prototype.clone = function () {
  64725. var node = new Node();
  64726. node.plane = this.plane && this.plane.clone();
  64727. node.front = this.front && this.front.clone();
  64728. node.back = this.back && this.back.clone();
  64729. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  64730. return node;
  64731. };
  64732. // Convert solid space to empty space and empty space to solid space.
  64733. Node.prototype.invert = function () {
  64734. for (var i = 0; i < this.polygons.length; i++) {
  64735. this.polygons[i].flip();
  64736. }
  64737. if (this.plane) {
  64738. this.plane.flip();
  64739. }
  64740. if (this.front) {
  64741. this.front.invert();
  64742. }
  64743. if (this.back) {
  64744. this.back.invert();
  64745. }
  64746. var temp = this.front;
  64747. this.front = this.back;
  64748. this.back = temp;
  64749. };
  64750. // Recursively remove all polygons in `polygons` that are inside this BSP
  64751. // tree.
  64752. Node.prototype.clipPolygons = function (polygons) {
  64753. if (!this.plane)
  64754. return polygons.slice();
  64755. var front = new Array(), back = new Array();
  64756. for (var i = 0; i < polygons.length; i++) {
  64757. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64758. }
  64759. if (this.front) {
  64760. front = this.front.clipPolygons(front);
  64761. }
  64762. if (this.back) {
  64763. back = this.back.clipPolygons(back);
  64764. }
  64765. else {
  64766. back = [];
  64767. }
  64768. return front.concat(back);
  64769. };
  64770. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64771. // `bsp`.
  64772. Node.prototype.clipTo = function (bsp) {
  64773. this.polygons = bsp.clipPolygons(this.polygons);
  64774. if (this.front)
  64775. this.front.clipTo(bsp);
  64776. if (this.back)
  64777. this.back.clipTo(bsp);
  64778. };
  64779. // Return a list of all polygons in this BSP tree.
  64780. Node.prototype.allPolygons = function () {
  64781. var polygons = this.polygons.slice();
  64782. if (this.front)
  64783. polygons = polygons.concat(this.front.allPolygons());
  64784. if (this.back)
  64785. polygons = polygons.concat(this.back.allPolygons());
  64786. return polygons;
  64787. };
  64788. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64789. // new polygons are filtered down to the bottom of the tree and become new
  64790. // nodes there. Each set of polygons is partitioned using the first polygon
  64791. // (no heuristic is used to pick a good split).
  64792. Node.prototype.build = function (polygons) {
  64793. if (!polygons.length)
  64794. return;
  64795. if (!this.plane)
  64796. this.plane = polygons[0].plane.clone();
  64797. var front = new Array(), back = new Array();
  64798. for (var i = 0; i < polygons.length; i++) {
  64799. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64800. }
  64801. if (front.length) {
  64802. if (!this.front)
  64803. this.front = new Node();
  64804. this.front.build(front);
  64805. }
  64806. if (back.length) {
  64807. if (!this.back)
  64808. this.back = new Node();
  64809. this.back.build(back);
  64810. }
  64811. };
  64812. return Node;
  64813. }());
  64814. var CSG = /** @class */ (function () {
  64815. function CSG() {
  64816. this.polygons = new Array();
  64817. }
  64818. // Convert BABYLON.Mesh to BABYLON.CSG
  64819. CSG.FromMesh = function (mesh) {
  64820. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64821. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64822. if (mesh instanceof BABYLON.Mesh) {
  64823. mesh.computeWorldMatrix(true);
  64824. matrix = mesh.getWorldMatrix();
  64825. meshPosition = mesh.position.clone();
  64826. meshRotation = mesh.rotation.clone();
  64827. if (mesh.rotationQuaternion) {
  64828. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64829. }
  64830. meshScaling = mesh.scaling.clone();
  64831. }
  64832. else {
  64833. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64834. }
  64835. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64836. var subMeshes = mesh.subMeshes;
  64837. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64838. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64839. vertices = [];
  64840. for (var j = 0; j < 3; j++) {
  64841. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64842. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64843. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64844. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64845. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64846. vertex = new Vertex(position, normal, uv);
  64847. vertices.push(vertex);
  64848. }
  64849. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64850. // To handle the case of degenerated triangle
  64851. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64852. if (polygon.plane)
  64853. polygons.push(polygon);
  64854. }
  64855. }
  64856. var csg = CSG.FromPolygons(polygons);
  64857. csg.matrix = matrix;
  64858. csg.position = meshPosition;
  64859. csg.rotation = meshRotation;
  64860. csg.scaling = meshScaling;
  64861. csg.rotationQuaternion = meshRotationQuaternion;
  64862. currentCSGMeshId++;
  64863. return csg;
  64864. };
  64865. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64866. CSG.FromPolygons = function (polygons) {
  64867. var csg = new CSG();
  64868. csg.polygons = polygons;
  64869. return csg;
  64870. };
  64871. CSG.prototype.clone = function () {
  64872. var csg = new CSG();
  64873. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64874. csg.copyTransformAttributes(this);
  64875. return csg;
  64876. };
  64877. CSG.prototype.union = function (csg) {
  64878. var a = new Node(this.clone().polygons);
  64879. var b = new Node(csg.clone().polygons);
  64880. a.clipTo(b);
  64881. b.clipTo(a);
  64882. b.invert();
  64883. b.clipTo(a);
  64884. b.invert();
  64885. a.build(b.allPolygons());
  64886. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64887. };
  64888. CSG.prototype.unionInPlace = function (csg) {
  64889. var a = new Node(this.polygons);
  64890. var b = new Node(csg.polygons);
  64891. a.clipTo(b);
  64892. b.clipTo(a);
  64893. b.invert();
  64894. b.clipTo(a);
  64895. b.invert();
  64896. a.build(b.allPolygons());
  64897. this.polygons = a.allPolygons();
  64898. };
  64899. CSG.prototype.subtract = function (csg) {
  64900. var a = new Node(this.clone().polygons);
  64901. var b = new Node(csg.clone().polygons);
  64902. a.invert();
  64903. a.clipTo(b);
  64904. b.clipTo(a);
  64905. b.invert();
  64906. b.clipTo(a);
  64907. b.invert();
  64908. a.build(b.allPolygons());
  64909. a.invert();
  64910. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64911. };
  64912. CSG.prototype.subtractInPlace = function (csg) {
  64913. var a = new Node(this.polygons);
  64914. var b = new Node(csg.polygons);
  64915. a.invert();
  64916. a.clipTo(b);
  64917. b.clipTo(a);
  64918. b.invert();
  64919. b.clipTo(a);
  64920. b.invert();
  64921. a.build(b.allPolygons());
  64922. a.invert();
  64923. this.polygons = a.allPolygons();
  64924. };
  64925. CSG.prototype.intersect = function (csg) {
  64926. var a = new Node(this.clone().polygons);
  64927. var b = new Node(csg.clone().polygons);
  64928. a.invert();
  64929. b.clipTo(a);
  64930. b.invert();
  64931. a.clipTo(b);
  64932. b.clipTo(a);
  64933. a.build(b.allPolygons());
  64934. a.invert();
  64935. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64936. };
  64937. CSG.prototype.intersectInPlace = function (csg) {
  64938. var a = new Node(this.polygons);
  64939. var b = new Node(csg.polygons);
  64940. a.invert();
  64941. b.clipTo(a);
  64942. b.invert();
  64943. a.clipTo(b);
  64944. b.clipTo(a);
  64945. a.build(b.allPolygons());
  64946. a.invert();
  64947. this.polygons = a.allPolygons();
  64948. };
  64949. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64950. // not modified.
  64951. CSG.prototype.inverse = function () {
  64952. var csg = this.clone();
  64953. csg.inverseInPlace();
  64954. return csg;
  64955. };
  64956. CSG.prototype.inverseInPlace = function () {
  64957. this.polygons.map(function (p) { p.flip(); });
  64958. };
  64959. // This is used to keep meshes transformations so they can be restored
  64960. // when we build back a Babylon Mesh
  64961. // NB : All CSG operations are performed in world coordinates
  64962. CSG.prototype.copyTransformAttributes = function (csg) {
  64963. this.matrix = csg.matrix;
  64964. this.position = csg.position;
  64965. this.rotation = csg.rotation;
  64966. this.scaling = csg.scaling;
  64967. this.rotationQuaternion = csg.rotationQuaternion;
  64968. return this;
  64969. };
  64970. // Build Raw mesh from CSG
  64971. // Coordinates here are in world space
  64972. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64973. var matrix = this.matrix.clone();
  64974. matrix.invert();
  64975. 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;
  64976. if (keepSubMeshes) {
  64977. // Sort Polygons, since subMeshes are indices range
  64978. polygons.sort(function (a, b) {
  64979. if (a.shared.meshId === b.shared.meshId) {
  64980. return a.shared.subMeshId - b.shared.subMeshId;
  64981. }
  64982. else {
  64983. return a.shared.meshId - b.shared.meshId;
  64984. }
  64985. });
  64986. }
  64987. for (var i = 0, il = polygons.length; i < il; i++) {
  64988. polygon = polygons[i];
  64989. // Building SubMeshes
  64990. if (!subMesh_dict[polygon.shared.meshId]) {
  64991. subMesh_dict[polygon.shared.meshId] = {};
  64992. }
  64993. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64994. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64995. indexStart: +Infinity,
  64996. indexEnd: -Infinity,
  64997. materialIndex: polygon.shared.materialIndex
  64998. };
  64999. }
  65000. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  65001. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  65002. polygonIndices[0] = 0;
  65003. polygonIndices[1] = j - 1;
  65004. polygonIndices[2] = j;
  65005. for (var k = 0; k < 3; k++) {
  65006. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  65007. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  65008. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  65009. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  65010. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  65011. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  65012. // Check if 2 points can be merged
  65013. if (!(typeof vertex_idx !== 'undefined' &&
  65014. normals[vertex_idx * 3] === localNormal.x &&
  65015. normals[vertex_idx * 3 + 1] === localNormal.y &&
  65016. normals[vertex_idx * 3 + 2] === localNormal.z &&
  65017. uvs[vertex_idx * 2] === uv.x &&
  65018. uvs[vertex_idx * 2 + 1] === uv.y)) {
  65019. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  65020. uvs.push(uv.x, uv.y);
  65021. normals.push(normal.x, normal.y, normal.z);
  65022. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  65023. }
  65024. indices.push(vertex_idx);
  65025. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  65026. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  65027. currentIndex++;
  65028. }
  65029. }
  65030. }
  65031. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  65032. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  65033. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  65034. mesh.setIndices(indices, null);
  65035. if (keepSubMeshes) {
  65036. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  65037. var materialIndexOffset = 0, materialMaxIndex;
  65038. mesh.subMeshes = new Array();
  65039. for (var m in subMesh_dict) {
  65040. materialMaxIndex = -1;
  65041. for (var sm in subMesh_dict[m]) {
  65042. subMesh_obj = subMesh_dict[m][sm];
  65043. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  65044. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  65045. }
  65046. materialIndexOffset += ++materialMaxIndex;
  65047. }
  65048. }
  65049. return mesh;
  65050. };
  65051. // Build Mesh from CSG taking material and transforms into account
  65052. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  65053. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  65054. mesh.material = material;
  65055. mesh.position.copyFrom(this.position);
  65056. mesh.rotation.copyFrom(this.rotation);
  65057. if (this.rotationQuaternion) {
  65058. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  65059. }
  65060. mesh.scaling.copyFrom(this.scaling);
  65061. mesh.computeWorldMatrix(true);
  65062. return mesh;
  65063. };
  65064. return CSG;
  65065. }());
  65066. BABYLON.CSG = CSG;
  65067. })(BABYLON || (BABYLON = {}));
  65068. //# sourceMappingURL=babylon.csg.js.map
  65069. var BABYLON;
  65070. (function (BABYLON) {
  65071. var LensFlare = /** @class */ (function () {
  65072. function LensFlare(size, position, color, imgUrl, system) {
  65073. this.size = size;
  65074. this.position = position;
  65075. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  65076. this.color = color || new BABYLON.Color3(1, 1, 1);
  65077. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  65078. this._system = system;
  65079. system.lensFlares.push(this);
  65080. }
  65081. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  65082. return new LensFlare(size, position, color, imgUrl, system);
  65083. };
  65084. LensFlare.prototype.dispose = function () {
  65085. if (this.texture) {
  65086. this.texture.dispose();
  65087. }
  65088. // Remove from scene
  65089. var index = this._system.lensFlares.indexOf(this);
  65090. this._system.lensFlares.splice(index, 1);
  65091. };
  65092. ;
  65093. return LensFlare;
  65094. }());
  65095. BABYLON.LensFlare = LensFlare;
  65096. })(BABYLON || (BABYLON = {}));
  65097. //# sourceMappingURL=babylon.lensFlare.js.map
  65098. var BABYLON;
  65099. (function (BABYLON) {
  65100. var LensFlareSystem = /** @class */ (function () {
  65101. function LensFlareSystem(name, emitter, scene) {
  65102. this.name = name;
  65103. this.lensFlares = new Array();
  65104. this.borderLimit = 300;
  65105. this.viewportBorder = 0;
  65106. this.layerMask = 0x0FFFFFFF;
  65107. this._vertexBuffers = {};
  65108. this._isEnabled = true;
  65109. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65110. this._emitter = emitter;
  65111. this.id = name;
  65112. scene.lensFlareSystems.push(this);
  65113. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  65114. var engine = scene.getEngine();
  65115. // VBO
  65116. var vertices = [];
  65117. vertices.push(1, 1);
  65118. vertices.push(-1, 1);
  65119. vertices.push(-1, -1);
  65120. vertices.push(1, -1);
  65121. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65122. // Indices
  65123. var indices = [];
  65124. indices.push(0);
  65125. indices.push(1);
  65126. indices.push(2);
  65127. indices.push(0);
  65128. indices.push(2);
  65129. indices.push(3);
  65130. this._indexBuffer = engine.createIndexBuffer(indices);
  65131. // Effects
  65132. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  65133. }
  65134. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  65135. get: function () {
  65136. return this._isEnabled;
  65137. },
  65138. set: function (value) {
  65139. this._isEnabled = value;
  65140. },
  65141. enumerable: true,
  65142. configurable: true
  65143. });
  65144. LensFlareSystem.prototype.getScene = function () {
  65145. return this._scene;
  65146. };
  65147. LensFlareSystem.prototype.getEmitter = function () {
  65148. return this._emitter;
  65149. };
  65150. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  65151. this._emitter = newEmitter;
  65152. };
  65153. LensFlareSystem.prototype.getEmitterPosition = function () {
  65154. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  65155. };
  65156. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  65157. var position = this.getEmitterPosition();
  65158. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  65159. this._positionX = position.x;
  65160. this._positionY = position.y;
  65161. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  65162. if (this.viewportBorder > 0) {
  65163. globalViewport.x -= this.viewportBorder;
  65164. globalViewport.y -= this.viewportBorder;
  65165. globalViewport.width += this.viewportBorder * 2;
  65166. globalViewport.height += this.viewportBorder * 2;
  65167. position.x += this.viewportBorder;
  65168. position.y += this.viewportBorder;
  65169. this._positionX += this.viewportBorder;
  65170. this._positionY += this.viewportBorder;
  65171. }
  65172. if (position.z > 0) {
  65173. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  65174. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  65175. return true;
  65176. }
  65177. return true;
  65178. }
  65179. return false;
  65180. };
  65181. LensFlareSystem.prototype._isVisible = function () {
  65182. if (!this._isEnabled || !this._scene.activeCamera) {
  65183. return false;
  65184. }
  65185. var emitterPosition = this.getEmitterPosition();
  65186. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  65187. var distance = direction.length();
  65188. direction.normalize();
  65189. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  65190. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  65191. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  65192. };
  65193. LensFlareSystem.prototype.render = function () {
  65194. if (!this._effect.isReady() || !this._scene.activeCamera)
  65195. return false;
  65196. var engine = this._scene.getEngine();
  65197. var viewport = this._scene.activeCamera.viewport;
  65198. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  65199. // Position
  65200. if (!this.computeEffectivePosition(globalViewport)) {
  65201. return false;
  65202. }
  65203. // Visibility
  65204. if (!this._isVisible()) {
  65205. return false;
  65206. }
  65207. // Intensity
  65208. var awayX;
  65209. var awayY;
  65210. if (this._positionX < this.borderLimit + globalViewport.x) {
  65211. awayX = this.borderLimit + globalViewport.x - this._positionX;
  65212. }
  65213. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  65214. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  65215. }
  65216. else {
  65217. awayX = 0;
  65218. }
  65219. if (this._positionY < this.borderLimit + globalViewport.y) {
  65220. awayY = this.borderLimit + globalViewport.y - this._positionY;
  65221. }
  65222. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  65223. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  65224. }
  65225. else {
  65226. awayY = 0;
  65227. }
  65228. var away = (awayX > awayY) ? awayX : awayY;
  65229. away -= this.viewportBorder;
  65230. if (away > this.borderLimit) {
  65231. away = this.borderLimit;
  65232. }
  65233. var intensity = 1.0 - (away / this.borderLimit);
  65234. if (intensity < 0) {
  65235. return false;
  65236. }
  65237. if (intensity > 1.0) {
  65238. intensity = 1.0;
  65239. }
  65240. if (this.viewportBorder > 0) {
  65241. globalViewport.x += this.viewportBorder;
  65242. globalViewport.y += this.viewportBorder;
  65243. globalViewport.width -= this.viewportBorder * 2;
  65244. globalViewport.height -= this.viewportBorder * 2;
  65245. this._positionX -= this.viewportBorder;
  65246. this._positionY -= this.viewportBorder;
  65247. }
  65248. // Position
  65249. var centerX = globalViewport.x + globalViewport.width / 2;
  65250. var centerY = globalViewport.y + globalViewport.height / 2;
  65251. var distX = centerX - this._positionX;
  65252. var distY = centerY - this._positionY;
  65253. // Effects
  65254. engine.enableEffect(this._effect);
  65255. engine.setState(false);
  65256. engine.setDepthBuffer(false);
  65257. // VBOs
  65258. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65259. // Flares
  65260. for (var index = 0; index < this.lensFlares.length; index++) {
  65261. var flare = this.lensFlares[index];
  65262. engine.setAlphaMode(flare.alphaMode);
  65263. var x = centerX - (distX * flare.position);
  65264. var y = centerY - (distY * flare.position);
  65265. var cw = flare.size;
  65266. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  65267. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  65268. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  65269. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  65270. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  65271. // Texture
  65272. this._effect.setTexture("textureSampler", flare.texture);
  65273. // Color
  65274. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  65275. // Draw order
  65276. engine.draw(true, 0, 6);
  65277. }
  65278. engine.setDepthBuffer(true);
  65279. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65280. return true;
  65281. };
  65282. LensFlareSystem.prototype.dispose = function () {
  65283. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65284. if (vertexBuffer) {
  65285. vertexBuffer.dispose();
  65286. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65287. }
  65288. if (this._indexBuffer) {
  65289. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65290. this._indexBuffer = null;
  65291. }
  65292. while (this.lensFlares.length) {
  65293. this.lensFlares[0].dispose();
  65294. }
  65295. // Remove from scene
  65296. var index = this._scene.lensFlareSystems.indexOf(this);
  65297. this._scene.lensFlareSystems.splice(index, 1);
  65298. };
  65299. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  65300. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  65301. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  65302. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  65303. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  65304. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  65305. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  65306. var parsedFlare = parsedLensFlareSystem.flares[index];
  65307. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  65308. }
  65309. return lensFlareSystem;
  65310. };
  65311. LensFlareSystem.prototype.serialize = function () {
  65312. var serializationObject = {};
  65313. serializationObject.id = this.id;
  65314. serializationObject.name = this.name;
  65315. serializationObject.emitterId = this.getEmitter().id;
  65316. serializationObject.borderLimit = this.borderLimit;
  65317. serializationObject.flares = [];
  65318. for (var index = 0; index < this.lensFlares.length; index++) {
  65319. var flare = this.lensFlares[index];
  65320. serializationObject.flares.push({
  65321. size: flare.size,
  65322. position: flare.position,
  65323. color: flare.color.asArray(),
  65324. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  65325. });
  65326. }
  65327. return serializationObject;
  65328. };
  65329. return LensFlareSystem;
  65330. }());
  65331. BABYLON.LensFlareSystem = LensFlareSystem;
  65332. })(BABYLON || (BABYLON = {}));
  65333. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  65334. var BABYLON;
  65335. (function (BABYLON) {
  65336. /**
  65337. * This is a holder class for the physics joint created by the physics plugin.
  65338. * It holds a set of functions to control the underlying joint.
  65339. */
  65340. var PhysicsJoint = /** @class */ (function () {
  65341. function PhysicsJoint(type, jointData) {
  65342. this.type = type;
  65343. this.jointData = jointData;
  65344. jointData.nativeParams = jointData.nativeParams || {};
  65345. }
  65346. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  65347. get: function () {
  65348. return this._physicsJoint;
  65349. },
  65350. set: function (newJoint) {
  65351. if (this._physicsJoint) {
  65352. //remove from the wolrd
  65353. }
  65354. this._physicsJoint = newJoint;
  65355. },
  65356. enumerable: true,
  65357. configurable: true
  65358. });
  65359. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  65360. set: function (physicsPlugin) {
  65361. this._physicsPlugin = physicsPlugin;
  65362. },
  65363. enumerable: true,
  65364. configurable: true
  65365. });
  65366. /**
  65367. * Execute a function that is physics-plugin specific.
  65368. * @param {Function} func the function that will be executed.
  65369. * It accepts two parameters: the physics world and the physics joint.
  65370. */
  65371. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  65372. func(this._physicsPlugin.world, this._physicsJoint);
  65373. };
  65374. //TODO check if the native joints are the same
  65375. //Joint Types
  65376. PhysicsJoint.DistanceJoint = 0;
  65377. PhysicsJoint.HingeJoint = 1;
  65378. PhysicsJoint.BallAndSocketJoint = 2;
  65379. PhysicsJoint.WheelJoint = 3;
  65380. PhysicsJoint.SliderJoint = 4;
  65381. //OIMO
  65382. PhysicsJoint.PrismaticJoint = 5;
  65383. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  65384. PhysicsJoint.UniversalJoint = 6;
  65385. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  65386. //Cannon
  65387. //Similar to a Ball-Joint. Different in params
  65388. PhysicsJoint.PointToPointJoint = 8;
  65389. //Cannon only at the moment
  65390. PhysicsJoint.SpringJoint = 9;
  65391. PhysicsJoint.LockJoint = 10;
  65392. return PhysicsJoint;
  65393. }());
  65394. BABYLON.PhysicsJoint = PhysicsJoint;
  65395. /**
  65396. * A class representing a physics distance joint.
  65397. */
  65398. var DistanceJoint = /** @class */ (function (_super) {
  65399. __extends(DistanceJoint, _super);
  65400. function DistanceJoint(jointData) {
  65401. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  65402. }
  65403. /**
  65404. * Update the predefined distance.
  65405. */
  65406. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  65407. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  65408. };
  65409. return DistanceJoint;
  65410. }(PhysicsJoint));
  65411. BABYLON.DistanceJoint = DistanceJoint;
  65412. var MotorEnabledJoint = /** @class */ (function (_super) {
  65413. __extends(MotorEnabledJoint, _super);
  65414. function MotorEnabledJoint(type, jointData) {
  65415. return _super.call(this, type, jointData) || this;
  65416. }
  65417. /**
  65418. * Set the motor values.
  65419. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65420. * @param {number} force the force to apply
  65421. * @param {number} maxForce max force for this motor.
  65422. */
  65423. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  65424. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65425. };
  65426. /**
  65427. * Set the motor's limits.
  65428. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65429. */
  65430. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65431. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65432. };
  65433. return MotorEnabledJoint;
  65434. }(PhysicsJoint));
  65435. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  65436. /**
  65437. * This class represents a single hinge physics joint
  65438. */
  65439. var HingeJoint = /** @class */ (function (_super) {
  65440. __extends(HingeJoint, _super);
  65441. function HingeJoint(jointData) {
  65442. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  65443. }
  65444. /**
  65445. * Set the motor values.
  65446. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65447. * @param {number} force the force to apply
  65448. * @param {number} maxForce max force for this motor.
  65449. */
  65450. HingeJoint.prototype.setMotor = function (force, maxForce) {
  65451. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65452. };
  65453. /**
  65454. * Set the motor's limits.
  65455. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65456. */
  65457. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65458. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65459. };
  65460. return HingeJoint;
  65461. }(MotorEnabledJoint));
  65462. BABYLON.HingeJoint = HingeJoint;
  65463. /**
  65464. * This class represents a dual hinge physics joint (same as wheel joint)
  65465. */
  65466. var Hinge2Joint = /** @class */ (function (_super) {
  65467. __extends(Hinge2Joint, _super);
  65468. function Hinge2Joint(jointData) {
  65469. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  65470. }
  65471. /**
  65472. * Set the motor values.
  65473. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65474. * @param {number} force the force to apply
  65475. * @param {number} maxForce max force for this motor.
  65476. * @param {motorIndex} the motor's index, 0 or 1.
  65477. */
  65478. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  65479. if (motorIndex === void 0) { motorIndex = 0; }
  65480. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  65481. };
  65482. /**
  65483. * Set the motor limits.
  65484. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65485. * @param {number} upperLimit the upper limit
  65486. * @param {number} lowerLimit lower limit
  65487. * @param {motorIndex} the motor's index, 0 or 1.
  65488. */
  65489. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  65490. if (motorIndex === void 0) { motorIndex = 0; }
  65491. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  65492. };
  65493. return Hinge2Joint;
  65494. }(MotorEnabledJoint));
  65495. BABYLON.Hinge2Joint = Hinge2Joint;
  65496. })(BABYLON || (BABYLON = {}));
  65497. //# sourceMappingURL=babylon.physicsJoint.js.map
  65498. var BABYLON;
  65499. (function (BABYLON) {
  65500. var PhysicsImpostor = /** @class */ (function () {
  65501. function PhysicsImpostor(object, type, _options, _scene) {
  65502. if (_options === void 0) { _options = { mass: 0 }; }
  65503. var _this = this;
  65504. this.object = object;
  65505. this.type = type;
  65506. this._options = _options;
  65507. this._scene = _scene;
  65508. this._bodyUpdateRequired = false;
  65509. this._onBeforePhysicsStepCallbacks = new Array();
  65510. this._onAfterPhysicsStepCallbacks = new Array();
  65511. this._onPhysicsCollideCallbacks = [];
  65512. this._deltaPosition = BABYLON.Vector3.Zero();
  65513. this._isDisposed = false;
  65514. //temp variables for parent rotation calculations
  65515. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  65516. this._tmpQuat = new BABYLON.Quaternion();
  65517. this._tmpQuat2 = new BABYLON.Quaternion();
  65518. /**
  65519. * this function is executed by the physics engine.
  65520. */
  65521. this.beforeStep = function () {
  65522. if (!_this._physicsEngine) {
  65523. return;
  65524. }
  65525. _this.object.translate(_this._deltaPosition, -1);
  65526. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  65527. _this.object.computeWorldMatrix(false);
  65528. if (_this.object.parent && _this.object.rotationQuaternion) {
  65529. _this.getParentsRotation();
  65530. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  65531. }
  65532. else {
  65533. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  65534. }
  65535. if (!_this._options.disableBidirectionalTransformation) {
  65536. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  65537. }
  65538. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  65539. func(_this);
  65540. });
  65541. };
  65542. /**
  65543. * this function is executed by the physics engine.
  65544. */
  65545. this.afterStep = function () {
  65546. if (!_this._physicsEngine) {
  65547. return;
  65548. }
  65549. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  65550. func(_this);
  65551. });
  65552. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  65553. // object has now its world rotation. needs to be converted to local.
  65554. if (_this.object.parent && _this.object.rotationQuaternion) {
  65555. _this.getParentsRotation();
  65556. _this._tmpQuat.conjugateInPlace();
  65557. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  65558. }
  65559. // take the position set and make it the absolute position of this object.
  65560. _this.object.setAbsolutePosition(_this.object.position);
  65561. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  65562. _this.object.translate(_this._deltaPosition, 1);
  65563. };
  65564. /**
  65565. * Legacy collision detection event support
  65566. */
  65567. this.onCollideEvent = null;
  65568. //event and body object due to cannon's event-based architecture.
  65569. this.onCollide = function (e) {
  65570. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  65571. return;
  65572. }
  65573. if (!_this._physicsEngine) {
  65574. return;
  65575. }
  65576. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65577. if (otherImpostor) {
  65578. // Legacy collision detection event support
  65579. if (_this.onCollideEvent) {
  65580. _this.onCollideEvent(_this, otherImpostor);
  65581. }
  65582. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65583. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65584. }).forEach(function (obj) {
  65585. obj.callback(_this, otherImpostor);
  65586. });
  65587. }
  65588. };
  65589. //sanity check!
  65590. if (!this.object) {
  65591. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65592. return;
  65593. }
  65594. //legacy support for old syntax.
  65595. if (!this._scene && object.getScene) {
  65596. this._scene = object.getScene();
  65597. }
  65598. if (!this._scene) {
  65599. return;
  65600. }
  65601. this._physicsEngine = this._scene.getPhysicsEngine();
  65602. if (!this._physicsEngine) {
  65603. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65604. }
  65605. else {
  65606. //set the object's quaternion, if not set
  65607. if (!this.object.rotationQuaternion) {
  65608. if (this.object.rotation) {
  65609. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65610. }
  65611. else {
  65612. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65613. }
  65614. }
  65615. //default options params
  65616. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65617. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65618. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65619. this._joints = [];
  65620. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65621. if (!this.object.parent || this._options.ignoreParent) {
  65622. this._init();
  65623. }
  65624. else if (this.object.parent.physicsImpostor) {
  65625. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65626. }
  65627. }
  65628. }
  65629. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65630. get: function () {
  65631. return this._isDisposed;
  65632. },
  65633. enumerable: true,
  65634. configurable: true
  65635. });
  65636. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65637. get: function () {
  65638. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65639. },
  65640. set: function (value) {
  65641. this.setMass(value);
  65642. },
  65643. enumerable: true,
  65644. configurable: true
  65645. });
  65646. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65647. get: function () {
  65648. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65649. },
  65650. set: function (value) {
  65651. if (!this._physicsEngine) {
  65652. return;
  65653. }
  65654. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65655. },
  65656. enumerable: true,
  65657. configurable: true
  65658. });
  65659. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65660. get: function () {
  65661. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65662. },
  65663. set: function (value) {
  65664. if (!this._physicsEngine) {
  65665. return;
  65666. }
  65667. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65668. },
  65669. enumerable: true,
  65670. configurable: true
  65671. });
  65672. /**
  65673. * This function will completly initialize this impostor.
  65674. * It will create a new body - but only if this mesh has no parent.
  65675. * If it has, this impostor will not be used other than to define the impostor
  65676. * of the child mesh.
  65677. */
  65678. PhysicsImpostor.prototype._init = function () {
  65679. if (!this._physicsEngine) {
  65680. return;
  65681. }
  65682. this._physicsEngine.removeImpostor(this);
  65683. this.physicsBody = null;
  65684. this._parent = this._parent || this._getPhysicsParent();
  65685. if (!this.parent || this._options.ignoreParent) {
  65686. this._physicsEngine.addImpostor(this);
  65687. }
  65688. };
  65689. PhysicsImpostor.prototype._getPhysicsParent = function () {
  65690. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  65691. var parentMesh = this.object.parent;
  65692. return parentMesh.physicsImpostor;
  65693. }
  65694. return null;
  65695. };
  65696. /**
  65697. * Should a new body be generated.
  65698. */
  65699. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  65700. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  65701. };
  65702. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  65703. this.forceUpdate();
  65704. };
  65705. /**
  65706. * Force a regeneration of this or the parent's impostor's body.
  65707. * Use under cautious - This will remove all joints already implemented.
  65708. */
  65709. PhysicsImpostor.prototype.forceUpdate = function () {
  65710. this._init();
  65711. if (this.parent && !this._options.ignoreParent) {
  65712. this.parent.forceUpdate();
  65713. }
  65714. };
  65715. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  65716. /*public get mesh(): AbstractMesh {
  65717. return this._mesh;
  65718. }*/
  65719. /**
  65720. * Gets the body that holds this impostor. Either its own, or its parent.
  65721. */
  65722. get: function () {
  65723. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  65724. },
  65725. /**
  65726. * Set the physics body. Used mainly by the physics engine/plugin
  65727. */
  65728. set: function (physicsBody) {
  65729. if (this._physicsBody && this._physicsEngine) {
  65730. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  65731. }
  65732. this._physicsBody = physicsBody;
  65733. this.resetUpdateFlags();
  65734. },
  65735. enumerable: true,
  65736. configurable: true
  65737. });
  65738. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65739. get: function () {
  65740. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65741. },
  65742. set: function (value) {
  65743. this._parent = value;
  65744. },
  65745. enumerable: true,
  65746. configurable: true
  65747. });
  65748. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65749. this._bodyUpdateRequired = false;
  65750. };
  65751. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65752. if (this.object.getBoundingInfo) {
  65753. var q = this.object.rotationQuaternion;
  65754. //reset rotation
  65755. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65756. //calculate the world matrix with no rotation
  65757. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65758. var boundingInfo = this.object.getBoundingInfo();
  65759. var size = void 0;
  65760. if (boundingInfo) {
  65761. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65762. }
  65763. else {
  65764. size = BABYLON.Vector3.Zero();
  65765. }
  65766. //bring back the rotation
  65767. this.object.rotationQuaternion = q;
  65768. //calculate the world matrix with the new rotation
  65769. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65770. return size;
  65771. }
  65772. else {
  65773. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65774. }
  65775. };
  65776. PhysicsImpostor.prototype.getObjectCenter = function () {
  65777. if (this.object.getBoundingInfo) {
  65778. var boundingInfo = this.object.getBoundingInfo();
  65779. if (!boundingInfo) {
  65780. return this.object.position;
  65781. }
  65782. return boundingInfo.boundingBox.centerWorld;
  65783. }
  65784. else {
  65785. return this.object.position;
  65786. }
  65787. };
  65788. /**
  65789. * Get a specific parametes from the options parameter.
  65790. */
  65791. PhysicsImpostor.prototype.getParam = function (paramName) {
  65792. return this._options[paramName];
  65793. };
  65794. /**
  65795. * Sets a specific parameter in the options given to the physics plugin
  65796. */
  65797. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65798. this._options[paramName] = value;
  65799. this._bodyUpdateRequired = true;
  65800. };
  65801. /**
  65802. * Specifically change the body's mass option. Won't recreate the physics body object
  65803. */
  65804. PhysicsImpostor.prototype.setMass = function (mass) {
  65805. if (this.getParam("mass") !== mass) {
  65806. this.setParam("mass", mass);
  65807. }
  65808. if (this._physicsEngine) {
  65809. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65810. }
  65811. };
  65812. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65813. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65814. };
  65815. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65816. if (this._physicsEngine) {
  65817. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65818. }
  65819. };
  65820. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65821. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65822. };
  65823. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65824. if (this._physicsEngine) {
  65825. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65826. }
  65827. };
  65828. /**
  65829. * Execute a function with the physics plugin native code.
  65830. * Provide a function the will have two variables - the world object and the physics body object.
  65831. */
  65832. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65833. if (this._physicsEngine) {
  65834. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65835. }
  65836. };
  65837. /**
  65838. * Register a function that will be executed before the physics world is stepping forward.
  65839. */
  65840. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65841. this._onBeforePhysicsStepCallbacks.push(func);
  65842. };
  65843. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65844. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65845. if (index > -1) {
  65846. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65847. }
  65848. else {
  65849. BABYLON.Tools.Warn("Function to remove was not found");
  65850. }
  65851. };
  65852. /**
  65853. * Register a function that will be executed after the physics step
  65854. */
  65855. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65856. this._onAfterPhysicsStepCallbacks.push(func);
  65857. };
  65858. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65859. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65860. if (index > -1) {
  65861. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65862. }
  65863. else {
  65864. BABYLON.Tools.Warn("Function to remove was not found");
  65865. }
  65866. };
  65867. /**
  65868. * register a function that will be executed when this impostor collides against a different body.
  65869. */
  65870. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65871. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65872. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65873. };
  65874. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65875. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65876. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65877. if (index > -1) {
  65878. this._onPhysicsCollideCallbacks.splice(index, 1);
  65879. }
  65880. else {
  65881. BABYLON.Tools.Warn("Function to remove was not found");
  65882. }
  65883. };
  65884. PhysicsImpostor.prototype.getParentsRotation = function () {
  65885. var parent = this.object.parent;
  65886. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  65887. while (parent) {
  65888. if (parent.rotationQuaternion) {
  65889. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  65890. }
  65891. else {
  65892. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  65893. }
  65894. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  65895. parent = parent.parent;
  65896. }
  65897. return this._tmpQuat;
  65898. };
  65899. /**
  65900. * Apply a force
  65901. */
  65902. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65903. if (this._physicsEngine) {
  65904. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65905. }
  65906. return this;
  65907. };
  65908. /**
  65909. * Apply an impulse
  65910. */
  65911. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65912. if (this._physicsEngine) {
  65913. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65914. }
  65915. return this;
  65916. };
  65917. /**
  65918. * A help function to create a joint.
  65919. */
  65920. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65921. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65922. this.addJoint(otherImpostor, joint);
  65923. return this;
  65924. };
  65925. /**
  65926. * Add a joint to this impostor with a different impostor.
  65927. */
  65928. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65929. this._joints.push({
  65930. otherImpostor: otherImpostor,
  65931. joint: joint
  65932. });
  65933. if (this._physicsEngine) {
  65934. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65935. }
  65936. return this;
  65937. };
  65938. /**
  65939. * Will keep this body still, in a sleep mode.
  65940. */
  65941. PhysicsImpostor.prototype.sleep = function () {
  65942. if (this._physicsEngine) {
  65943. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65944. }
  65945. return this;
  65946. };
  65947. /**
  65948. * Wake the body up.
  65949. */
  65950. PhysicsImpostor.prototype.wakeUp = function () {
  65951. if (this._physicsEngine) {
  65952. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65953. }
  65954. return this;
  65955. };
  65956. PhysicsImpostor.prototype.clone = function (newObject) {
  65957. if (!newObject)
  65958. return null;
  65959. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65960. };
  65961. PhysicsImpostor.prototype.dispose = function () {
  65962. var _this = this;
  65963. //no dispose if no physics engine is available.
  65964. if (!this._physicsEngine) {
  65965. return;
  65966. }
  65967. this._joints.forEach(function (j) {
  65968. if (_this._physicsEngine) {
  65969. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65970. }
  65971. });
  65972. //dispose the physics body
  65973. this._physicsEngine.removeImpostor(this);
  65974. if (this.parent) {
  65975. this.parent.forceUpdate();
  65976. }
  65977. else {
  65978. /*this._object.getChildMeshes().forEach(function(mesh) {
  65979. if (mesh.physicsImpostor) {
  65980. if (disposeChildren) {
  65981. mesh.physicsImpostor.dispose();
  65982. mesh.physicsImpostor = null;
  65983. }
  65984. }
  65985. })*/
  65986. }
  65987. this._isDisposed = true;
  65988. };
  65989. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65990. this._deltaPosition.copyFrom(position);
  65991. };
  65992. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65993. if (!this._deltaRotation) {
  65994. this._deltaRotation = new BABYLON.Quaternion();
  65995. }
  65996. this._deltaRotation.copyFrom(rotation);
  65997. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65998. };
  65999. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  66000. if (this._physicsEngine) {
  66001. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  66002. }
  66003. return this;
  66004. };
  66005. PhysicsImpostor.prototype.getRadius = function () {
  66006. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  66007. };
  66008. /**
  66009. * Sync a bone with this impostor
  66010. * @param bone The bone to sync to the impostor.
  66011. * @param boneMesh The mesh that the bone is influencing.
  66012. * @param jointPivot The pivot of the joint / bone in local space.
  66013. * @param distToJoint Optional distance from the impostor to the joint.
  66014. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66015. */
  66016. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  66017. var tempVec = PhysicsImpostor._tmpVecs[0];
  66018. var mesh = this.object;
  66019. if (mesh.rotationQuaternion) {
  66020. if (adjustRotation) {
  66021. var tempQuat = PhysicsImpostor._tmpQuat;
  66022. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  66023. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  66024. }
  66025. else {
  66026. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  66027. }
  66028. }
  66029. tempVec.x = 0;
  66030. tempVec.y = 0;
  66031. tempVec.z = 0;
  66032. if (jointPivot) {
  66033. tempVec.x = jointPivot.x;
  66034. tempVec.y = jointPivot.y;
  66035. tempVec.z = jointPivot.z;
  66036. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  66037. if (distToJoint === undefined || distToJoint === null) {
  66038. distToJoint = jointPivot.length();
  66039. }
  66040. tempVec.x *= distToJoint;
  66041. tempVec.y *= distToJoint;
  66042. tempVec.z *= distToJoint;
  66043. }
  66044. if (bone.getParent()) {
  66045. tempVec.addInPlace(mesh.getAbsolutePosition());
  66046. bone.setAbsolutePosition(tempVec, boneMesh);
  66047. }
  66048. else {
  66049. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  66050. boneMesh.position.x -= tempVec.x;
  66051. boneMesh.position.y -= tempVec.y;
  66052. boneMesh.position.z -= tempVec.z;
  66053. }
  66054. };
  66055. /**
  66056. * Sync impostor to a bone
  66057. * @param bone The bone that the impostor will be synced to.
  66058. * @param boneMesh The mesh that the bone is influencing.
  66059. * @param jointPivot The pivot of the joint / bone in local space.
  66060. * @param distToJoint Optional distance from the impostor to the joint.
  66061. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66062. * @param boneAxis Optional vector3 axis the bone is aligned with
  66063. */
  66064. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  66065. var mesh = this.object;
  66066. if (mesh.rotationQuaternion) {
  66067. if (adjustRotation) {
  66068. var tempQuat = PhysicsImpostor._tmpQuat;
  66069. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  66070. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  66071. }
  66072. else {
  66073. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  66074. }
  66075. }
  66076. var pos = PhysicsImpostor._tmpVecs[0];
  66077. var boneDir = PhysicsImpostor._tmpVecs[1];
  66078. if (!boneAxis) {
  66079. boneAxis = PhysicsImpostor._tmpVecs[2];
  66080. boneAxis.x = 0;
  66081. boneAxis.y = 1;
  66082. boneAxis.z = 0;
  66083. }
  66084. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  66085. bone.getAbsolutePositionToRef(boneMesh, pos);
  66086. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  66087. distToJoint = jointPivot.length();
  66088. }
  66089. if (distToJoint !== undefined && distToJoint !== null) {
  66090. pos.x += boneDir.x * distToJoint;
  66091. pos.y += boneDir.y * distToJoint;
  66092. pos.z += boneDir.z * distToJoint;
  66093. }
  66094. mesh.setAbsolutePosition(pos);
  66095. };
  66096. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  66097. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  66098. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66099. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  66100. //Impostor types
  66101. PhysicsImpostor.NoImpostor = 0;
  66102. PhysicsImpostor.SphereImpostor = 1;
  66103. PhysicsImpostor.BoxImpostor = 2;
  66104. PhysicsImpostor.PlaneImpostor = 3;
  66105. PhysicsImpostor.MeshImpostor = 4;
  66106. PhysicsImpostor.CylinderImpostor = 7;
  66107. PhysicsImpostor.ParticleImpostor = 8;
  66108. PhysicsImpostor.HeightmapImpostor = 9;
  66109. return PhysicsImpostor;
  66110. }());
  66111. BABYLON.PhysicsImpostor = PhysicsImpostor;
  66112. })(BABYLON || (BABYLON = {}));
  66113. //# sourceMappingURL=babylon.physicsImpostor.js.map
  66114. var BABYLON;
  66115. (function (BABYLON) {
  66116. var PhysicsEngine = /** @class */ (function () {
  66117. function PhysicsEngine(gravity, _physicsPlugin) {
  66118. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  66119. this._physicsPlugin = _physicsPlugin;
  66120. //new methods and parameters
  66121. this._impostors = [];
  66122. this._joints = [];
  66123. if (!this._physicsPlugin.isSupported()) {
  66124. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  66125. + "Please make sure it is included.");
  66126. }
  66127. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  66128. this.setGravity(gravity);
  66129. this.setTimeStep();
  66130. }
  66131. PhysicsEngine.prototype.setGravity = function (gravity) {
  66132. this.gravity = gravity;
  66133. this._physicsPlugin.setGravity(this.gravity);
  66134. };
  66135. /**
  66136. * Set the time step of the physics engine.
  66137. * default is 1/60.
  66138. * To slow it down, enter 1/600 for example.
  66139. * To speed it up, 1/30
  66140. * @param {number} newTimeStep the new timestep to apply to this world.
  66141. */
  66142. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  66143. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  66144. this._physicsPlugin.setTimeStep(newTimeStep);
  66145. };
  66146. /**
  66147. * Get the time step of the physics engine.
  66148. */
  66149. PhysicsEngine.prototype.getTimeStep = function () {
  66150. return this._physicsPlugin.getTimeStep();
  66151. };
  66152. PhysicsEngine.prototype.dispose = function () {
  66153. this._impostors.forEach(function (impostor) {
  66154. impostor.dispose();
  66155. });
  66156. this._physicsPlugin.dispose();
  66157. };
  66158. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  66159. return this._physicsPlugin.name;
  66160. };
  66161. /**
  66162. * Adding a new impostor for the impostor tracking.
  66163. * This will be done by the impostor itself.
  66164. * @param {PhysicsImpostor} impostor the impostor to add
  66165. */
  66166. PhysicsEngine.prototype.addImpostor = function (impostor) {
  66167. impostor.uniqueId = this._impostors.push(impostor);
  66168. //if no parent, generate the body
  66169. if (!impostor.parent) {
  66170. this._physicsPlugin.generatePhysicsBody(impostor);
  66171. }
  66172. };
  66173. /**
  66174. * Remove an impostor from the engine.
  66175. * This impostor and its mesh will not longer be updated by the physics engine.
  66176. * @param {PhysicsImpostor} impostor the impostor to remove
  66177. */
  66178. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  66179. var index = this._impostors.indexOf(impostor);
  66180. if (index > -1) {
  66181. var removed = this._impostors.splice(index, 1);
  66182. //Is it needed?
  66183. if (removed.length) {
  66184. //this will also remove it from the world.
  66185. removed[0].physicsBody = null;
  66186. }
  66187. }
  66188. };
  66189. /**
  66190. * Add a joint to the physics engine
  66191. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  66192. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  66193. * @param {PhysicsJoint} the joint that will connect both impostors.
  66194. */
  66195. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  66196. var impostorJoint = {
  66197. mainImpostor: mainImpostor,
  66198. connectedImpostor: connectedImpostor,
  66199. joint: joint
  66200. };
  66201. joint.physicsPlugin = this._physicsPlugin;
  66202. this._joints.push(impostorJoint);
  66203. this._physicsPlugin.generateJoint(impostorJoint);
  66204. };
  66205. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  66206. var matchingJoints = this._joints.filter(function (impostorJoint) {
  66207. return (impostorJoint.connectedImpostor === connectedImpostor
  66208. && impostorJoint.joint === joint
  66209. && impostorJoint.mainImpostor === mainImpostor);
  66210. });
  66211. if (matchingJoints.length) {
  66212. this._physicsPlugin.removeJoint(matchingJoints[0]);
  66213. //TODO remove it from the list as well
  66214. }
  66215. };
  66216. /**
  66217. * Called by the scene. no need to call it.
  66218. */
  66219. PhysicsEngine.prototype._step = function (delta) {
  66220. var _this = this;
  66221. //check if any mesh has no body / requires an update
  66222. this._impostors.forEach(function (impostor) {
  66223. if (impostor.isBodyInitRequired()) {
  66224. _this._physicsPlugin.generatePhysicsBody(impostor);
  66225. }
  66226. });
  66227. if (delta > 0.1) {
  66228. delta = 0.1;
  66229. }
  66230. else if (delta <= 0) {
  66231. delta = 1.0 / 60.0;
  66232. }
  66233. this._physicsPlugin.executeStep(delta, this._impostors);
  66234. };
  66235. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  66236. return this._physicsPlugin;
  66237. };
  66238. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  66239. for (var i = 0; i < this._impostors.length; ++i) {
  66240. if (this._impostors[i].object === object) {
  66241. return this._impostors[i];
  66242. }
  66243. }
  66244. return null;
  66245. };
  66246. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  66247. for (var i = 0; i < this._impostors.length; ++i) {
  66248. if (this._impostors[i].physicsBody === body) {
  66249. return this._impostors[i];
  66250. }
  66251. }
  66252. return null;
  66253. };
  66254. // Statics
  66255. PhysicsEngine.Epsilon = 0.001;
  66256. return PhysicsEngine;
  66257. }());
  66258. BABYLON.PhysicsEngine = PhysicsEngine;
  66259. })(BABYLON || (BABYLON = {}));
  66260. //# sourceMappingURL=babylon.physicsEngine.js.map
  66261. var BABYLON;
  66262. (function (BABYLON) {
  66263. var CannonJSPlugin = /** @class */ (function () {
  66264. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  66265. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  66266. if (iterations === void 0) { iterations = 10; }
  66267. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  66268. this.name = "CannonJSPlugin";
  66269. this._physicsMaterials = new Array();
  66270. this._fixedTimeStep = 1 / 60;
  66271. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  66272. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(15) : undefined);
  66273. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  66274. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  66275. this._tmpPosition = BABYLON.Vector3.Zero();
  66276. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  66277. this._tmpUnityRotation = new BABYLON.Quaternion();
  66278. if (!this.isSupported()) {
  66279. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  66280. return;
  66281. }
  66282. this.world = new this.BJSCANNON.World();
  66283. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  66284. this.world.solver.iterations = iterations;
  66285. }
  66286. CannonJSPlugin.prototype.setGravity = function (gravity) {
  66287. this.world.gravity.copy(gravity);
  66288. };
  66289. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  66290. this._fixedTimeStep = timeStep;
  66291. };
  66292. CannonJSPlugin.prototype.getTimeStep = function () {
  66293. return this._fixedTimeStep;
  66294. };
  66295. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  66296. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  66297. };
  66298. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66299. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66300. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66301. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  66302. };
  66303. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66304. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66305. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66306. impostor.physicsBody.applyForce(impulse, worldPoint);
  66307. };
  66308. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66309. //parent-child relationship. Does this impostor has a parent impostor?
  66310. if (impostor.parent) {
  66311. if (impostor.physicsBody) {
  66312. this.removePhysicsBody(impostor);
  66313. //TODO is that needed?
  66314. impostor.forceUpdate();
  66315. }
  66316. return;
  66317. }
  66318. //should a new body be created for this impostor?
  66319. if (impostor.isBodyInitRequired()) {
  66320. var shape = this._createShape(impostor);
  66321. //unregister events, if body is being changed
  66322. var oldBody = impostor.physicsBody;
  66323. if (oldBody) {
  66324. this.removePhysicsBody(impostor);
  66325. }
  66326. //create the body and material
  66327. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  66328. var bodyCreationObject = {
  66329. mass: impostor.getParam("mass"),
  66330. material: material
  66331. };
  66332. // A simple extend, in case native options were used.
  66333. var nativeOptions = impostor.getParam("nativeOptions");
  66334. for (var key in nativeOptions) {
  66335. if (nativeOptions.hasOwnProperty(key)) {
  66336. bodyCreationObject[key] = nativeOptions[key];
  66337. }
  66338. }
  66339. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  66340. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  66341. this.world.addEventListener("preStep", impostor.beforeStep);
  66342. this.world.addEventListener("postStep", impostor.afterStep);
  66343. impostor.physicsBody.addShape(shape);
  66344. this.world.add(impostor.physicsBody);
  66345. //try to keep the body moving in the right direction by taking old properties.
  66346. //Should be tested!
  66347. if (oldBody) {
  66348. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  66349. impostor.physicsBody[param].copy(oldBody[param]);
  66350. });
  66351. }
  66352. this._processChildMeshes(impostor);
  66353. }
  66354. //now update the body's transformation
  66355. this._updatePhysicsBodyTransformation(impostor);
  66356. };
  66357. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  66358. var _this = this;
  66359. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  66360. var currentRotation = mainImpostor.object.rotationQuaternion;
  66361. if (meshChildren.length) {
  66362. var processMesh = function (localPosition, mesh) {
  66363. if (!currentRotation || !mesh.rotationQuaternion) {
  66364. return;
  66365. }
  66366. var childImpostor = mesh.getPhysicsImpostor();
  66367. if (childImpostor) {
  66368. var parent = childImpostor.parent;
  66369. if (parent !== mainImpostor) {
  66370. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  66371. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  66372. if (childImpostor.physicsBody) {
  66373. _this.removePhysicsBody(childImpostor);
  66374. childImpostor.physicsBody = null;
  66375. }
  66376. childImpostor.parent = mainImpostor;
  66377. childImpostor.resetUpdateFlags();
  66378. 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));
  66379. //Add the mass of the children.
  66380. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  66381. }
  66382. }
  66383. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  66384. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  66385. };
  66386. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  66387. }
  66388. };
  66389. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66390. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  66391. this.world.removeEventListener("preStep", impostor.beforeStep);
  66392. this.world.removeEventListener("postStep", impostor.afterStep);
  66393. this.world.remove(impostor.physicsBody);
  66394. };
  66395. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66396. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66397. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66398. if (!mainBody || !connectedBody) {
  66399. return;
  66400. }
  66401. var constraint;
  66402. var jointData = impostorJoint.joint.jointData;
  66403. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  66404. var constraintData = {
  66405. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  66406. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  66407. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  66408. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  66409. maxForce: jointData.nativeParams.maxForce,
  66410. collideConnected: !!jointData.collision
  66411. };
  66412. switch (impostorJoint.joint.type) {
  66413. case BABYLON.PhysicsJoint.HingeJoint:
  66414. case BABYLON.PhysicsJoint.Hinge2Joint:
  66415. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  66416. break;
  66417. case BABYLON.PhysicsJoint.DistanceJoint:
  66418. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  66419. break;
  66420. case BABYLON.PhysicsJoint.SpringJoint:
  66421. var springData = jointData;
  66422. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  66423. restLength: springData.length,
  66424. stiffness: springData.stiffness,
  66425. damping: springData.damping,
  66426. localAnchorA: constraintData.pivotA,
  66427. localAnchorB: constraintData.pivotB
  66428. });
  66429. break;
  66430. case BABYLON.PhysicsJoint.LockJoint:
  66431. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  66432. break;
  66433. case BABYLON.PhysicsJoint.PointToPointJoint:
  66434. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66435. default:
  66436. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  66437. break;
  66438. }
  66439. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  66440. constraint.collideConnected = !!jointData.collision;
  66441. impostorJoint.joint.physicsJoint = constraint;
  66442. //don't add spring as constraint, as it is not one.
  66443. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  66444. this.world.addConstraint(constraint);
  66445. }
  66446. else {
  66447. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  66448. constraint.applyForce();
  66449. });
  66450. }
  66451. };
  66452. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66453. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  66454. };
  66455. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  66456. var index;
  66457. var mat;
  66458. for (index = 0; index < this._physicsMaterials.length; index++) {
  66459. mat = this._physicsMaterials[index];
  66460. if (mat.friction === friction && mat.restitution === restitution) {
  66461. return mat;
  66462. }
  66463. }
  66464. var currentMat = new this.BJSCANNON.Material(name);
  66465. currentMat.friction = friction;
  66466. currentMat.restitution = restitution;
  66467. this._physicsMaterials.push(currentMat);
  66468. return currentMat;
  66469. };
  66470. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  66471. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  66472. };
  66473. CannonJSPlugin.prototype._createShape = function (impostor) {
  66474. var object = impostor.object;
  66475. var returnValue;
  66476. var extendSize = impostor.getObjectExtendSize();
  66477. switch (impostor.type) {
  66478. case BABYLON.PhysicsImpostor.SphereImpostor:
  66479. var radiusX = extendSize.x;
  66480. var radiusY = extendSize.y;
  66481. var radiusZ = extendSize.z;
  66482. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  66483. break;
  66484. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  66485. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66486. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  66487. break;
  66488. case BABYLON.PhysicsImpostor.BoxImpostor:
  66489. var box = extendSize.scale(0.5);
  66490. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  66491. break;
  66492. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66493. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  66494. returnValue = new this.BJSCANNON.Plane();
  66495. break;
  66496. case BABYLON.PhysicsImpostor.MeshImpostor:
  66497. // should transform the vertex data to world coordinates!!
  66498. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  66499. var rawFaces = object.getIndices ? object.getIndices() : [];
  66500. if (!rawVerts)
  66501. return;
  66502. // get only scale! so the object could transform correctly.
  66503. var oldPosition = object.position.clone();
  66504. var oldRotation = object.rotation && object.rotation.clone();
  66505. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  66506. object.position.copyFromFloats(0, 0, 0);
  66507. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66508. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66509. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66510. var transform = object.computeWorldMatrix(true);
  66511. // convert rawVerts to object space
  66512. var temp = new Array();
  66513. var index;
  66514. for (index = 0; index < rawVerts.length; index += 3) {
  66515. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  66516. }
  66517. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  66518. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  66519. //now set back the transformation!
  66520. object.position.copyFrom(oldPosition);
  66521. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  66522. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  66523. break;
  66524. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  66525. var oldPosition2 = object.position.clone();
  66526. var oldRotation2 = object.rotation && object.rotation.clone();
  66527. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  66528. object.position.copyFromFloats(0, 0, 0);
  66529. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66530. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66531. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66532. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  66533. returnValue = this._createHeightmap(object);
  66534. object.position.copyFrom(oldPosition2);
  66535. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  66536. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  66537. object.computeWorldMatrix(true);
  66538. break;
  66539. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66540. returnValue = new this.BJSCANNON.Particle();
  66541. break;
  66542. }
  66543. return returnValue;
  66544. };
  66545. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  66546. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66547. var transform = object.computeWorldMatrix(true);
  66548. // convert rawVerts to object space
  66549. var temp = new Array();
  66550. var index;
  66551. for (index = 0; index < pos.length; index += 3) {
  66552. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  66553. }
  66554. pos = temp;
  66555. var matrix = new Array();
  66556. //For now pointDepth will not be used and will be automatically calculated.
  66557. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  66558. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  66559. var boundingInfo = (object.getBoundingInfo());
  66560. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  66561. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  66562. var elementSize = dim * 2 / arraySize;
  66563. for (var i = 0; i < pos.length; i = i + 3) {
  66564. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  66565. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  66566. var y = -pos[i + 2] + minY;
  66567. if (!matrix[x]) {
  66568. matrix[x] = [];
  66569. }
  66570. if (!matrix[x][z]) {
  66571. matrix[x][z] = y;
  66572. }
  66573. matrix[x][z] = Math.max(y, matrix[x][z]);
  66574. }
  66575. for (var x = 0; x <= arraySize; ++x) {
  66576. if (!matrix[x]) {
  66577. var loc = 1;
  66578. while (!matrix[(x + loc) % arraySize]) {
  66579. loc++;
  66580. }
  66581. matrix[x] = matrix[(x + loc) % arraySize].slice();
  66582. //console.log("missing x", x);
  66583. }
  66584. for (var z = 0; z <= arraySize; ++z) {
  66585. if (!matrix[x][z]) {
  66586. var loc = 1;
  66587. var newValue;
  66588. while (newValue === undefined) {
  66589. newValue = matrix[x][(z + loc++) % arraySize];
  66590. }
  66591. matrix[x][z] = newValue;
  66592. }
  66593. }
  66594. }
  66595. var shape = new this.BJSCANNON.Heightfield(matrix, {
  66596. elementSize: elementSize
  66597. });
  66598. //For future reference, needed for body transformation
  66599. shape.minY = minY;
  66600. return shape;
  66601. };
  66602. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  66603. var object = impostor.object;
  66604. //make sure it is updated...
  66605. object.computeWorldMatrix && object.computeWorldMatrix(true);
  66606. // The delta between the mesh position and the mesh bounding box center
  66607. var bInfo = object.getBoundingInfo();
  66608. if (!bInfo)
  66609. return;
  66610. var center = impostor.getObjectCenter();
  66611. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  66612. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  66613. this._tmpPosition.copyFrom(center);
  66614. var quaternion = object.rotationQuaternion;
  66615. if (!quaternion) {
  66616. return;
  66617. }
  66618. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  66619. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  66620. //-90 DEG in X, precalculated
  66621. quaternion = quaternion.multiply(this._minus90X);
  66622. //Invert! (Precalculated, 90 deg in X)
  66623. //No need to clone. this will never change.
  66624. impostor.setDeltaRotation(this._plus90X);
  66625. }
  66626. //If it is a heightfield, if should be centered.
  66627. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  66628. var mesh = object;
  66629. var boundingInfo = mesh.getBoundingInfo();
  66630. //calculate the correct body position:
  66631. var rotationQuaternion = mesh.rotationQuaternion;
  66632. mesh.rotationQuaternion = this._tmpUnityRotation;
  66633. mesh.computeWorldMatrix(true);
  66634. //get original center with no rotation
  66635. var c = center.clone();
  66636. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  66637. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66638. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66639. mesh.setPivotMatrix(p);
  66640. mesh.computeWorldMatrix(true);
  66641. //calculate the translation
  66642. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66643. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66644. //add it inverted to the delta
  66645. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66646. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66647. //rotation is back
  66648. mesh.rotationQuaternion = rotationQuaternion;
  66649. mesh.setPivotMatrix(oldPivot);
  66650. mesh.computeWorldMatrix(true);
  66651. }
  66652. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66653. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66654. //this._tmpPosition.copyFrom(object.position);
  66655. }
  66656. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66657. //Now update the impostor object
  66658. impostor.physicsBody.position.copy(this._tmpPosition);
  66659. impostor.physicsBody.quaternion.copy(quaternion);
  66660. };
  66661. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66662. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66663. if (impostor.object.rotationQuaternion) {
  66664. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66665. }
  66666. };
  66667. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66668. impostor.physicsBody.position.copy(newPosition);
  66669. impostor.physicsBody.quaternion.copy(newRotation);
  66670. };
  66671. CannonJSPlugin.prototype.isSupported = function () {
  66672. return this.BJSCANNON !== undefined;
  66673. };
  66674. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66675. impostor.physicsBody.velocity.copy(velocity);
  66676. };
  66677. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66678. impostor.physicsBody.angularVelocity.copy(velocity);
  66679. };
  66680. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66681. var v = impostor.physicsBody.velocity;
  66682. if (!v) {
  66683. return null;
  66684. }
  66685. return new BABYLON.Vector3(v.x, v.y, v.z);
  66686. };
  66687. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66688. var v = impostor.physicsBody.angularVelocity;
  66689. if (!v) {
  66690. return null;
  66691. }
  66692. return new BABYLON.Vector3(v.x, v.y, v.z);
  66693. };
  66694. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66695. impostor.physicsBody.mass = mass;
  66696. impostor.physicsBody.updateMassProperties();
  66697. };
  66698. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  66699. return impostor.physicsBody.mass;
  66700. };
  66701. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  66702. return impostor.physicsBody.material.friction;
  66703. };
  66704. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66705. impostor.physicsBody.material.friction = friction;
  66706. };
  66707. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66708. return impostor.physicsBody.material.restitution;
  66709. };
  66710. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66711. impostor.physicsBody.material.restitution = restitution;
  66712. };
  66713. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  66714. impostor.physicsBody.sleep();
  66715. };
  66716. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  66717. impostor.physicsBody.wakeUp();
  66718. };
  66719. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66720. joint.physicsJoint.distance = maxDistance;
  66721. };
  66722. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66723. // if (!motorIndex) {
  66724. // joint.physicsJoint.enableMotor();
  66725. // }
  66726. // }
  66727. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66728. // if (!motorIndex) {
  66729. // joint.physicsJoint.disableMotor();
  66730. // }
  66731. // }
  66732. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66733. if (!motorIndex) {
  66734. joint.physicsJoint.enableMotor();
  66735. joint.physicsJoint.setMotorSpeed(speed);
  66736. if (maxForce) {
  66737. this.setLimit(joint, maxForce);
  66738. }
  66739. }
  66740. };
  66741. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  66742. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  66743. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  66744. };
  66745. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66746. var body = impostor.physicsBody;
  66747. mesh.position.x = body.position.x;
  66748. mesh.position.y = body.position.y;
  66749. mesh.position.z = body.position.z;
  66750. if (mesh.rotationQuaternion) {
  66751. mesh.rotationQuaternion.x = body.quaternion.x;
  66752. mesh.rotationQuaternion.y = body.quaternion.y;
  66753. mesh.rotationQuaternion.z = body.quaternion.z;
  66754. mesh.rotationQuaternion.w = body.quaternion.w;
  66755. }
  66756. };
  66757. CannonJSPlugin.prototype.getRadius = function (impostor) {
  66758. var shape = impostor.physicsBody.shapes[0];
  66759. return shape.boundingSphereRadius;
  66760. };
  66761. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66762. var shape = impostor.physicsBody.shapes[0];
  66763. result.x = shape.halfExtents.x * 2;
  66764. result.y = shape.halfExtents.y * 2;
  66765. result.z = shape.halfExtents.z * 2;
  66766. };
  66767. CannonJSPlugin.prototype.dispose = function () {
  66768. };
  66769. return CannonJSPlugin;
  66770. }());
  66771. BABYLON.CannonJSPlugin = CannonJSPlugin;
  66772. })(BABYLON || (BABYLON = {}));
  66773. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  66774. var BABYLON;
  66775. (function (BABYLON) {
  66776. var OimoJSPlugin = /** @class */ (function () {
  66777. function OimoJSPlugin(iterations) {
  66778. this.name = "OimoJSPlugin";
  66779. this._tmpImpostorsArray = [];
  66780. this._tmpPositionVector = BABYLON.Vector3.Zero();
  66781. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(16) : undefined);
  66782. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  66783. this.world.worldscale(1);
  66784. this.world.clear();
  66785. //making sure no stats are calculated
  66786. this.world.isNoStat = true;
  66787. }
  66788. OimoJSPlugin.prototype.setGravity = function (gravity) {
  66789. this.world.gravity.copy(gravity);
  66790. };
  66791. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  66792. this.world.timeStep = timeStep;
  66793. };
  66794. OimoJSPlugin.prototype.getTimeStep = function () {
  66795. return this.world.timeStep;
  66796. };
  66797. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66798. var _this = this;
  66799. impostors.forEach(function (impostor) {
  66800. impostor.beforeStep();
  66801. });
  66802. this.world.step();
  66803. impostors.forEach(function (impostor) {
  66804. impostor.afterStep();
  66805. //update the ordered impostors array
  66806. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66807. });
  66808. //check for collisions
  66809. var contact = this.world.contacts;
  66810. while (contact !== null) {
  66811. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66812. contact = contact.next;
  66813. continue;
  66814. }
  66815. //is this body colliding with any other? get the impostor
  66816. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66817. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66818. if (!mainImpostor || !collidingImpostor) {
  66819. contact = contact.next;
  66820. continue;
  66821. }
  66822. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66823. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66824. contact = contact.next;
  66825. }
  66826. };
  66827. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66828. var mass = impostor.physicsBody.massInfo.mass;
  66829. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66830. };
  66831. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66832. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66833. this.applyImpulse(impostor, force, contactPoint);
  66834. };
  66835. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66836. var _this = this;
  66837. //parent-child relationship. Does this impostor has a parent impostor?
  66838. if (impostor.parent) {
  66839. if (impostor.physicsBody) {
  66840. this.removePhysicsBody(impostor);
  66841. //TODO is that needed?
  66842. impostor.forceUpdate();
  66843. }
  66844. return;
  66845. }
  66846. if (impostor.isBodyInitRequired()) {
  66847. var bodyConfig = {
  66848. name: impostor.uniqueId,
  66849. //Oimo must have mass, also for static objects.
  66850. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66851. size: [],
  66852. type: [],
  66853. pos: [],
  66854. rot: [],
  66855. move: impostor.getParam("mass") !== 0,
  66856. //Supporting older versions of Oimo
  66857. world: this.world
  66858. };
  66859. var impostors = [impostor];
  66860. var addToArray = function (parent) {
  66861. if (!parent.getChildMeshes)
  66862. return;
  66863. parent.getChildMeshes().forEach(function (m) {
  66864. if (m.physicsImpostor) {
  66865. impostors.push(m.physicsImpostor);
  66866. //m.physicsImpostor._init();
  66867. }
  66868. });
  66869. };
  66870. addToArray(impostor.object);
  66871. var checkWithEpsilon_1 = function (value) {
  66872. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66873. };
  66874. impostors.forEach(function (i) {
  66875. if (!impostor.object.rotationQuaternion) {
  66876. return;
  66877. }
  66878. //get the correct bounding box
  66879. var oldQuaternion = i.object.rotationQuaternion;
  66880. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66881. x: impostor.object.rotationQuaternion.x,
  66882. y: impostor.object.rotationQuaternion.y,
  66883. z: impostor.object.rotationQuaternion.z,
  66884. s: impostor.object.rotationQuaternion.w
  66885. });
  66886. var extendSize = i.getObjectExtendSize();
  66887. if (i === impostor) {
  66888. var center = impostor.getObjectCenter();
  66889. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66890. //Can also use Array.prototype.push.apply
  66891. bodyConfig.pos.push(center.x);
  66892. bodyConfig.pos.push(center.y);
  66893. bodyConfig.pos.push(center.z);
  66894. //tmp solution
  66895. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66896. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66897. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66898. }
  66899. else {
  66900. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66901. bodyConfig.pos.push(localPosition.x);
  66902. bodyConfig.pos.push(localPosition.y);
  66903. bodyConfig.pos.push(localPosition.z);
  66904. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66905. bodyConfig.rot.push(0);
  66906. bodyConfig.rot.push(0);
  66907. bodyConfig.rot.push(0);
  66908. }
  66909. // register mesh
  66910. switch (i.type) {
  66911. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66912. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66913. case BABYLON.PhysicsImpostor.SphereImpostor:
  66914. var radiusX = extendSize.x;
  66915. var radiusY = extendSize.y;
  66916. var radiusZ = extendSize.z;
  66917. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66918. bodyConfig.type.push('sphere');
  66919. //due to the way oimo works with compounds, add 3 times
  66920. bodyConfig.size.push(size);
  66921. bodyConfig.size.push(size);
  66922. bodyConfig.size.push(size);
  66923. break;
  66924. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66925. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66926. var sizeY = checkWithEpsilon_1(extendSize.y);
  66927. bodyConfig.type.push('cylinder');
  66928. bodyConfig.size.push(sizeX);
  66929. bodyConfig.size.push(sizeY);
  66930. //due to the way oimo works with compounds, add one more value.
  66931. bodyConfig.size.push(sizeY);
  66932. break;
  66933. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66934. case BABYLON.PhysicsImpostor.BoxImpostor:
  66935. default:
  66936. var sizeX = checkWithEpsilon_1(extendSize.x);
  66937. var sizeY = checkWithEpsilon_1(extendSize.y);
  66938. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66939. bodyConfig.type.push('box');
  66940. bodyConfig.size.push(sizeX);
  66941. bodyConfig.size.push(sizeY);
  66942. bodyConfig.size.push(sizeZ);
  66943. break;
  66944. }
  66945. //actually not needed, but hey...
  66946. i.object.rotationQuaternion = oldQuaternion;
  66947. });
  66948. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66949. }
  66950. else {
  66951. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66952. }
  66953. impostor.setDeltaPosition(this._tmpPositionVector);
  66954. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66955. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66956. };
  66957. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66958. //impostor.physicsBody.dispose();
  66959. //Same as : (older oimo versions)
  66960. this.world.removeRigidBody(impostor.physicsBody);
  66961. };
  66962. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66963. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66964. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66965. if (!mainBody || !connectedBody) {
  66966. return;
  66967. }
  66968. var jointData = impostorJoint.joint.jointData;
  66969. var options = jointData.nativeParams || {};
  66970. var type;
  66971. var nativeJointData = {
  66972. body1: mainBody,
  66973. body2: connectedBody,
  66974. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66975. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66976. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66977. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66978. min: options.min,
  66979. max: options.max,
  66980. collision: options.collision || jointData.collision,
  66981. spring: options.spring,
  66982. //supporting older version of Oimo
  66983. world: this.world
  66984. };
  66985. switch (impostorJoint.joint.type) {
  66986. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66987. type = "jointBall";
  66988. break;
  66989. case BABYLON.PhysicsJoint.SpringJoint:
  66990. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66991. var springData = jointData;
  66992. nativeJointData.min = springData.length || nativeJointData.min;
  66993. //Max should also be set, just make sure it is at least min
  66994. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66995. case BABYLON.PhysicsJoint.DistanceJoint:
  66996. type = "jointDistance";
  66997. nativeJointData.max = jointData.maxDistance;
  66998. break;
  66999. case BABYLON.PhysicsJoint.PrismaticJoint:
  67000. type = "jointPrisme";
  67001. break;
  67002. case BABYLON.PhysicsJoint.SliderJoint:
  67003. type = "jointSlide";
  67004. break;
  67005. case BABYLON.PhysicsJoint.WheelJoint:
  67006. type = "jointWheel";
  67007. break;
  67008. case BABYLON.PhysicsJoint.HingeJoint:
  67009. default:
  67010. type = "jointHinge";
  67011. break;
  67012. }
  67013. nativeJointData.type = type;
  67014. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  67015. };
  67016. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  67017. //Bug in Oimo prevents us from disposing a joint in the playground
  67018. //joint.joint.physicsJoint.dispose();
  67019. //So we will bruteforce it!
  67020. try {
  67021. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  67022. }
  67023. catch (e) {
  67024. BABYLON.Tools.Warn(e);
  67025. }
  67026. };
  67027. OimoJSPlugin.prototype.isSupported = function () {
  67028. return this.BJSOIMO !== undefined;
  67029. };
  67030. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  67031. if (!impostor.physicsBody.sleeping) {
  67032. //TODO check that
  67033. if (impostor.physicsBody.shapes.next) {
  67034. var parentShape = this._getLastShape(impostor.physicsBody);
  67035. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  67036. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  67037. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  67038. }
  67039. else {
  67040. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  67041. }
  67042. if (impostor.object.rotationQuaternion) {
  67043. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  67044. impostor.object.rotationQuaternion.normalize();
  67045. }
  67046. }
  67047. };
  67048. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  67049. var body = impostor.physicsBody;
  67050. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  67051. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  67052. body.syncShapes();
  67053. body.awake();
  67054. };
  67055. OimoJSPlugin.prototype._getLastShape = function (body) {
  67056. var lastShape = body.shapes;
  67057. while (lastShape.next) {
  67058. lastShape = lastShape.next;
  67059. }
  67060. return lastShape;
  67061. };
  67062. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  67063. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  67064. };
  67065. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  67066. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  67067. };
  67068. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  67069. var v = impostor.physicsBody.linearVelocity;
  67070. if (!v) {
  67071. return null;
  67072. }
  67073. return new BABYLON.Vector3(v.x, v.y, v.z);
  67074. };
  67075. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  67076. var v = impostor.physicsBody.angularVelocity;
  67077. if (!v) {
  67078. return null;
  67079. }
  67080. return new BABYLON.Vector3(v.x, v.y, v.z);
  67081. };
  67082. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  67083. var staticBody = mass === 0;
  67084. //this will actually set the body's density and not its mass.
  67085. //But this is how oimo treats the mass variable.
  67086. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  67087. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  67088. };
  67089. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  67090. return impostor.physicsBody.shapes.density;
  67091. };
  67092. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  67093. return impostor.physicsBody.shapes.friction;
  67094. };
  67095. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  67096. impostor.physicsBody.shapes.friction = friction;
  67097. };
  67098. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  67099. return impostor.physicsBody.shapes.restitution;
  67100. };
  67101. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  67102. impostor.physicsBody.shapes.restitution = restitution;
  67103. };
  67104. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  67105. impostor.physicsBody.sleep();
  67106. };
  67107. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  67108. impostor.physicsBody.awake();
  67109. };
  67110. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  67111. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  67112. if (minDistance !== void 0) {
  67113. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  67114. }
  67115. };
  67116. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  67117. //TODO separate rotational and transational motors.
  67118. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  67119. if (motor) {
  67120. motor.setMotor(speed, maxForce);
  67121. }
  67122. };
  67123. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  67124. //TODO separate rotational and transational motors.
  67125. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  67126. if (motor) {
  67127. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  67128. }
  67129. };
  67130. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  67131. var body = impostor.physicsBody;
  67132. mesh.position.x = body.position.x;
  67133. mesh.position.y = body.position.y;
  67134. mesh.position.z = body.position.z;
  67135. if (mesh.rotationQuaternion) {
  67136. mesh.rotationQuaternion.x = body.orientation.x;
  67137. mesh.rotationQuaternion.y = body.orientation.y;
  67138. mesh.rotationQuaternion.z = body.orientation.z;
  67139. mesh.rotationQuaternion.w = body.orientation.s;
  67140. }
  67141. };
  67142. OimoJSPlugin.prototype.getRadius = function (impostor) {
  67143. return impostor.physicsBody.shapes.radius;
  67144. };
  67145. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  67146. var shape = impostor.physicsBody.shapes;
  67147. result.x = shape.halfWidth * 2;
  67148. result.y = shape.halfHeight * 2;
  67149. result.z = shape.halfDepth * 2;
  67150. };
  67151. OimoJSPlugin.prototype.dispose = function () {
  67152. this.world.clear();
  67153. };
  67154. return OimoJSPlugin;
  67155. }());
  67156. BABYLON.OimoJSPlugin = OimoJSPlugin;
  67157. })(BABYLON || (BABYLON = {}));
  67158. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  67159. var BABYLON;
  67160. (function (BABYLON) {
  67161. var Internals;
  67162. (function (Internals) {
  67163. /*
  67164. * Based on jsTGALoader - Javascript loader for TGA file
  67165. * By Vincent Thibault
  67166. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  67167. */
  67168. var TGATools = /** @class */ (function () {
  67169. function TGATools() {
  67170. }
  67171. TGATools.GetTGAHeader = function (data) {
  67172. var offset = 0;
  67173. var header = {
  67174. id_length: data[offset++],
  67175. colormap_type: data[offset++],
  67176. image_type: data[offset++],
  67177. colormap_index: data[offset++] | data[offset++] << 8,
  67178. colormap_length: data[offset++] | data[offset++] << 8,
  67179. colormap_size: data[offset++],
  67180. origin: [
  67181. data[offset++] | data[offset++] << 8,
  67182. data[offset++] | data[offset++] << 8
  67183. ],
  67184. width: data[offset++] | data[offset++] << 8,
  67185. height: data[offset++] | data[offset++] << 8,
  67186. pixel_size: data[offset++],
  67187. flags: data[offset++]
  67188. };
  67189. return header;
  67190. };
  67191. TGATools.UploadContent = function (gl, data) {
  67192. // Not enough data to contain header ?
  67193. if (data.length < 19) {
  67194. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  67195. return;
  67196. }
  67197. // Read Header
  67198. var offset = 18;
  67199. var header = TGATools.GetTGAHeader(data);
  67200. // Assume it's a valid Targa file.
  67201. if (header.id_length + offset > data.length) {
  67202. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  67203. return;
  67204. }
  67205. // Skip not needed data
  67206. offset += header.id_length;
  67207. var use_rle = false;
  67208. var use_pal = false;
  67209. var use_rgb = false;
  67210. var use_grey = false;
  67211. // Get some informations.
  67212. switch (header.image_type) {
  67213. case TGATools._TYPE_RLE_INDEXED:
  67214. use_rle = true;
  67215. case TGATools._TYPE_INDEXED:
  67216. use_pal = true;
  67217. break;
  67218. case TGATools._TYPE_RLE_RGB:
  67219. use_rle = true;
  67220. case TGATools._TYPE_RGB:
  67221. use_rgb = true;
  67222. break;
  67223. case TGATools._TYPE_RLE_GREY:
  67224. use_rle = true;
  67225. case TGATools._TYPE_GREY:
  67226. use_grey = true;
  67227. break;
  67228. }
  67229. var pixel_data;
  67230. // var numAlphaBits = header.flags & 0xf;
  67231. var pixel_size = header.pixel_size >> 3;
  67232. var pixel_total = header.width * header.height * pixel_size;
  67233. // Read palettes
  67234. var palettes;
  67235. if (use_pal) {
  67236. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  67237. }
  67238. // Read LRE
  67239. if (use_rle) {
  67240. pixel_data = new Uint8Array(pixel_total);
  67241. var c, count, i;
  67242. var localOffset = 0;
  67243. var pixels = new Uint8Array(pixel_size);
  67244. while (offset < pixel_total && localOffset < pixel_total) {
  67245. c = data[offset++];
  67246. count = (c & 0x7f) + 1;
  67247. // RLE pixels
  67248. if (c & 0x80) {
  67249. // Bind pixel tmp array
  67250. for (i = 0; i < pixel_size; ++i) {
  67251. pixels[i] = data[offset++];
  67252. }
  67253. // Copy pixel array
  67254. for (i = 0; i < count; ++i) {
  67255. pixel_data.set(pixels, localOffset + i * pixel_size);
  67256. }
  67257. localOffset += pixel_size * count;
  67258. }
  67259. else {
  67260. count *= pixel_size;
  67261. for (i = 0; i < count; ++i) {
  67262. pixel_data[localOffset + i] = data[offset++];
  67263. }
  67264. localOffset += count;
  67265. }
  67266. }
  67267. }
  67268. else {
  67269. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  67270. }
  67271. // Load to texture
  67272. var x_start, y_start, x_step, y_step, y_end, x_end;
  67273. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  67274. default:
  67275. case TGATools._ORIGIN_UL:
  67276. x_start = 0;
  67277. x_step = 1;
  67278. x_end = header.width;
  67279. y_start = 0;
  67280. y_step = 1;
  67281. y_end = header.height;
  67282. break;
  67283. case TGATools._ORIGIN_BL:
  67284. x_start = 0;
  67285. x_step = 1;
  67286. x_end = header.width;
  67287. y_start = header.height - 1;
  67288. y_step = -1;
  67289. y_end = -1;
  67290. break;
  67291. case TGATools._ORIGIN_UR:
  67292. x_start = header.width - 1;
  67293. x_step = -1;
  67294. x_end = -1;
  67295. y_start = 0;
  67296. y_step = 1;
  67297. y_end = header.height;
  67298. break;
  67299. case TGATools._ORIGIN_BR:
  67300. x_start = header.width - 1;
  67301. x_step = -1;
  67302. x_end = -1;
  67303. y_start = header.height - 1;
  67304. y_step = -1;
  67305. y_end = -1;
  67306. break;
  67307. }
  67308. // Load the specify method
  67309. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  67310. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  67311. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  67312. };
  67313. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67314. var image = pixel_data, colormap = palettes;
  67315. var width = header.width, height = header.height;
  67316. var color, i = 0, x, y;
  67317. var imageData = new Uint8Array(width * height * 4);
  67318. for (y = y_start; y !== y_end; y += y_step) {
  67319. for (x = x_start; x !== x_end; x += x_step, i++) {
  67320. color = image[i];
  67321. imageData[(x + width * y) * 4 + 3] = 255;
  67322. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  67323. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  67324. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  67325. }
  67326. }
  67327. return imageData;
  67328. };
  67329. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67330. var image = pixel_data;
  67331. var width = header.width, height = header.height;
  67332. var color, i = 0, x, y;
  67333. var imageData = new Uint8Array(width * height * 4);
  67334. for (y = y_start; y !== y_end; y += y_step) {
  67335. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67336. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  67337. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  67338. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  67339. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  67340. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  67341. }
  67342. }
  67343. return imageData;
  67344. };
  67345. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67346. var image = pixel_data;
  67347. var width = header.width, height = header.height;
  67348. var i = 0, x, y;
  67349. var imageData = new Uint8Array(width * height * 4);
  67350. for (y = y_start; y !== y_end; y += y_step) {
  67351. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  67352. imageData[(x + width * y) * 4 + 3] = 255;
  67353. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67354. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67355. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67356. }
  67357. }
  67358. return imageData;
  67359. };
  67360. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67361. var image = pixel_data;
  67362. var width = header.width, height = header.height;
  67363. var i = 0, x, y;
  67364. var imageData = new Uint8Array(width * height * 4);
  67365. for (y = y_start; y !== y_end; y += y_step) {
  67366. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  67367. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67368. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67369. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67370. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  67371. }
  67372. }
  67373. return imageData;
  67374. };
  67375. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67376. var image = pixel_data;
  67377. var width = header.width, height = header.height;
  67378. var color, i = 0, x, y;
  67379. var imageData = new Uint8Array(width * height * 4);
  67380. for (y = y_start; y !== y_end; y += y_step) {
  67381. for (x = x_start; x !== x_end; x += x_step, i++) {
  67382. color = image[i];
  67383. imageData[(x + width * y) * 4 + 0] = color;
  67384. imageData[(x + width * y) * 4 + 1] = color;
  67385. imageData[(x + width * y) * 4 + 2] = color;
  67386. imageData[(x + width * y) * 4 + 3] = 255;
  67387. }
  67388. }
  67389. return imageData;
  67390. };
  67391. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67392. var image = pixel_data;
  67393. var width = header.width, height = header.height;
  67394. var i = 0, x, y;
  67395. var imageData = new Uint8Array(width * height * 4);
  67396. for (y = y_start; y !== y_end; y += y_step) {
  67397. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67398. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  67399. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  67400. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67401. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  67402. }
  67403. }
  67404. return imageData;
  67405. };
  67406. //private static _TYPE_NO_DATA = 0;
  67407. TGATools._TYPE_INDEXED = 1;
  67408. TGATools._TYPE_RGB = 2;
  67409. TGATools._TYPE_GREY = 3;
  67410. TGATools._TYPE_RLE_INDEXED = 9;
  67411. TGATools._TYPE_RLE_RGB = 10;
  67412. TGATools._TYPE_RLE_GREY = 11;
  67413. TGATools._ORIGIN_MASK = 0x30;
  67414. TGATools._ORIGIN_SHIFT = 0x04;
  67415. TGATools._ORIGIN_BL = 0x00;
  67416. TGATools._ORIGIN_BR = 0x01;
  67417. TGATools._ORIGIN_UL = 0x02;
  67418. TGATools._ORIGIN_UR = 0x03;
  67419. return TGATools;
  67420. }());
  67421. Internals.TGATools = TGATools;
  67422. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67423. })(BABYLON || (BABYLON = {}));
  67424. //# sourceMappingURL=babylon.tga.js.map
  67425. var BABYLON;
  67426. (function (BABYLON) {
  67427. var Internals;
  67428. (function (Internals) {
  67429. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  67430. // All values and structures referenced from:
  67431. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  67432. var DDS_MAGIC = 0x20534444;
  67433. var
  67434. //DDSD_CAPS = 0x1,
  67435. //DDSD_HEIGHT = 0x2,
  67436. //DDSD_WIDTH = 0x4,
  67437. //DDSD_PITCH = 0x8,
  67438. //DDSD_PIXELFORMAT = 0x1000,
  67439. DDSD_MIPMAPCOUNT = 0x20000;
  67440. //DDSD_LINEARSIZE = 0x80000,
  67441. //DDSD_DEPTH = 0x800000;
  67442. // var DDSCAPS_COMPLEX = 0x8,
  67443. // DDSCAPS_MIPMAP = 0x400000,
  67444. // DDSCAPS_TEXTURE = 0x1000;
  67445. var DDSCAPS2_CUBEMAP = 0x200;
  67446. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  67447. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  67448. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  67449. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  67450. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  67451. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  67452. // DDSCAPS2_VOLUME = 0x200000;
  67453. var
  67454. //DDPF_ALPHAPIXELS = 0x1,
  67455. //DDPF_ALPHA = 0x2,
  67456. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  67457. //DDPF_YUV = 0x200,
  67458. DDPF_LUMINANCE = 0x20000;
  67459. function FourCCToInt32(value) {
  67460. return value.charCodeAt(0) +
  67461. (value.charCodeAt(1) << 8) +
  67462. (value.charCodeAt(2) << 16) +
  67463. (value.charCodeAt(3) << 24);
  67464. }
  67465. function Int32ToFourCC(value) {
  67466. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  67467. }
  67468. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  67469. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  67470. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  67471. var FOURCC_DX10 = FourCCToInt32("DX10");
  67472. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  67473. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  67474. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  67475. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  67476. var headerLengthInt = 31; // The header length in 32 bit ints
  67477. // Offsets into the header array
  67478. var off_magic = 0;
  67479. var off_size = 1;
  67480. var off_flags = 2;
  67481. var off_height = 3;
  67482. var off_width = 4;
  67483. var off_mipmapCount = 7;
  67484. var off_pfFlags = 20;
  67485. var off_pfFourCC = 21;
  67486. var off_RGBbpp = 22;
  67487. // var off_RMask = 23;
  67488. // var off_GMask = 24;
  67489. // var off_BMask = 25;
  67490. // var off_AMask = 26;
  67491. // var off_caps1 = 27;
  67492. var off_caps2 = 28;
  67493. // var off_caps3 = 29;
  67494. // var off_caps4 = 30;
  67495. var off_dxgiFormat = 32;
  67496. ;
  67497. var DDSTools = /** @class */ (function () {
  67498. function DDSTools() {
  67499. }
  67500. DDSTools.GetDDSInfo = function (arrayBuffer) {
  67501. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  67502. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  67503. var mipmapCount = 1;
  67504. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  67505. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67506. }
  67507. var fourCC = header[off_pfFourCC];
  67508. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  67509. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67510. switch (fourCC) {
  67511. case FOURCC_D3DFMT_R16G16B16A16F:
  67512. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67513. break;
  67514. case FOURCC_D3DFMT_R32G32B32A32F:
  67515. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67516. break;
  67517. case FOURCC_DX10:
  67518. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  67519. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67520. break;
  67521. }
  67522. }
  67523. return {
  67524. width: header[off_width],
  67525. height: header[off_height],
  67526. mipmapCount: mipmapCount,
  67527. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  67528. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  67529. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  67530. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  67531. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  67532. dxgiFormat: dxgiFormat,
  67533. textureType: textureType
  67534. };
  67535. };
  67536. DDSTools._ToHalfFloat = function (value) {
  67537. if (!DDSTools._FloatView) {
  67538. DDSTools._FloatView = new Float32Array(1);
  67539. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  67540. }
  67541. DDSTools._FloatView[0] = value;
  67542. var x = DDSTools._Int32View[0];
  67543. var bits = (x >> 16) & 0x8000; /* Get the sign */
  67544. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  67545. var e = (x >> 23) & 0xff; /* Using int is faster here */
  67546. /* If zero, or denormal, or exponent underflows too much for a denormal
  67547. * half, return signed zero. */
  67548. if (e < 103) {
  67549. return bits;
  67550. }
  67551. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  67552. if (e > 142) {
  67553. bits |= 0x7c00;
  67554. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  67555. * not Inf, so make sure we set one mantissa bit too. */
  67556. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  67557. return bits;
  67558. }
  67559. /* If exponent underflows but not too much, return a denormal */
  67560. if (e < 113) {
  67561. m |= 0x0800;
  67562. /* Extra rounding may overflow and set mantissa to 0 and exponent
  67563. * to 1, which is OK. */
  67564. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  67565. return bits;
  67566. }
  67567. bits |= ((e - 112) << 10) | (m >> 1);
  67568. bits += m & 1;
  67569. return bits;
  67570. };
  67571. DDSTools._FromHalfFloat = function (value) {
  67572. var s = (value & 0x8000) >> 15;
  67573. var e = (value & 0x7C00) >> 10;
  67574. var f = value & 0x03FF;
  67575. if (e === 0) {
  67576. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  67577. }
  67578. else if (e == 0x1F) {
  67579. return f ? NaN : ((s ? -1 : 1) * Infinity);
  67580. }
  67581. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  67582. };
  67583. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67584. var destArray = new Float32Array(dataLength);
  67585. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67586. var index = 0;
  67587. for (var y = 0; y < height; y++) {
  67588. for (var x = 0; x < width; x++) {
  67589. var srcPos = (x + y * width) * 4;
  67590. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  67591. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  67592. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  67593. if (DDSTools.StoreLODInAlphaChannel) {
  67594. destArray[index + 3] = lod;
  67595. }
  67596. else {
  67597. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  67598. }
  67599. index += 4;
  67600. }
  67601. }
  67602. return destArray;
  67603. };
  67604. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67605. if (DDSTools.StoreLODInAlphaChannel) {
  67606. var destArray = new Uint16Array(dataLength);
  67607. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67608. var index = 0;
  67609. for (var y = 0; y < height; y++) {
  67610. for (var x = 0; x < width; x++) {
  67611. var srcPos = (x + y * width) * 4;
  67612. destArray[index] = srcData[srcPos];
  67613. destArray[index + 1] = srcData[srcPos + 1];
  67614. destArray[index + 2] = srcData[srcPos + 2];
  67615. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  67616. index += 4;
  67617. }
  67618. }
  67619. return destArray;
  67620. }
  67621. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  67622. };
  67623. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67624. if (DDSTools.StoreLODInAlphaChannel) {
  67625. var destArray = new Float32Array(dataLength);
  67626. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67627. var index = 0;
  67628. for (var y = 0; y < height; y++) {
  67629. for (var x = 0; x < width; x++) {
  67630. var srcPos = (x + y * width) * 4;
  67631. destArray[index] = srcData[srcPos];
  67632. destArray[index + 1] = srcData[srcPos + 1];
  67633. destArray[index + 2] = srcData[srcPos + 2];
  67634. destArray[index + 3] = lod;
  67635. index += 4;
  67636. }
  67637. }
  67638. return destArray;
  67639. }
  67640. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67641. };
  67642. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67643. var destArray = new Uint8Array(dataLength);
  67644. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67645. var index = 0;
  67646. for (var y = 0; y < height; y++) {
  67647. for (var x = 0; x < width; x++) {
  67648. var srcPos = (x + y * width) * 4;
  67649. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67650. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67651. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67652. if (DDSTools.StoreLODInAlphaChannel) {
  67653. destArray[index + 3] = lod;
  67654. }
  67655. else {
  67656. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67657. }
  67658. index += 4;
  67659. }
  67660. }
  67661. return destArray;
  67662. };
  67663. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67664. var destArray = new Uint8Array(dataLength);
  67665. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67666. var index = 0;
  67667. for (var y = 0; y < height; y++) {
  67668. for (var x = 0; x < width; x++) {
  67669. var srcPos = (x + y * width) * 4;
  67670. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67671. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67672. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67673. if (DDSTools.StoreLODInAlphaChannel) {
  67674. destArray[index + 3] = lod;
  67675. }
  67676. else {
  67677. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67678. }
  67679. index += 4;
  67680. }
  67681. }
  67682. return destArray;
  67683. };
  67684. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67685. var byteArray = new Uint8Array(dataLength);
  67686. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67687. var index = 0;
  67688. for (var y = 0; y < height; y++) {
  67689. for (var x = 0; x < width; x++) {
  67690. var srcPos = (x + y * width) * 4;
  67691. byteArray[index] = srcData[srcPos + 2];
  67692. byteArray[index + 1] = srcData[srcPos + 1];
  67693. byteArray[index + 2] = srcData[srcPos];
  67694. byteArray[index + 3] = srcData[srcPos + 3];
  67695. index += 4;
  67696. }
  67697. }
  67698. return byteArray;
  67699. };
  67700. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67701. var byteArray = new Uint8Array(dataLength);
  67702. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67703. var index = 0;
  67704. for (var y = 0; y < height; y++) {
  67705. for (var x = 0; x < width; x++) {
  67706. var srcPos = (x + y * width) * 3;
  67707. byteArray[index] = srcData[srcPos + 2];
  67708. byteArray[index + 1] = srcData[srcPos + 1];
  67709. byteArray[index + 2] = srcData[srcPos];
  67710. index += 3;
  67711. }
  67712. }
  67713. return byteArray;
  67714. };
  67715. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67716. var byteArray = new Uint8Array(dataLength);
  67717. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67718. var index = 0;
  67719. for (var y = 0; y < height; y++) {
  67720. for (var x = 0; x < width; x++) {
  67721. var srcPos = (x + y * width);
  67722. byteArray[index] = srcData[srcPos];
  67723. index++;
  67724. }
  67725. }
  67726. return byteArray;
  67727. };
  67728. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  67729. if (lodIndex === void 0) { lodIndex = -1; }
  67730. var ext = engine.getCaps().s3tc;
  67731. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  67732. var internalFormat = 0;
  67733. var format = 0;
  67734. var blockBytes = 1;
  67735. if (header[off_magic] != DDS_MAGIC) {
  67736. BABYLON.Tools.Error("Invalid magic number in DDS header");
  67737. return;
  67738. }
  67739. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  67740. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  67741. return;
  67742. }
  67743. if (info.isCompressed && !ext) {
  67744. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  67745. return;
  67746. }
  67747. var bpp = header[off_RGBbpp];
  67748. dataOffset = header[off_size] + 4;
  67749. var computeFormats = false;
  67750. if (info.isFourCC) {
  67751. fourCC = header[off_pfFourCC];
  67752. switch (fourCC) {
  67753. case FOURCC_DXT1:
  67754. blockBytes = 8;
  67755. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  67756. break;
  67757. case FOURCC_DXT3:
  67758. blockBytes = 16;
  67759. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  67760. break;
  67761. case FOURCC_DXT5:
  67762. blockBytes = 16;
  67763. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  67764. break;
  67765. case FOURCC_D3DFMT_R16G16B16A16F:
  67766. computeFormats = true;
  67767. break;
  67768. case FOURCC_D3DFMT_R32G32B32A32F:
  67769. computeFormats = true;
  67770. break;
  67771. case FOURCC_DX10:
  67772. // There is an additionnal header so dataOffset need to be changed
  67773. dataOffset += 5 * 4; // 5 uints
  67774. var supported = false;
  67775. switch (info.dxgiFormat) {
  67776. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  67777. computeFormats = true;
  67778. supported = true;
  67779. break;
  67780. case DXGI_FORMAT_B8G8R8X8_UNORM:
  67781. info.isRGB = true;
  67782. info.isFourCC = false;
  67783. bpp = 32;
  67784. supported = true;
  67785. break;
  67786. }
  67787. if (supported) {
  67788. break;
  67789. }
  67790. default:
  67791. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  67792. return;
  67793. }
  67794. }
  67795. if (computeFormats) {
  67796. format = engine._getWebGLTextureType(info.textureType);
  67797. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67798. }
  67799. mipmapCount = 1;
  67800. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67801. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67802. }
  67803. for (var face = 0; face < faces; face++) {
  67804. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67805. width = header[off_width];
  67806. height = header[off_height];
  67807. for (mip = 0; mip < mipmapCount; ++mip) {
  67808. if (lodIndex === -1 || lodIndex === mip) {
  67809. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67810. var i = (lodIndex === -1) ? mip : 0;
  67811. if (!info.isCompressed && info.isFourCC) {
  67812. dataLength = width * height * 4;
  67813. var FloatArray = null;
  67814. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67815. if (bpp === 128) {
  67816. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67817. }
  67818. else if (bpp === 64) {
  67819. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67820. }
  67821. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67822. format = engine._getWebGLTextureType(info.textureType);
  67823. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67824. }
  67825. else {
  67826. if (bpp === 128) {
  67827. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67828. }
  67829. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67830. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67831. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67832. format = engine._getWebGLTextureType(info.textureType);
  67833. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67834. }
  67835. else {
  67836. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67837. }
  67838. }
  67839. if (FloatArray) {
  67840. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67841. }
  67842. }
  67843. else if (info.isRGB) {
  67844. if (bpp === 24) {
  67845. dataLength = width * height * 3;
  67846. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67847. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67848. }
  67849. else {
  67850. dataLength = width * height * 4;
  67851. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67852. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67853. }
  67854. }
  67855. else if (info.isLuminance) {
  67856. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67857. var unpaddedRowSize = width;
  67858. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67859. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67860. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67861. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67862. }
  67863. else {
  67864. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67865. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67866. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67867. }
  67868. }
  67869. dataOffset += width * height * (bpp / 8);
  67870. width *= 0.5;
  67871. height *= 0.5;
  67872. width = Math.max(1.0, width);
  67873. height = Math.max(1.0, height);
  67874. }
  67875. }
  67876. };
  67877. DDSTools.StoreLODInAlphaChannel = false;
  67878. return DDSTools;
  67879. }());
  67880. Internals.DDSTools = DDSTools;
  67881. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67882. })(BABYLON || (BABYLON = {}));
  67883. //# sourceMappingURL=babylon.dds.js.map
  67884. var BABYLON;
  67885. (function (BABYLON) {
  67886. var Internals;
  67887. (function (Internals) {
  67888. /**
  67889. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67890. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67891. */
  67892. var KhronosTextureContainer = /** @class */ (function () {
  67893. /**
  67894. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67895. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67896. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67897. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67898. */
  67899. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67900. this.arrayBuffer = arrayBuffer;
  67901. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67902. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67903. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67904. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67905. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67906. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67907. BABYLON.Tools.Error("texture missing KTX identifier");
  67908. return;
  67909. }
  67910. // load the reset of the header in native 32 bit int
  67911. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67912. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67913. var oppositeEndianess = header[0] === 0x01020304;
  67914. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67915. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67916. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67917. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67918. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67919. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67920. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67921. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67922. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67923. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67924. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67925. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67926. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67927. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67928. if (this.glType !== 0) {
  67929. BABYLON.Tools.Error("only compressed formats currently supported");
  67930. return;
  67931. }
  67932. else {
  67933. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67934. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67935. }
  67936. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67937. BABYLON.Tools.Error("only 2D textures currently supported");
  67938. return;
  67939. }
  67940. if (this.numberOfArrayElements !== 0) {
  67941. BABYLON.Tools.Error("texture arrays not currently supported");
  67942. return;
  67943. }
  67944. if (this.numberOfFaces !== facesExpected) {
  67945. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67946. return;
  67947. }
  67948. // we now have a completely validated file, so could use existence of loadType as success
  67949. // would need to make this more elaborate & adjust checks above to support more than one load type
  67950. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67951. }
  67952. // not as fast hardware based, but will probably never need to use
  67953. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67954. return ((val & 0xFF) << 24)
  67955. | ((val & 0xFF00) << 8)
  67956. | ((val >> 8) & 0xFF00)
  67957. | ((val >> 24) & 0xFF);
  67958. };
  67959. /**
  67960. * It is assumed that the texture has already been created & is currently bound
  67961. */
  67962. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67963. switch (this.loadType) {
  67964. case KhronosTextureContainer.COMPRESSED_2D:
  67965. this._upload2DCompressedLevels(gl, loadMipmaps);
  67966. break;
  67967. case KhronosTextureContainer.TEX_2D:
  67968. case KhronosTextureContainer.COMPRESSED_3D:
  67969. case KhronosTextureContainer.TEX_3D:
  67970. }
  67971. };
  67972. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67973. // initialize width & height for level 1
  67974. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67975. var width = this.pixelWidth;
  67976. var height = this.pixelHeight;
  67977. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67978. for (var level = 0; level < mipmapCount; level++) {
  67979. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67980. for (var face = 0; face < this.numberOfFaces; face++) {
  67981. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67982. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67983. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67984. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67985. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67986. }
  67987. width = Math.max(1.0, width * 0.5);
  67988. height = Math.max(1.0, height * 0.5);
  67989. }
  67990. };
  67991. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67992. // load types
  67993. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67994. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67995. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67996. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67997. return KhronosTextureContainer;
  67998. }());
  67999. Internals.KhronosTextureContainer = KhronosTextureContainer;
  68000. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68001. })(BABYLON || (BABYLON = {}));
  68002. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  68003. var BABYLON;
  68004. (function (BABYLON) {
  68005. var Debug;
  68006. (function (Debug) {
  68007. /**
  68008. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  68009. */
  68010. var SkeletonViewer = /** @class */ (function () {
  68011. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  68012. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  68013. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  68014. this.skeleton = skeleton;
  68015. this.mesh = mesh;
  68016. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  68017. this.renderingGroupId = renderingGroupId;
  68018. this.color = BABYLON.Color3.White();
  68019. this._debugLines = new Array();
  68020. this._isEnabled = false;
  68021. this._scene = scene;
  68022. this.update();
  68023. this._renderFunction = this.update.bind(this);
  68024. }
  68025. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  68026. get: function () {
  68027. return this._isEnabled;
  68028. },
  68029. set: function (value) {
  68030. if (this._isEnabled === value) {
  68031. return;
  68032. }
  68033. this._isEnabled = value;
  68034. if (value) {
  68035. this._scene.registerBeforeRender(this._renderFunction);
  68036. }
  68037. else {
  68038. this._scene.unregisterBeforeRender(this._renderFunction);
  68039. }
  68040. },
  68041. enumerable: true,
  68042. configurable: true
  68043. });
  68044. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  68045. if (x === void 0) { x = 0; }
  68046. if (y === void 0) { y = 0; }
  68047. if (z === void 0) { z = 0; }
  68048. var tmat = BABYLON.Tmp.Matrix[0];
  68049. var parentBone = bone.getParent();
  68050. tmat.copyFrom(bone.getLocalMatrix());
  68051. if (x !== 0 || y !== 0 || z !== 0) {
  68052. var tmat2 = BABYLON.Tmp.Matrix[1];
  68053. BABYLON.Matrix.IdentityToRef(tmat2);
  68054. tmat2.m[12] = x;
  68055. tmat2.m[13] = y;
  68056. tmat2.m[14] = z;
  68057. tmat2.multiplyToRef(tmat, tmat);
  68058. }
  68059. if (parentBone) {
  68060. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  68061. }
  68062. tmat.multiplyToRef(meshMat, tmat);
  68063. position.x = tmat.m[12];
  68064. position.y = tmat.m[13];
  68065. position.z = tmat.m[14];
  68066. };
  68067. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  68068. var len = bones.length;
  68069. var meshPos = this.mesh.position;
  68070. for (var i = 0; i < len; i++) {
  68071. var bone = bones[i];
  68072. var points = this._debugLines[i];
  68073. if (!points) {
  68074. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68075. this._debugLines[i] = points;
  68076. }
  68077. this._getBonePosition(points[0], bone, meshMat);
  68078. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  68079. points[0].subtractInPlace(meshPos);
  68080. points[1].subtractInPlace(meshPos);
  68081. }
  68082. };
  68083. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  68084. var len = bones.length;
  68085. var boneNum = 0;
  68086. var meshPos = this.mesh.position;
  68087. for (var i = len - 1; i >= 0; i--) {
  68088. var childBone = bones[i];
  68089. var parentBone = childBone.getParent();
  68090. if (!parentBone) {
  68091. continue;
  68092. }
  68093. var points = this._debugLines[boneNum];
  68094. if (!points) {
  68095. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68096. this._debugLines[boneNum] = points;
  68097. }
  68098. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  68099. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  68100. points[0].subtractInPlace(meshPos);
  68101. points[1].subtractInPlace(meshPos);
  68102. boneNum++;
  68103. }
  68104. };
  68105. SkeletonViewer.prototype.update = function () {
  68106. if (this.autoUpdateBonesMatrices) {
  68107. this.skeleton.computeAbsoluteTransforms();
  68108. }
  68109. if (this.skeleton.bones[0].length === undefined) {
  68110. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  68111. }
  68112. else {
  68113. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  68114. }
  68115. if (!this._debugMesh) {
  68116. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  68117. this._debugMesh.renderingGroupId = this.renderingGroupId;
  68118. }
  68119. else {
  68120. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  68121. }
  68122. this._debugMesh.position.copyFrom(this.mesh.position);
  68123. this._debugMesh.color = this.color;
  68124. };
  68125. SkeletonViewer.prototype.dispose = function () {
  68126. if (this._debugMesh) {
  68127. this.isEnabled = false;
  68128. this._debugMesh.dispose();
  68129. this._debugMesh = null;
  68130. }
  68131. };
  68132. return SkeletonViewer;
  68133. }());
  68134. Debug.SkeletonViewer = SkeletonViewer;
  68135. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68136. })(BABYLON || (BABYLON = {}));
  68137. //# sourceMappingURL=babylon.skeletonViewer.js.map
  68138. var BABYLON;
  68139. (function (BABYLON) {
  68140. var Debug;
  68141. (function (Debug) {
  68142. var AxesViewer = /** @class */ (function () {
  68143. function AxesViewer(scene, scaleLines) {
  68144. if (scaleLines === void 0) { scaleLines = 1; }
  68145. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68146. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68147. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68148. this.scaleLines = 1;
  68149. this.scaleLines = scaleLines;
  68150. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  68151. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  68152. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  68153. this._xmesh.renderingGroupId = 2;
  68154. this._ymesh.renderingGroupId = 2;
  68155. this._zmesh.renderingGroupId = 2;
  68156. this._xmesh.material.checkReadyOnlyOnce = true;
  68157. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  68158. this._ymesh.material.checkReadyOnlyOnce = true;
  68159. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  68160. this._zmesh.material.checkReadyOnlyOnce = true;
  68161. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  68162. this.scene = scene;
  68163. }
  68164. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  68165. var scaleLines = this.scaleLines;
  68166. if (this._xmesh) {
  68167. this._xmesh.position.copyFrom(position);
  68168. }
  68169. if (this._ymesh) {
  68170. this._ymesh.position.copyFrom(position);
  68171. }
  68172. if (this._zmesh) {
  68173. this._zmesh.position.copyFrom(position);
  68174. }
  68175. var point2 = this._xline[1];
  68176. point2.x = xaxis.x * scaleLines;
  68177. point2.y = xaxis.y * scaleLines;
  68178. point2.z = xaxis.z * scaleLines;
  68179. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  68180. point2 = this._yline[1];
  68181. point2.x = yaxis.x * scaleLines;
  68182. point2.y = yaxis.y * scaleLines;
  68183. point2.z = yaxis.z * scaleLines;
  68184. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  68185. point2 = this._zline[1];
  68186. point2.x = zaxis.x * scaleLines;
  68187. point2.y = zaxis.y * scaleLines;
  68188. point2.z = zaxis.z * scaleLines;
  68189. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  68190. };
  68191. AxesViewer.prototype.dispose = function () {
  68192. if (this._xmesh) {
  68193. this._xmesh.dispose();
  68194. }
  68195. if (this._ymesh) {
  68196. this._ymesh.dispose();
  68197. }
  68198. if (this._zmesh) {
  68199. this._zmesh.dispose();
  68200. }
  68201. this._xmesh = null;
  68202. this._ymesh = null;
  68203. this._zmesh = null;
  68204. this.scene = null;
  68205. };
  68206. return AxesViewer;
  68207. }());
  68208. Debug.AxesViewer = AxesViewer;
  68209. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68210. })(BABYLON || (BABYLON = {}));
  68211. //# sourceMappingURL=babylon.axesViewer.js.map
  68212. var BABYLON;
  68213. (function (BABYLON) {
  68214. var Debug;
  68215. (function (Debug) {
  68216. var BoneAxesViewer = /** @class */ (function (_super) {
  68217. __extends(BoneAxesViewer, _super);
  68218. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  68219. if (scaleLines === void 0) { scaleLines = 1; }
  68220. var _this = _super.call(this, scene, scaleLines) || this;
  68221. _this.pos = BABYLON.Vector3.Zero();
  68222. _this.xaxis = BABYLON.Vector3.Zero();
  68223. _this.yaxis = BABYLON.Vector3.Zero();
  68224. _this.zaxis = BABYLON.Vector3.Zero();
  68225. _this.mesh = mesh;
  68226. _this.bone = bone;
  68227. return _this;
  68228. }
  68229. BoneAxesViewer.prototype.update = function () {
  68230. if (!this.mesh || !this.bone) {
  68231. return;
  68232. }
  68233. var bone = this.bone;
  68234. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  68235. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  68236. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  68237. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  68238. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  68239. };
  68240. BoneAxesViewer.prototype.dispose = function () {
  68241. if (this.mesh) {
  68242. this.mesh = null;
  68243. this.bone = null;
  68244. _super.prototype.dispose.call(this);
  68245. }
  68246. };
  68247. return BoneAxesViewer;
  68248. }(Debug.AxesViewer));
  68249. Debug.BoneAxesViewer = BoneAxesViewer;
  68250. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68251. })(BABYLON || (BABYLON = {}));
  68252. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  68253. var BABYLON;
  68254. (function (BABYLON) {
  68255. var RayHelper = /** @class */ (function () {
  68256. function RayHelper(ray) {
  68257. this.ray = ray;
  68258. }
  68259. RayHelper.CreateAndShow = function (ray, scene, color) {
  68260. var helper = new RayHelper(ray);
  68261. helper.show(scene, color);
  68262. return helper;
  68263. };
  68264. RayHelper.prototype.show = function (scene, color) {
  68265. if (!this._renderFunction && this.ray) {
  68266. var ray = this.ray;
  68267. this._renderFunction = this._render.bind(this);
  68268. this._scene = scene;
  68269. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  68270. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  68271. if (this._renderFunction) {
  68272. this._scene.registerBeforeRender(this._renderFunction);
  68273. }
  68274. }
  68275. if (color && this._renderLine) {
  68276. this._renderLine.color.copyFrom(color);
  68277. }
  68278. };
  68279. RayHelper.prototype.hide = function () {
  68280. if (this._renderFunction && this._scene) {
  68281. this._scene.unregisterBeforeRender(this._renderFunction);
  68282. this._scene = null;
  68283. this._renderFunction = null;
  68284. if (this._renderLine) {
  68285. this._renderLine.dispose();
  68286. this._renderLine = null;
  68287. }
  68288. this._renderPoints = [];
  68289. }
  68290. };
  68291. RayHelper.prototype._render = function () {
  68292. var ray = this.ray;
  68293. if (!ray) {
  68294. return;
  68295. }
  68296. var point = this._renderPoints[1];
  68297. var len = Math.min(ray.length, 1000000);
  68298. point.copyFrom(ray.direction);
  68299. point.scaleInPlace(len);
  68300. point.addInPlace(ray.origin);
  68301. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  68302. };
  68303. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  68304. this._attachedToMesh = mesh;
  68305. var ray = this.ray;
  68306. if (!ray) {
  68307. return;
  68308. }
  68309. if (!ray.direction) {
  68310. ray.direction = BABYLON.Vector3.Zero();
  68311. }
  68312. if (!ray.origin) {
  68313. ray.origin = BABYLON.Vector3.Zero();
  68314. }
  68315. if (length) {
  68316. ray.length = length;
  68317. }
  68318. if (!meshSpaceOrigin) {
  68319. meshSpaceOrigin = BABYLON.Vector3.Zero();
  68320. }
  68321. if (!meshSpaceDirection) {
  68322. // -1 so that this will work with Mesh.lookAt
  68323. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  68324. }
  68325. if (!this._meshSpaceDirection) {
  68326. this._meshSpaceDirection = meshSpaceDirection.clone();
  68327. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  68328. }
  68329. else {
  68330. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  68331. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  68332. }
  68333. if (!this._updateToMeshFunction) {
  68334. this._updateToMeshFunction = this._updateToMesh.bind(this);
  68335. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  68336. }
  68337. this._updateToMesh();
  68338. };
  68339. RayHelper.prototype.detachFromMesh = function () {
  68340. if (this._attachedToMesh) {
  68341. if (this._updateToMeshFunction) {
  68342. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  68343. }
  68344. this._attachedToMesh = null;
  68345. this._updateToMeshFunction = null;
  68346. }
  68347. };
  68348. RayHelper.prototype._updateToMesh = function () {
  68349. var ray = this.ray;
  68350. if (!this._attachedToMesh || !ray) {
  68351. return;
  68352. }
  68353. if (this._attachedToMesh._isDisposed) {
  68354. this.detachFromMesh();
  68355. return;
  68356. }
  68357. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  68358. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  68359. };
  68360. RayHelper.prototype.dispose = function () {
  68361. this.hide();
  68362. this.detachFromMesh();
  68363. this.ray = null;
  68364. };
  68365. return RayHelper;
  68366. }());
  68367. BABYLON.RayHelper = RayHelper;
  68368. })(BABYLON || (BABYLON = {}));
  68369. //# sourceMappingURL=babylon.rayHelper.js.map
  68370. var BABYLON;
  68371. (function (BABYLON) {
  68372. // load the inspector using require, if not present in the global namespace.
  68373. var DebugLayer = /** @class */ (function () {
  68374. function DebugLayer(scene) {
  68375. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  68376. this._scene = scene;
  68377. // load inspector using require, if it doesn't exist on the global namespace.
  68378. }
  68379. /** Creates the inspector window. */
  68380. DebugLayer.prototype._createInspector = function (config) {
  68381. if (config === void 0) { config = {}; }
  68382. var popup = config.popup || false;
  68383. var initialTab = config.initialTab || 0;
  68384. var parentElement = config.parentElement || null;
  68385. if (!this._inspector) {
  68386. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  68387. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  68388. } // else nothing to do,; instance is already existing
  68389. };
  68390. DebugLayer.prototype.isVisible = function () {
  68391. if (!this._inspector) {
  68392. return false;
  68393. }
  68394. return true;
  68395. };
  68396. DebugLayer.prototype.hide = function () {
  68397. if (this._inspector) {
  68398. try {
  68399. this._inspector.dispose();
  68400. }
  68401. catch (e) {
  68402. // If the inspector has been removed directly from the inspector tool
  68403. }
  68404. this._inspector = null;
  68405. }
  68406. };
  68407. DebugLayer.prototype.show = function (config) {
  68408. if (config === void 0) { config = {}; }
  68409. if (typeof this.BJSINSPECTOR == 'undefined') {
  68410. // Load inspector and add it to the DOM
  68411. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  68412. }
  68413. else {
  68414. // Otherwise creates the inspector
  68415. this._createInspector(config);
  68416. }
  68417. };
  68418. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  68419. return DebugLayer;
  68420. }());
  68421. BABYLON.DebugLayer = DebugLayer;
  68422. })(BABYLON || (BABYLON = {}));
  68423. //# sourceMappingURL=babylon.debugLayer.js.map
  68424. var BABYLON;
  68425. (function (BABYLON) {
  68426. var Debug;
  68427. (function (Debug) {
  68428. var PhysicsViewer = /** @class */ (function () {
  68429. function PhysicsViewer(scene) {
  68430. this._impostors = [];
  68431. this._meshes = [];
  68432. this._numMeshes = 0;
  68433. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68434. var physicEngine = this._scene.getPhysicsEngine();
  68435. if (physicEngine) {
  68436. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  68437. }
  68438. }
  68439. PhysicsViewer.prototype._updateDebugMeshes = function () {
  68440. var plugin = this._physicsEnginePlugin;
  68441. for (var i = 0; i < this._numMeshes; i++) {
  68442. var impostor = this._impostors[i];
  68443. if (!impostor) {
  68444. continue;
  68445. }
  68446. if (impostor.isDisposed) {
  68447. this.hideImpostor(this._impostors[i--]);
  68448. }
  68449. else {
  68450. var mesh = this._meshes[i];
  68451. if (mesh && plugin) {
  68452. plugin.syncMeshWithImpostor(mesh, impostor);
  68453. }
  68454. }
  68455. }
  68456. };
  68457. PhysicsViewer.prototype.showImpostor = function (impostor) {
  68458. if (!this._scene) {
  68459. return;
  68460. }
  68461. for (var i = 0; i < this._numMeshes; i++) {
  68462. if (this._impostors[i] == impostor) {
  68463. return;
  68464. }
  68465. }
  68466. var debugMesh = this._getDebugMesh(impostor, this._scene);
  68467. if (debugMesh) {
  68468. this._impostors[this._numMeshes] = impostor;
  68469. this._meshes[this._numMeshes] = debugMesh;
  68470. if (this._numMeshes === 0) {
  68471. this._renderFunction = this._updateDebugMeshes.bind(this);
  68472. this._scene.registerBeforeRender(this._renderFunction);
  68473. }
  68474. this._numMeshes++;
  68475. }
  68476. };
  68477. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  68478. if (!impostor || !this._scene) {
  68479. return;
  68480. }
  68481. var removed = false;
  68482. for (var i = 0; i < this._numMeshes; i++) {
  68483. if (this._impostors[i] == impostor) {
  68484. var mesh = this._meshes[i];
  68485. if (!mesh) {
  68486. continue;
  68487. }
  68488. this._scene.removeMesh(mesh);
  68489. mesh.dispose();
  68490. this._numMeshes--;
  68491. if (this._numMeshes > 0) {
  68492. this._meshes[i] = this._meshes[this._numMeshes];
  68493. this._impostors[i] = this._impostors[this._numMeshes];
  68494. this._meshes[this._numMeshes] = null;
  68495. this._impostors[this._numMeshes] = null;
  68496. }
  68497. else {
  68498. this._meshes[0] = null;
  68499. this._impostors[0] = null;
  68500. }
  68501. removed = true;
  68502. break;
  68503. }
  68504. }
  68505. if (removed && this._numMeshes === 0) {
  68506. this._scene.unregisterBeforeRender(this._renderFunction);
  68507. }
  68508. };
  68509. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  68510. if (!this._debugMaterial) {
  68511. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  68512. this._debugMaterial.wireframe = true;
  68513. }
  68514. return this._debugMaterial;
  68515. };
  68516. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  68517. if (!this._debugBoxMesh) {
  68518. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  68519. this._debugBoxMesh.renderingGroupId = 1;
  68520. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68521. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  68522. scene.removeMesh(this._debugBoxMesh);
  68523. }
  68524. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  68525. };
  68526. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  68527. if (!this._debugSphereMesh) {
  68528. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  68529. this._debugSphereMesh.renderingGroupId = 1;
  68530. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68531. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  68532. scene.removeMesh(this._debugSphereMesh);
  68533. }
  68534. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  68535. };
  68536. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  68537. var mesh = null;
  68538. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  68539. mesh = this._getDebugBoxMesh(scene);
  68540. impostor.getBoxSizeToRef(mesh.scaling);
  68541. }
  68542. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  68543. mesh = this._getDebugSphereMesh(scene);
  68544. var radius = impostor.getRadius();
  68545. mesh.scaling.x = radius * 2;
  68546. mesh.scaling.y = radius * 2;
  68547. mesh.scaling.z = radius * 2;
  68548. }
  68549. return mesh;
  68550. };
  68551. PhysicsViewer.prototype.dispose = function () {
  68552. for (var i = 0; i < this._numMeshes; i++) {
  68553. this.hideImpostor(this._impostors[i]);
  68554. }
  68555. if (this._debugBoxMesh) {
  68556. this._debugBoxMesh.dispose();
  68557. }
  68558. if (this._debugSphereMesh) {
  68559. this._debugSphereMesh.dispose();
  68560. }
  68561. if (this._debugMaterial) {
  68562. this._debugMaterial.dispose();
  68563. }
  68564. this._impostors.length = 0;
  68565. this._scene = null;
  68566. this._physicsEnginePlugin = null;
  68567. };
  68568. return PhysicsViewer;
  68569. }());
  68570. Debug.PhysicsViewer = PhysicsViewer;
  68571. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68572. })(BABYLON || (BABYLON = {}));
  68573. //# sourceMappingURL=babylon.physicsViewer.js.map
  68574. var BABYLON;
  68575. (function (BABYLON) {
  68576. var BoundingBoxRenderer = /** @class */ (function () {
  68577. function BoundingBoxRenderer(scene) {
  68578. this.frontColor = new BABYLON.Color3(1, 1, 1);
  68579. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  68580. this.showBackLines = true;
  68581. this.renderList = new BABYLON.SmartArray(32);
  68582. this._vertexBuffers = {};
  68583. this._scene = scene;
  68584. }
  68585. BoundingBoxRenderer.prototype._prepareRessources = function () {
  68586. if (this._colorShader) {
  68587. return;
  68588. }
  68589. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  68590. attributes: [BABYLON.VertexBuffer.PositionKind],
  68591. uniforms: ["world", "viewProjection", "color"]
  68592. });
  68593. var engine = this._scene.getEngine();
  68594. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  68595. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  68596. this._createIndexBuffer();
  68597. };
  68598. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  68599. var engine = this._scene.getEngine();
  68600. 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]);
  68601. };
  68602. BoundingBoxRenderer.prototype._rebuild = function () {
  68603. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68604. if (vb) {
  68605. vb._rebuild();
  68606. }
  68607. this._createIndexBuffer();
  68608. };
  68609. BoundingBoxRenderer.prototype.reset = function () {
  68610. this.renderList.reset();
  68611. };
  68612. BoundingBoxRenderer.prototype.render = function () {
  68613. if (this.renderList.length === 0) {
  68614. return;
  68615. }
  68616. this._prepareRessources();
  68617. if (!this._colorShader.isReady()) {
  68618. return;
  68619. }
  68620. var engine = this._scene.getEngine();
  68621. engine.setDepthWrite(false);
  68622. this._colorShader._preBind();
  68623. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  68624. var boundingBox = this.renderList.data[boundingBoxIndex];
  68625. var min = boundingBox.minimum;
  68626. var max = boundingBox.maximum;
  68627. var diff = max.subtract(min);
  68628. var median = min.add(diff.scale(0.5));
  68629. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68630. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68631. .multiply(boundingBox.getWorldMatrix());
  68632. // VBOs
  68633. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68634. if (this.showBackLines) {
  68635. // Back
  68636. engine.setDepthFunctionToGreaterOrEqual();
  68637. this._scene.resetCachedMaterial();
  68638. this._colorShader.setColor4("color", this.backColor.toColor4());
  68639. this._colorShader.bind(worldMatrix);
  68640. // Draw order
  68641. engine.draw(false, 0, 24);
  68642. }
  68643. // Front
  68644. engine.setDepthFunctionToLess();
  68645. this._scene.resetCachedMaterial();
  68646. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68647. this._colorShader.bind(worldMatrix);
  68648. // Draw order
  68649. engine.draw(false, 0, 24);
  68650. }
  68651. this._colorShader.unbind();
  68652. engine.setDepthFunctionToLessOrEqual();
  68653. engine.setDepthWrite(true);
  68654. };
  68655. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68656. this._prepareRessources();
  68657. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68658. return;
  68659. }
  68660. var engine = this._scene.getEngine();
  68661. engine.setDepthWrite(false);
  68662. engine.setColorWrite(false);
  68663. this._colorShader._preBind();
  68664. var boundingBox = mesh._boundingInfo.boundingBox;
  68665. var min = boundingBox.minimum;
  68666. var max = boundingBox.maximum;
  68667. var diff = max.subtract(min);
  68668. var median = min.add(diff.scale(0.5));
  68669. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68670. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68671. .multiply(boundingBox.getWorldMatrix());
  68672. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68673. engine.setDepthFunctionToLess();
  68674. this._scene.resetCachedMaterial();
  68675. this._colorShader.bind(worldMatrix);
  68676. engine.draw(false, 0, 24);
  68677. this._colorShader.unbind();
  68678. engine.setDepthFunctionToLessOrEqual();
  68679. engine.setDepthWrite(true);
  68680. engine.setColorWrite(true);
  68681. };
  68682. BoundingBoxRenderer.prototype.dispose = function () {
  68683. if (!this._colorShader) {
  68684. return;
  68685. }
  68686. this.renderList.dispose();
  68687. this._colorShader.dispose();
  68688. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68689. if (buffer) {
  68690. buffer.dispose();
  68691. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68692. }
  68693. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68694. };
  68695. return BoundingBoxRenderer;
  68696. }());
  68697. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  68698. })(BABYLON || (BABYLON = {}));
  68699. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  68700. var BABYLON;
  68701. (function (BABYLON) {
  68702. var MorphTarget = /** @class */ (function () {
  68703. function MorphTarget(name, influence) {
  68704. if (influence === void 0) { influence = 0; }
  68705. this.name = name;
  68706. this.animations = new Array();
  68707. this._positions = null;
  68708. this._normals = null;
  68709. this._tangents = null;
  68710. this.onInfluenceChanged = new BABYLON.Observable();
  68711. this.influence = influence;
  68712. }
  68713. Object.defineProperty(MorphTarget.prototype, "influence", {
  68714. get: function () {
  68715. return this._influence;
  68716. },
  68717. set: function (influence) {
  68718. if (this._influence === influence) {
  68719. return;
  68720. }
  68721. var previous = this._influence;
  68722. this._influence = influence;
  68723. if (this.onInfluenceChanged.hasObservers) {
  68724. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  68725. }
  68726. },
  68727. enumerable: true,
  68728. configurable: true
  68729. });
  68730. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  68731. get: function () {
  68732. return !!this._positions;
  68733. },
  68734. enumerable: true,
  68735. configurable: true
  68736. });
  68737. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  68738. get: function () {
  68739. return !!this._normals;
  68740. },
  68741. enumerable: true,
  68742. configurable: true
  68743. });
  68744. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  68745. get: function () {
  68746. return !!this._tangents;
  68747. },
  68748. enumerable: true,
  68749. configurable: true
  68750. });
  68751. MorphTarget.prototype.setPositions = function (data) {
  68752. this._positions = data;
  68753. };
  68754. MorphTarget.prototype.getPositions = function () {
  68755. return this._positions;
  68756. };
  68757. MorphTarget.prototype.setNormals = function (data) {
  68758. this._normals = data;
  68759. };
  68760. MorphTarget.prototype.getNormals = function () {
  68761. return this._normals;
  68762. };
  68763. MorphTarget.prototype.setTangents = function (data) {
  68764. this._tangents = data;
  68765. };
  68766. MorphTarget.prototype.getTangents = function () {
  68767. return this._tangents;
  68768. };
  68769. /**
  68770. * Serializes the current target into a Serialization object.
  68771. * Returns the serialized object.
  68772. */
  68773. MorphTarget.prototype.serialize = function () {
  68774. var serializationObject = {};
  68775. serializationObject.name = this.name;
  68776. serializationObject.influence = this.influence;
  68777. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  68778. if (this.hasNormals) {
  68779. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  68780. }
  68781. if (this.hasTangents) {
  68782. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  68783. }
  68784. // Animations
  68785. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  68786. return serializationObject;
  68787. };
  68788. // Statics
  68789. MorphTarget.Parse = function (serializationObject) {
  68790. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  68791. result.setPositions(serializationObject.positions);
  68792. if (serializationObject.normals) {
  68793. result.setNormals(serializationObject.normals);
  68794. }
  68795. if (serializationObject.tangents) {
  68796. result.setTangents(serializationObject.tangents);
  68797. }
  68798. // Animations
  68799. if (serializationObject.animations) {
  68800. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  68801. var parsedAnimation = serializationObject.animations[animationIndex];
  68802. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68803. }
  68804. }
  68805. return result;
  68806. };
  68807. MorphTarget.FromMesh = function (mesh, name, influence) {
  68808. if (!name) {
  68809. name = mesh.name;
  68810. }
  68811. var result = new MorphTarget(name, influence);
  68812. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68813. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68814. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68815. }
  68816. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68817. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68818. }
  68819. return result;
  68820. };
  68821. return MorphTarget;
  68822. }());
  68823. BABYLON.MorphTarget = MorphTarget;
  68824. })(BABYLON || (BABYLON = {}));
  68825. //# sourceMappingURL=babylon.morphTarget.js.map
  68826. var BABYLON;
  68827. (function (BABYLON) {
  68828. var MorphTargetManager = /** @class */ (function () {
  68829. function MorphTargetManager(scene) {
  68830. if (scene === void 0) { scene = null; }
  68831. this._targets = new Array();
  68832. this._targetObservable = new Array();
  68833. this._activeTargets = new BABYLON.SmartArray(16);
  68834. this._supportsNormals = false;
  68835. this._supportsTangents = false;
  68836. this._vertexCount = 0;
  68837. this._uniqueId = 0;
  68838. this._tempInfluences = new Array();
  68839. if (!scene) {
  68840. scene = BABYLON.Engine.LastCreatedScene;
  68841. }
  68842. this._scene = scene;
  68843. if (this._scene) {
  68844. this._scene.morphTargetManagers.push(this);
  68845. this._uniqueId = this._scene.getUniqueId();
  68846. }
  68847. }
  68848. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68849. get: function () {
  68850. return this._uniqueId;
  68851. },
  68852. enumerable: true,
  68853. configurable: true
  68854. });
  68855. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68856. get: function () {
  68857. return this._vertexCount;
  68858. },
  68859. enumerable: true,
  68860. configurable: true
  68861. });
  68862. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68863. get: function () {
  68864. return this._supportsNormals;
  68865. },
  68866. enumerable: true,
  68867. configurable: true
  68868. });
  68869. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68870. get: function () {
  68871. return this._supportsTangents;
  68872. },
  68873. enumerable: true,
  68874. configurable: true
  68875. });
  68876. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68877. get: function () {
  68878. return this._targets.length;
  68879. },
  68880. enumerable: true,
  68881. configurable: true
  68882. });
  68883. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68884. get: function () {
  68885. return this._activeTargets.length;
  68886. },
  68887. enumerable: true,
  68888. configurable: true
  68889. });
  68890. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68891. get: function () {
  68892. return this._influences;
  68893. },
  68894. enumerable: true,
  68895. configurable: true
  68896. });
  68897. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68898. return this._activeTargets.data[index];
  68899. };
  68900. MorphTargetManager.prototype.getTarget = function (index) {
  68901. return this._targets[index];
  68902. };
  68903. MorphTargetManager.prototype.addTarget = function (target) {
  68904. var _this = this;
  68905. this._targets.push(target);
  68906. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68907. _this._syncActiveTargets(needUpdate);
  68908. }));
  68909. this._syncActiveTargets(true);
  68910. };
  68911. MorphTargetManager.prototype.removeTarget = function (target) {
  68912. var index = this._targets.indexOf(target);
  68913. if (index >= 0) {
  68914. this._targets.splice(index, 1);
  68915. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68916. this._syncActiveTargets(true);
  68917. }
  68918. };
  68919. /**
  68920. * Serializes the current manager into a Serialization object.
  68921. * Returns the serialized object.
  68922. */
  68923. MorphTargetManager.prototype.serialize = function () {
  68924. var serializationObject = {};
  68925. serializationObject.id = this.uniqueId;
  68926. serializationObject.targets = [];
  68927. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68928. var target = _a[_i];
  68929. serializationObject.targets.push(target.serialize());
  68930. }
  68931. return serializationObject;
  68932. };
  68933. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68934. var influenceCount = 0;
  68935. this._activeTargets.reset();
  68936. this._supportsNormals = true;
  68937. this._supportsTangents = true;
  68938. this._vertexCount = 0;
  68939. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68940. var target = _a[_i];
  68941. if (target.influence > 0) {
  68942. this._activeTargets.push(target);
  68943. this._tempInfluences[influenceCount++] = target.influence;
  68944. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68945. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68946. var positions = target.getPositions();
  68947. if (!positions) {
  68948. BABYLON.Tools.Error("Invalid target. Target must positions.");
  68949. return;
  68950. }
  68951. var vertexCount = positions.length / 3;
  68952. if (this._vertexCount === 0) {
  68953. this._vertexCount = vertexCount;
  68954. }
  68955. else if (this._vertexCount !== vertexCount) {
  68956. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68957. return;
  68958. }
  68959. }
  68960. }
  68961. if (!this._influences || this._influences.length !== influenceCount) {
  68962. this._influences = new Float32Array(influenceCount);
  68963. }
  68964. for (var index = 0; index < influenceCount; index++) {
  68965. this._influences[index] = this._tempInfluences[index];
  68966. }
  68967. if (needUpdate && this._scene) {
  68968. // Flag meshes as dirty to resync with the active targets
  68969. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68970. var mesh = _c[_b];
  68971. if (mesh.morphTargetManager === this) {
  68972. mesh._syncGeometryWithMorphTargetManager();
  68973. }
  68974. }
  68975. }
  68976. };
  68977. // Statics
  68978. MorphTargetManager.Parse = function (serializationObject, scene) {
  68979. var result = new MorphTargetManager(scene);
  68980. result._uniqueId = serializationObject.id;
  68981. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68982. var targetData = _a[_i];
  68983. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68984. }
  68985. return result;
  68986. };
  68987. return MorphTargetManager;
  68988. }());
  68989. BABYLON.MorphTargetManager = MorphTargetManager;
  68990. })(BABYLON || (BABYLON = {}));
  68991. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68992. var BABYLON;
  68993. (function (BABYLON) {
  68994. var Octree = /** @class */ (function () {
  68995. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68996. if (maxDepth === void 0) { maxDepth = 2; }
  68997. this.maxDepth = maxDepth;
  68998. this.dynamicContent = new Array();
  68999. this._maxBlockCapacity = maxBlockCapacity || 64;
  69000. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  69001. this._creationFunc = creationFunc;
  69002. }
  69003. // Methods
  69004. Octree.prototype.update = function (worldMin, worldMax, entries) {
  69005. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  69006. };
  69007. Octree.prototype.addMesh = function (entry) {
  69008. for (var index = 0; index < this.blocks.length; index++) {
  69009. var block = this.blocks[index];
  69010. block.addEntry(entry);
  69011. }
  69012. };
  69013. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  69014. this._selectionContent.reset();
  69015. for (var index = 0; index < this.blocks.length; index++) {
  69016. var block = this.blocks[index];
  69017. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  69018. }
  69019. if (allowDuplicate) {
  69020. this._selectionContent.concat(this.dynamicContent);
  69021. }
  69022. else {
  69023. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69024. }
  69025. return this._selectionContent;
  69026. };
  69027. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  69028. this._selectionContent.reset();
  69029. for (var index = 0; index < this.blocks.length; index++) {
  69030. var block = this.blocks[index];
  69031. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  69032. }
  69033. if (allowDuplicate) {
  69034. this._selectionContent.concat(this.dynamicContent);
  69035. }
  69036. else {
  69037. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69038. }
  69039. return this._selectionContent;
  69040. };
  69041. Octree.prototype.intersectsRay = function (ray) {
  69042. this._selectionContent.reset();
  69043. for (var index = 0; index < this.blocks.length; index++) {
  69044. var block = this.blocks[index];
  69045. block.intersectsRay(ray, this._selectionContent);
  69046. }
  69047. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69048. return this._selectionContent;
  69049. };
  69050. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  69051. target.blocks = new Array();
  69052. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  69053. // Segmenting space
  69054. for (var x = 0; x < 2; x++) {
  69055. for (var y = 0; y < 2; y++) {
  69056. for (var z = 0; z < 2; z++) {
  69057. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  69058. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  69059. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  69060. block.addEntries(entries);
  69061. target.blocks.push(block);
  69062. }
  69063. }
  69064. }
  69065. };
  69066. Octree.CreationFuncForMeshes = function (entry, block) {
  69067. var boundingInfo = entry.getBoundingInfo();
  69068. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  69069. block.entries.push(entry);
  69070. }
  69071. };
  69072. Octree.CreationFuncForSubMeshes = function (entry, block) {
  69073. var boundingInfo = entry.getBoundingInfo();
  69074. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  69075. block.entries.push(entry);
  69076. }
  69077. };
  69078. return Octree;
  69079. }());
  69080. BABYLON.Octree = Octree;
  69081. })(BABYLON || (BABYLON = {}));
  69082. //# sourceMappingURL=babylon.octree.js.map
  69083. var BABYLON;
  69084. (function (BABYLON) {
  69085. var OctreeBlock = /** @class */ (function () {
  69086. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  69087. this.entries = new Array();
  69088. this._boundingVectors = new Array();
  69089. this._capacity = capacity;
  69090. this._depth = depth;
  69091. this._maxDepth = maxDepth;
  69092. this._creationFunc = creationFunc;
  69093. this._minPoint = minPoint;
  69094. this._maxPoint = maxPoint;
  69095. this._boundingVectors.push(minPoint.clone());
  69096. this._boundingVectors.push(maxPoint.clone());
  69097. this._boundingVectors.push(minPoint.clone());
  69098. this._boundingVectors[2].x = maxPoint.x;
  69099. this._boundingVectors.push(minPoint.clone());
  69100. this._boundingVectors[3].y = maxPoint.y;
  69101. this._boundingVectors.push(minPoint.clone());
  69102. this._boundingVectors[4].z = maxPoint.z;
  69103. this._boundingVectors.push(maxPoint.clone());
  69104. this._boundingVectors[5].z = minPoint.z;
  69105. this._boundingVectors.push(maxPoint.clone());
  69106. this._boundingVectors[6].x = minPoint.x;
  69107. this._boundingVectors.push(maxPoint.clone());
  69108. this._boundingVectors[7].y = minPoint.y;
  69109. }
  69110. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  69111. // Property
  69112. get: function () {
  69113. return this._capacity;
  69114. },
  69115. enumerable: true,
  69116. configurable: true
  69117. });
  69118. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  69119. get: function () {
  69120. return this._minPoint;
  69121. },
  69122. enumerable: true,
  69123. configurable: true
  69124. });
  69125. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  69126. get: function () {
  69127. return this._maxPoint;
  69128. },
  69129. enumerable: true,
  69130. configurable: true
  69131. });
  69132. // Methods
  69133. OctreeBlock.prototype.addEntry = function (entry) {
  69134. if (this.blocks) {
  69135. for (var index = 0; index < this.blocks.length; index++) {
  69136. var block = this.blocks[index];
  69137. block.addEntry(entry);
  69138. }
  69139. return;
  69140. }
  69141. this._creationFunc(entry, this);
  69142. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  69143. this.createInnerBlocks();
  69144. }
  69145. };
  69146. OctreeBlock.prototype.addEntries = function (entries) {
  69147. for (var index = 0; index < entries.length; index++) {
  69148. var mesh = entries[index];
  69149. this.addEntry(mesh);
  69150. }
  69151. };
  69152. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  69153. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  69154. if (this.blocks) {
  69155. for (var index = 0; index < this.blocks.length; index++) {
  69156. var block = this.blocks[index];
  69157. block.select(frustumPlanes, selection, allowDuplicate);
  69158. }
  69159. return;
  69160. }
  69161. if (allowDuplicate) {
  69162. selection.concat(this.entries);
  69163. }
  69164. else {
  69165. selection.concatWithNoDuplicate(this.entries);
  69166. }
  69167. }
  69168. };
  69169. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  69170. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  69171. if (this.blocks) {
  69172. for (var index = 0; index < this.blocks.length; index++) {
  69173. var block = this.blocks[index];
  69174. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  69175. }
  69176. return;
  69177. }
  69178. if (allowDuplicate) {
  69179. selection.concat(this.entries);
  69180. }
  69181. else {
  69182. selection.concatWithNoDuplicate(this.entries);
  69183. }
  69184. }
  69185. };
  69186. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  69187. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  69188. if (this.blocks) {
  69189. for (var index = 0; index < this.blocks.length; index++) {
  69190. var block = this.blocks[index];
  69191. block.intersectsRay(ray, selection);
  69192. }
  69193. return;
  69194. }
  69195. selection.concatWithNoDuplicate(this.entries);
  69196. }
  69197. };
  69198. OctreeBlock.prototype.createInnerBlocks = function () {
  69199. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  69200. };
  69201. return OctreeBlock;
  69202. }());
  69203. BABYLON.OctreeBlock = OctreeBlock;
  69204. })(BABYLON || (BABYLON = {}));
  69205. //# sourceMappingURL=babylon.octreeBlock.js.map
  69206. var BABYLON;
  69207. (function (BABYLON) {
  69208. var SIMDVector3 = /** @class */ (function () {
  69209. function SIMDVector3() {
  69210. }
  69211. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  69212. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  69213. };
  69214. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  69215. var m = transformation.m;
  69216. var m0 = SIMD.Float32x4.load(m, 0);
  69217. var m1 = SIMD.Float32x4.load(m, 4);
  69218. var m2 = SIMD.Float32x4.load(m, 8);
  69219. var m3 = SIMD.Float32x4.load(m, 12);
  69220. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  69221. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  69222. result.x = SIMD.Float32x4.extractLane(r, 0);
  69223. result.y = SIMD.Float32x4.extractLane(r, 1);
  69224. result.z = SIMD.Float32x4.extractLane(r, 2);
  69225. };
  69226. return SIMDVector3;
  69227. }());
  69228. var SIMDMatrix = /** @class */ (function () {
  69229. function SIMDMatrix() {
  69230. }
  69231. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  69232. var tm = this.m;
  69233. var om = other.m;
  69234. var m0 = SIMD.Float32x4.load(om, 0);
  69235. var m1 = SIMD.Float32x4.load(om, 4);
  69236. var m2 = SIMD.Float32x4.load(om, 8);
  69237. var m3 = SIMD.Float32x4.load(om, 12);
  69238. for (var i = 0; i < 16; i += 4) {
  69239. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  69240. }
  69241. return this;
  69242. };
  69243. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  69244. var src = this.m;
  69245. var dest = other.m;
  69246. // Load the 4 rows
  69247. var src0 = SIMD.Float32x4.load(src, 0);
  69248. var src1 = SIMD.Float32x4.load(src, 4);
  69249. var src2 = SIMD.Float32x4.load(src, 8);
  69250. var src3 = SIMD.Float32x4.load(src, 12);
  69251. // Transpose the source matrix. Sort of. Not a true transpose operation
  69252. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  69253. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  69254. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  69255. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  69256. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  69257. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  69258. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  69259. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  69260. // This is a true transposition, but it will lead to an incorrect result
  69261. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  69262. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  69263. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69264. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69265. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  69266. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  69267. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69268. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69269. // ----
  69270. tmp1 = SIMD.Float32x4.mul(row2, row3);
  69271. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69272. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  69273. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  69274. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69275. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  69276. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  69277. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  69278. // ----
  69279. tmp1 = SIMD.Float32x4.mul(row1, row2);
  69280. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69281. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  69282. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  69283. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69284. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  69285. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  69286. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  69287. // ----
  69288. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  69289. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69290. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  69291. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  69292. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  69293. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69294. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  69295. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  69296. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  69297. // ----
  69298. tmp1 = SIMD.Float32x4.mul(row0, row1);
  69299. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69300. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69301. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  69302. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69303. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69304. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  69305. // ----
  69306. tmp1 = SIMD.Float32x4.mul(row0, row3);
  69307. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69308. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  69309. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  69310. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69311. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  69312. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  69313. // ----
  69314. tmp1 = SIMD.Float32x4.mul(row0, row2);
  69315. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69316. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  69317. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  69318. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69319. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  69320. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  69321. // Compute determinant
  69322. var det = SIMD.Float32x4.mul(row0, minor0);
  69323. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  69324. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  69325. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  69326. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  69327. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  69328. // These shuffles aren't necessary if the faulty transposition is done
  69329. // up at the top of this function.
  69330. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  69331. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  69332. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  69333. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  69334. // Compute final values by multiplying with 1/det
  69335. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  69336. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  69337. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  69338. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  69339. return this;
  69340. };
  69341. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  69342. var out = result.m;
  69343. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  69344. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  69345. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  69346. // cc.kmVec3Subtract(f, pCenter, pEye);
  69347. var f = SIMD.Float32x4.sub(center, eye);
  69348. // cc.kmVec3Normalize(f, f);
  69349. var tmp = SIMD.Float32x4.mul(f, f);
  69350. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69351. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69352. // cc.kmVec3Assign(up, pUp);
  69353. // cc.kmVec3Normalize(up, up);
  69354. tmp = SIMD.Float32x4.mul(up, up);
  69355. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69356. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69357. // cc.kmVec3Cross(s, f, up);
  69358. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  69359. // cc.kmVec3Normalize(s, s);
  69360. tmp = SIMD.Float32x4.mul(s, s);
  69361. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69362. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69363. // cc.kmVec3Cross(u, s, f);
  69364. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  69365. // cc.kmVec3Normalize(s, s);
  69366. tmp = SIMD.Float32x4.mul(s, s);
  69367. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69368. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69369. var zero = SIMD.Float32x4.splat(0.0);
  69370. s = SIMD.Float32x4.neg(s);
  69371. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  69372. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  69373. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  69374. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  69375. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  69376. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  69377. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  69378. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69379. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  69380. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69381. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  69382. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69383. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  69384. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69385. };
  69386. return SIMDMatrix;
  69387. }());
  69388. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  69389. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  69390. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  69391. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  69392. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  69393. var SIMDHelper = /** @class */ (function () {
  69394. function SIMDHelper() {
  69395. }
  69396. Object.defineProperty(SIMDHelper, "IsEnabled", {
  69397. get: function () {
  69398. return SIMDHelper._isEnabled;
  69399. },
  69400. enumerable: true,
  69401. configurable: true
  69402. });
  69403. SIMDHelper.DisableSIMD = function () {
  69404. // Replace functions
  69405. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  69406. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  69407. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  69408. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  69409. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  69410. SIMDHelper._isEnabled = false;
  69411. };
  69412. SIMDHelper.EnableSIMD = function () {
  69413. if (self.SIMD === undefined) {
  69414. return;
  69415. }
  69416. // check if polyfills needed
  69417. if (!self.Math.fround) {
  69418. self.Math.fround = (function (array) { return function (x) {
  69419. return array[0] = x, array[0];
  69420. }; })(new Float32Array(1));
  69421. }
  69422. if (!self.Math.imul) {
  69423. self.Math.imul = function (a, b) {
  69424. var ah = (a >>> 16) & 0xffff;
  69425. var al = a & 0xffff;
  69426. var bh = (b >>> 16) & 0xffff;
  69427. var bl = b & 0xffff;
  69428. // the shift by 0 fixes the sign on the high part
  69429. // the final |0 converts the unsigned value into a signed value
  69430. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  69431. };
  69432. }
  69433. // Replace functions
  69434. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  69435. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  69436. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  69437. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  69438. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  69439. SIMDHelper._isEnabled = true;
  69440. };
  69441. SIMDHelper._isEnabled = false;
  69442. return SIMDHelper;
  69443. }());
  69444. BABYLON.SIMDHelper = SIMDHelper;
  69445. })(BABYLON || (BABYLON = {}));
  69446. //# sourceMappingURL=babylon.math.SIMD.js.map
  69447. var BABYLON;
  69448. (function (BABYLON) {
  69449. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  69450. __extends(VRDistortionCorrectionPostProcess, _super);
  69451. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  69452. var _this = _super.call(this, name, "vrDistortionCorrection", [
  69453. 'LensCenter',
  69454. 'Scale',
  69455. 'ScaleIn',
  69456. 'HmdWarpParam'
  69457. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  69458. _this._isRightEye = isRightEye;
  69459. _this._distortionFactors = vrMetrics.distortionK;
  69460. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  69461. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  69462. _this.adaptScaleToCurrentViewport = true;
  69463. _this.onSizeChangedObservable.add(function () {
  69464. _this.aspectRatio = _this.width * .5 / _this.height;
  69465. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  69466. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  69467. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  69468. });
  69469. _this.onApplyObservable.add(function (effect) {
  69470. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  69471. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  69472. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  69473. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  69474. });
  69475. return _this;
  69476. }
  69477. return VRDistortionCorrectionPostProcess;
  69478. }(BABYLON.PostProcess));
  69479. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  69480. })(BABYLON || (BABYLON = {}));
  69481. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  69482. var BABYLON;
  69483. (function (BABYLON) {
  69484. var AnaglyphPostProcess = /** @class */ (function (_super) {
  69485. __extends(AnaglyphPostProcess, _super);
  69486. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  69487. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  69488. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69489. _this.onApplyObservable.add(function (effect) {
  69490. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  69491. });
  69492. return _this;
  69493. }
  69494. return AnaglyphPostProcess;
  69495. }(BABYLON.PostProcess));
  69496. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  69497. })(BABYLON || (BABYLON = {}));
  69498. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  69499. var BABYLON;
  69500. (function (BABYLON) {
  69501. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  69502. __extends(StereoscopicInterlacePostProcess, _super);
  69503. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  69504. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  69505. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69506. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69507. _this.onSizeChangedObservable.add(function () {
  69508. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69509. });
  69510. _this.onApplyObservable.add(function (effect) {
  69511. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  69512. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  69513. });
  69514. return _this;
  69515. }
  69516. return StereoscopicInterlacePostProcess;
  69517. }(BABYLON.PostProcess));
  69518. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  69519. })(BABYLON || (BABYLON = {}));
  69520. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  69521. var BABYLON;
  69522. (function (BABYLON) {
  69523. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  69524. function FreeCameraDeviceOrientationInput() {
  69525. var _this = this;
  69526. this._screenOrientationAngle = 0;
  69527. this._screenQuaternion = new BABYLON.Quaternion();
  69528. this._alpha = 0;
  69529. this._beta = 0;
  69530. this._gamma = 0;
  69531. this._orientationChanged = function () {
  69532. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  69533. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  69534. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  69535. };
  69536. this._deviceOrientation = function (evt) {
  69537. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  69538. _this._beta = evt.beta !== null ? evt.beta : 0;
  69539. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  69540. };
  69541. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  69542. this._orientationChanged();
  69543. }
  69544. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  69545. get: function () {
  69546. return this._camera;
  69547. },
  69548. set: function (camera) {
  69549. this._camera = camera;
  69550. if (this._camera != null && !this._camera.rotationQuaternion) {
  69551. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  69552. }
  69553. },
  69554. enumerable: true,
  69555. configurable: true
  69556. });
  69557. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69558. window.addEventListener("orientationchange", this._orientationChanged);
  69559. window.addEventListener("deviceorientation", this._deviceOrientation);
  69560. //In certain cases, the attach control is called AFTER orientation was changed,
  69561. //So this is needed.
  69562. this._orientationChanged();
  69563. };
  69564. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  69565. window.removeEventListener("orientationchange", this._orientationChanged);
  69566. window.removeEventListener("deviceorientation", this._deviceOrientation);
  69567. };
  69568. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  69569. //if no device orientation provided, don't update the rotation.
  69570. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  69571. if (!this._alpha)
  69572. return;
  69573. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  69574. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  69575. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  69576. //Mirror on XY Plane
  69577. this._camera.rotationQuaternion.z *= -1;
  69578. this._camera.rotationQuaternion.w *= -1;
  69579. };
  69580. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  69581. return "FreeCameraDeviceOrientationInput";
  69582. };
  69583. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  69584. return "deviceOrientation";
  69585. };
  69586. return FreeCameraDeviceOrientationInput;
  69587. }());
  69588. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  69589. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  69590. })(BABYLON || (BABYLON = {}));
  69591. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  69592. var BABYLON;
  69593. (function (BABYLON) {
  69594. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  69595. function ArcRotateCameraVRDeviceOrientationInput() {
  69596. this.alphaCorrection = 1;
  69597. this.betaCorrection = 1;
  69598. this.gammaCorrection = 1;
  69599. this._alpha = 0;
  69600. this._beta = 0;
  69601. this._gamma = 0;
  69602. this._dirty = false;
  69603. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  69604. }
  69605. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69606. this.camera.attachControl(element, noPreventDefault);
  69607. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  69608. };
  69609. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  69610. if (evt.alpha !== null) {
  69611. this._alpha = +evt.alpha | 0;
  69612. }
  69613. if (evt.beta !== null) {
  69614. this._beta = +evt.beta | 0;
  69615. }
  69616. if (evt.gamma !== null) {
  69617. this._gamma = +evt.gamma | 0;
  69618. }
  69619. this._dirty = true;
  69620. };
  69621. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  69622. if (this._dirty) {
  69623. this._dirty = false;
  69624. if (this._gamma < 0) {
  69625. this._gamma = 180 + this._gamma;
  69626. }
  69627. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  69628. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  69629. }
  69630. };
  69631. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  69632. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  69633. };
  69634. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  69635. return "ArcRotateCameraVRDeviceOrientationInput";
  69636. };
  69637. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  69638. return "VRDeviceOrientation";
  69639. };
  69640. return ArcRotateCameraVRDeviceOrientationInput;
  69641. }());
  69642. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  69643. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  69644. })(BABYLON || (BABYLON = {}));
  69645. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  69646. var BABYLON;
  69647. (function (BABYLON) {
  69648. var VRCameraMetrics = /** @class */ (function () {
  69649. function VRCameraMetrics() {
  69650. this.compensateDistortion = true;
  69651. }
  69652. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  69653. get: function () {
  69654. return this.hResolution / (2 * this.vResolution);
  69655. },
  69656. enumerable: true,
  69657. configurable: true
  69658. });
  69659. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  69660. get: function () {
  69661. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  69662. },
  69663. enumerable: true,
  69664. configurable: true
  69665. });
  69666. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69667. get: function () {
  69668. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69669. var h = (4 * meters) / this.hScreenSize;
  69670. return BABYLON.Matrix.Translation(h, 0, 0);
  69671. },
  69672. enumerable: true,
  69673. configurable: true
  69674. });
  69675. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69676. get: function () {
  69677. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69678. var h = (4 * meters) / this.hScreenSize;
  69679. return BABYLON.Matrix.Translation(-h, 0, 0);
  69680. },
  69681. enumerable: true,
  69682. configurable: true
  69683. });
  69684. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  69685. get: function () {
  69686. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  69687. },
  69688. enumerable: true,
  69689. configurable: true
  69690. });
  69691. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  69692. get: function () {
  69693. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  69694. },
  69695. enumerable: true,
  69696. configurable: true
  69697. });
  69698. VRCameraMetrics.GetDefault = function () {
  69699. var result = new VRCameraMetrics();
  69700. result.hResolution = 1280;
  69701. result.vResolution = 800;
  69702. result.hScreenSize = 0.149759993;
  69703. result.vScreenSize = 0.0935999975;
  69704. result.vScreenCenter = 0.0467999987;
  69705. result.eyeToScreenDistance = 0.0410000011;
  69706. result.lensSeparationDistance = 0.0635000020;
  69707. result.interpupillaryDistance = 0.0640000030;
  69708. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  69709. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  69710. result.postProcessScaleFactor = 1.714605507808412;
  69711. result.lensCenterOffset = 0.151976421;
  69712. return result;
  69713. };
  69714. return VRCameraMetrics;
  69715. }());
  69716. BABYLON.VRCameraMetrics = VRCameraMetrics;
  69717. })(BABYLON || (BABYLON = {}));
  69718. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  69719. var BABYLON;
  69720. (function (BABYLON) {
  69721. var WebVRFreeCamera = /** @class */ (function (_super) {
  69722. __extends(WebVRFreeCamera, _super);
  69723. function WebVRFreeCamera(name, position, scene, webVROptions) {
  69724. if (webVROptions === void 0) { webVROptions = {}; }
  69725. var _this = _super.call(this, name, position, scene) || this;
  69726. _this.webVROptions = webVROptions;
  69727. _this._vrDevice = null;
  69728. _this.rawPose = null;
  69729. _this._specsVersion = "1.1";
  69730. _this._attached = false;
  69731. _this._descendants = [];
  69732. _this.devicePosition = BABYLON.Vector3.Zero();
  69733. _this.deviceScaleFactor = 1;
  69734. _this.controllers = [];
  69735. _this.onControllersAttachedObservable = new BABYLON.Observable();
  69736. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  69737. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  69738. _this.minZ = 0.1;
  69739. //legacy support - the compensation boolean was removed.
  69740. if (arguments.length === 5) {
  69741. _this.webVROptions = arguments[4];
  69742. }
  69743. // default webVR options
  69744. if (_this.webVROptions.trackPosition == undefined) {
  69745. _this.webVROptions.trackPosition = true;
  69746. }
  69747. if (_this.webVROptions.controllerMeshes == undefined) {
  69748. _this.webVROptions.controllerMeshes = true;
  69749. }
  69750. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  69751. _this.webVROptions.defaultLightingOnControllers = true;
  69752. }
  69753. _this.rotationQuaternion = new BABYLON.Quaternion();
  69754. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69755. if (_this.webVROptions && _this.webVROptions.positionScale) {
  69756. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  69757. }
  69758. //enable VR
  69759. var engine = _this.getEngine();
  69760. _this._onVREnabled = function (success) { if (success) {
  69761. _this.initControllers();
  69762. } };
  69763. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  69764. engine.initWebVR().add(function (event) {
  69765. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  69766. return;
  69767. }
  69768. _this._vrDevice = event.vrDisplay;
  69769. //reset the rig parameters.
  69770. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  69771. if (_this._attached) {
  69772. _this.getEngine().enableVR();
  69773. }
  69774. });
  69775. if (typeof (VRFrameData) !== "undefined")
  69776. _this._frameData = new VRFrameData();
  69777. /**
  69778. * The idea behind the following lines:
  69779. * objects that have the camera as parent should actually have the rig cameras as a parent.
  69780. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  69781. * the second will not show it correctly.
  69782. *
  69783. * To solve this - each object that has the camera as parent will be added to a protected array.
  69784. * When the rig camera renders, it will take this array and set all of those to be its children.
  69785. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  69786. * Amazing!
  69787. */
  69788. scene.onBeforeCameraRenderObservable.add(function (camera) {
  69789. if (camera.parent === _this && _this.rigParenting) {
  69790. _this._descendants = _this.getDescendants(true, function (n) {
  69791. // don't take the cameras or the controllers!
  69792. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  69793. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  69794. return !isController && !isRigCamera;
  69795. });
  69796. _this._descendants.forEach(function (node) {
  69797. node.parent = camera;
  69798. });
  69799. }
  69800. });
  69801. scene.onAfterCameraRenderObservable.add(function (camera) {
  69802. if (camera.parent === _this && _this.rigParenting) {
  69803. _this._descendants.forEach(function (node) {
  69804. node.parent = _this;
  69805. });
  69806. }
  69807. });
  69808. return _this;
  69809. }
  69810. WebVRFreeCamera.prototype.dispose = function () {
  69811. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  69812. _super.prototype.dispose.call(this);
  69813. };
  69814. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69815. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69816. var gp = _a[_i];
  69817. if (gp.hand === name) {
  69818. return gp;
  69819. }
  69820. }
  69821. return null;
  69822. };
  69823. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69824. get: function () {
  69825. if (!this._leftController) {
  69826. this._leftController = this.getControllerByName("left");
  69827. }
  69828. return this._leftController;
  69829. },
  69830. enumerable: true,
  69831. configurable: true
  69832. });
  69833. ;
  69834. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69835. get: function () {
  69836. if (!this._rightController) {
  69837. this._rightController = this.getControllerByName("right");
  69838. }
  69839. return this._rightController;
  69840. },
  69841. enumerable: true,
  69842. configurable: true
  69843. });
  69844. ;
  69845. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69846. if (length === void 0) { length = 100; }
  69847. if (this.leftCamera) {
  69848. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69849. }
  69850. else {
  69851. return _super.prototype.getForwardRay.call(this, length);
  69852. }
  69853. };
  69854. WebVRFreeCamera.prototype._checkInputs = function () {
  69855. if (this._vrDevice && this._vrDevice.isPresenting) {
  69856. this._vrDevice.getFrameData(this._frameData);
  69857. this.updateFromDevice(this._frameData.pose);
  69858. }
  69859. _super.prototype._checkInputs.call(this);
  69860. };
  69861. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69862. if (poseData && poseData.orientation) {
  69863. this.rawPose = poseData;
  69864. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69865. if (this.getScene().useRightHandedSystem) {
  69866. this.deviceRotationQuaternion.z *= -1;
  69867. this.deviceRotationQuaternion.w *= -1;
  69868. }
  69869. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69870. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69871. if (this.getScene().useRightHandedSystem) {
  69872. this.devicePosition.z *= -1;
  69873. }
  69874. }
  69875. }
  69876. };
  69877. /**
  69878. * WebVR's attach control will start broadcasting frames to the device.
  69879. * Note that in certain browsers (chrome for example) this function must be called
  69880. * within a user-interaction callback. Example:
  69881. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69882. *
  69883. * @param {HTMLElement} element
  69884. * @param {boolean} [noPreventDefault]
  69885. *
  69886. * @memberOf WebVRFreeCamera
  69887. */
  69888. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69889. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69890. this._attached = true;
  69891. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69892. if (this._vrDevice) {
  69893. this.getEngine().enableVR();
  69894. }
  69895. };
  69896. WebVRFreeCamera.prototype.detachControl = function (element) {
  69897. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69898. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69899. _super.prototype.detachControl.call(this, element);
  69900. this._attached = false;
  69901. this.getEngine().disableVR();
  69902. };
  69903. WebVRFreeCamera.prototype.getClassName = function () {
  69904. return "WebVRFreeCamera";
  69905. };
  69906. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69907. //uses the vrDisplay's "resetPose()".
  69908. //pitch and roll won't be affected.
  69909. this._vrDevice.resetPose();
  69910. };
  69911. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69912. var camLeft = this._rigCameras[0];
  69913. var camRight = this._rigCameras[1];
  69914. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69915. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69916. camLeft.position.copyFrom(this.devicePosition);
  69917. camRight.position.copyFrom(this.devicePosition);
  69918. };
  69919. /**
  69920. * This function is called by the two RIG cameras.
  69921. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69922. */
  69923. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69924. var _this = this;
  69925. //WebVR 1.1
  69926. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69927. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69928. if (!this.getScene().useRightHandedSystem) {
  69929. [2, 6, 8, 9, 14].forEach(function (num) {
  69930. _this._webvrViewMatrix.m[num] *= -1;
  69931. });
  69932. }
  69933. // update the camera rotation matrix
  69934. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69935. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69936. // Computing target and final matrix
  69937. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69938. var parentCamera = this._cameraRigParams["parentCamera"];
  69939. // should the view matrix be updated with scale and position offset?
  69940. if (parentCamera.deviceScaleFactor !== 1) {
  69941. this._webvrViewMatrix.invert();
  69942. // scale the position, if set
  69943. if (parentCamera.deviceScaleFactor) {
  69944. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69945. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69946. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69947. }
  69948. this._webvrViewMatrix.invert();
  69949. }
  69950. return this._webvrViewMatrix;
  69951. };
  69952. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69953. var _this = this;
  69954. var parentCamera = this.parent;
  69955. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69956. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69957. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69958. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69959. //babylon compatible matrix
  69960. if (!this.getScene().useRightHandedSystem) {
  69961. [8, 9, 10, 11].forEach(function (num) {
  69962. _this._projectionMatrix.m[num] *= -1;
  69963. });
  69964. }
  69965. return this._projectionMatrix;
  69966. };
  69967. WebVRFreeCamera.prototype.initControllers = function () {
  69968. var _this = this;
  69969. this.controllers = [];
  69970. var manager = this.getScene().gamepadManager;
  69971. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69972. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69973. var webVrController = gamepad;
  69974. if (webVrController.defaultModel) {
  69975. webVrController.defaultModel.setEnabled(false);
  69976. }
  69977. }
  69978. });
  69979. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69980. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69981. var webVrController_1 = gamepad;
  69982. if (_this.webVROptions.controllerMeshes) {
  69983. if (webVrController_1.defaultModel) {
  69984. webVrController_1.defaultModel.setEnabled(true);
  69985. }
  69986. else {
  69987. // Load the meshes
  69988. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69989. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69990. if (_this.webVROptions.defaultLightingOnControllers) {
  69991. if (!_this._lightOnControllers) {
  69992. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69993. }
  69994. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69995. var children = mesh.getChildren();
  69996. if (children.length !== 0) {
  69997. children.forEach(function (mesh) {
  69998. light.includedOnlyMeshes.push(mesh);
  69999. activateLightOnSubMeshes_1(mesh, light);
  70000. });
  70001. }
  70002. };
  70003. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  70004. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  70005. }
  70006. });
  70007. }
  70008. }
  70009. webVrController_1.attachToPoseControlledCamera(_this);
  70010. // since this is async - sanity check. Is the controller already stored?
  70011. if (_this.controllers.indexOf(webVrController_1) === -1) {
  70012. //add to the controllers array
  70013. _this.controllers.push(webVrController_1);
  70014. //did we find enough controllers? Great! let the developer know.
  70015. if (_this.controllers.length >= 2) {
  70016. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  70017. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  70018. // So we're overriding setting left & right manually to be sure
  70019. var firstViveWandDetected = false;
  70020. for (var i = 0; i < _this.controllers.length; i++) {
  70021. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  70022. if (!firstViveWandDetected) {
  70023. firstViveWandDetected = true;
  70024. _this.controllers[i].hand = "left";
  70025. }
  70026. else {
  70027. _this.controllers[i].hand = "right";
  70028. }
  70029. }
  70030. }
  70031. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  70032. }
  70033. }
  70034. }
  70035. });
  70036. };
  70037. return WebVRFreeCamera;
  70038. }(BABYLON.FreeCamera));
  70039. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  70040. })(BABYLON || (BABYLON = {}));
  70041. //# sourceMappingURL=babylon.webVRCamera.js.map
  70042. var BABYLON;
  70043. (function (BABYLON) {
  70044. // We're mainly based on the logic defined into the FreeCamera code
  70045. var DeviceOrientationCamera = /** @class */ (function (_super) {
  70046. __extends(DeviceOrientationCamera, _super);
  70047. function DeviceOrientationCamera(name, position, scene) {
  70048. var _this = _super.call(this, name, position, scene) || this;
  70049. _this._quaternionCache = new BABYLON.Quaternion();
  70050. _this.inputs.addDeviceOrientation();
  70051. return _this;
  70052. }
  70053. DeviceOrientationCamera.prototype.getClassName = function () {
  70054. return "DeviceOrientationCamera";
  70055. };
  70056. DeviceOrientationCamera.prototype._checkInputs = function () {
  70057. _super.prototype._checkInputs.call(this);
  70058. this._quaternionCache.copyFrom(this.rotationQuaternion);
  70059. if (this._initialQuaternion) {
  70060. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  70061. }
  70062. };
  70063. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  70064. var _this = this;
  70065. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  70066. //can only work if this camera has a rotation quaternion already.
  70067. if (!this.rotationQuaternion)
  70068. return;
  70069. if (!this._initialQuaternion) {
  70070. this._initialQuaternion = new BABYLON.Quaternion();
  70071. }
  70072. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  70073. ['x', 'y', 'z'].forEach(function (axisName) {
  70074. if (!axis[axisName]) {
  70075. _this._initialQuaternion[axisName] = 0;
  70076. }
  70077. else {
  70078. _this._initialQuaternion[axisName] *= -1;
  70079. }
  70080. });
  70081. this._initialQuaternion.normalize();
  70082. //force rotation update
  70083. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  70084. };
  70085. return DeviceOrientationCamera;
  70086. }(BABYLON.FreeCamera));
  70087. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  70088. })(BABYLON || (BABYLON = {}));
  70089. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  70090. var BABYLON;
  70091. (function (BABYLON) {
  70092. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  70093. __extends(VRDeviceOrientationFreeCamera, _super);
  70094. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  70095. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70096. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70097. var _this = _super.call(this, name, position, scene) || this;
  70098. vrCameraMetrics.compensateDistortion = compensateDistortion;
  70099. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  70100. return _this;
  70101. }
  70102. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  70103. return "VRDeviceOrientationFreeCamera";
  70104. };
  70105. return VRDeviceOrientationFreeCamera;
  70106. }(BABYLON.DeviceOrientationCamera));
  70107. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  70108. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  70109. __extends(VRDeviceOrientationGamepadCamera, _super);
  70110. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  70111. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70112. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70113. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  70114. _this.inputs.addGamepad();
  70115. return _this;
  70116. }
  70117. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  70118. return "VRDeviceOrientationGamepadCamera";
  70119. };
  70120. return VRDeviceOrientationGamepadCamera;
  70121. }(VRDeviceOrientationFreeCamera));
  70122. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  70123. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  70124. __extends(VRDeviceOrientationArcRotateCamera, _super);
  70125. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  70126. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70127. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70128. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70129. vrCameraMetrics.compensateDistortion = compensateDistortion;
  70130. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  70131. _this.inputs.addVRDeviceOrientation();
  70132. return _this;
  70133. }
  70134. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  70135. return "VRDeviceOrientationArcRotateCamera";
  70136. };
  70137. return VRDeviceOrientationArcRotateCamera;
  70138. }(BABYLON.ArcRotateCamera));
  70139. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  70140. })(BABYLON || (BABYLON = {}));
  70141. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  70142. var BABYLON;
  70143. (function (BABYLON) {
  70144. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  70145. __extends(AnaglyphFreeCamera, _super);
  70146. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  70147. var _this = _super.call(this, name, position, scene) || this;
  70148. _this.interaxialDistance = interaxialDistance;
  70149. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70150. return _this;
  70151. }
  70152. AnaglyphFreeCamera.prototype.getClassName = function () {
  70153. return "AnaglyphFreeCamera";
  70154. };
  70155. return AnaglyphFreeCamera;
  70156. }(BABYLON.FreeCamera));
  70157. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  70158. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  70159. __extends(AnaglyphArcRotateCamera, _super);
  70160. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  70161. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70162. _this.interaxialDistance = interaxialDistance;
  70163. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70164. return _this;
  70165. }
  70166. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  70167. return "AnaglyphArcRotateCamera";
  70168. };
  70169. return AnaglyphArcRotateCamera;
  70170. }(BABYLON.ArcRotateCamera));
  70171. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  70172. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  70173. __extends(AnaglyphGamepadCamera, _super);
  70174. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  70175. var _this = _super.call(this, name, position, scene) || this;
  70176. _this.interaxialDistance = interaxialDistance;
  70177. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70178. return _this;
  70179. }
  70180. AnaglyphGamepadCamera.prototype.getClassName = function () {
  70181. return "AnaglyphGamepadCamera";
  70182. };
  70183. return AnaglyphGamepadCamera;
  70184. }(BABYLON.GamepadCamera));
  70185. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  70186. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  70187. __extends(AnaglyphUniversalCamera, _super);
  70188. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  70189. var _this = _super.call(this, name, position, scene) || this;
  70190. _this.interaxialDistance = interaxialDistance;
  70191. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70192. return _this;
  70193. }
  70194. AnaglyphUniversalCamera.prototype.getClassName = function () {
  70195. return "AnaglyphUniversalCamera";
  70196. };
  70197. return AnaglyphUniversalCamera;
  70198. }(BABYLON.UniversalCamera));
  70199. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  70200. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  70201. __extends(StereoscopicFreeCamera, _super);
  70202. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70203. var _this = _super.call(this, name, position, scene) || this;
  70204. _this.interaxialDistance = interaxialDistance;
  70205. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70206. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70207. return _this;
  70208. }
  70209. StereoscopicFreeCamera.prototype.getClassName = function () {
  70210. return "StereoscopicFreeCamera";
  70211. };
  70212. return StereoscopicFreeCamera;
  70213. }(BABYLON.FreeCamera));
  70214. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  70215. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  70216. __extends(StereoscopicArcRotateCamera, _super);
  70217. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  70218. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70219. _this.interaxialDistance = interaxialDistance;
  70220. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70221. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70222. return _this;
  70223. }
  70224. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  70225. return "StereoscopicArcRotateCamera";
  70226. };
  70227. return StereoscopicArcRotateCamera;
  70228. }(BABYLON.ArcRotateCamera));
  70229. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  70230. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  70231. __extends(StereoscopicGamepadCamera, _super);
  70232. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70233. var _this = _super.call(this, name, position, scene) || this;
  70234. _this.interaxialDistance = interaxialDistance;
  70235. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70236. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70237. return _this;
  70238. }
  70239. StereoscopicGamepadCamera.prototype.getClassName = function () {
  70240. return "StereoscopicGamepadCamera";
  70241. };
  70242. return StereoscopicGamepadCamera;
  70243. }(BABYLON.GamepadCamera));
  70244. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  70245. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  70246. __extends(StereoscopicUniversalCamera, _super);
  70247. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70248. var _this = _super.call(this, name, position, scene) || this;
  70249. _this.interaxialDistance = interaxialDistance;
  70250. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70251. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70252. return _this;
  70253. }
  70254. StereoscopicUniversalCamera.prototype.getClassName = function () {
  70255. return "StereoscopicUniversalCamera";
  70256. };
  70257. return StereoscopicUniversalCamera;
  70258. }(BABYLON.UniversalCamera));
  70259. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  70260. })(BABYLON || (BABYLON = {}));
  70261. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  70262. var BABYLON;
  70263. (function (BABYLON) {
  70264. var VRExperienceHelper = /** @class */ (function () {
  70265. function VRExperienceHelper(scene, webVROptions) {
  70266. if (webVROptions === void 0) { webVROptions = {}; }
  70267. var _this = this;
  70268. this.webVROptions = webVROptions;
  70269. // Can the system support WebVR, even if a headset isn't plugged in?
  70270. this._webVRsupported = false;
  70271. // If WebVR is supported, is a headset plugged in and are we ready to present?
  70272. this._webVRready = false;
  70273. // Are we waiting for the requestPresent callback to complete?
  70274. this._webVRrequesting = false;
  70275. // Are we presenting to the headset right now?
  70276. this._webVRpresenting = false;
  70277. // Are we presenting in the fullscreen fallback?
  70278. this._fullscreenVRpresenting = false;
  70279. this._scene = scene;
  70280. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  70281. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  70282. }
  70283. else {
  70284. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  70285. if (scene.activeCamera.rotation) {
  70286. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  70287. }
  70288. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  70289. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  70290. }
  70291. this._scene.activeCamera = this._deviceOrientationCamera;
  70292. this._position = this._scene.activeCamera.position;
  70293. this._canvas = scene.getEngine().getRenderingCanvas();
  70294. if (this._canvas) {
  70295. this._scene.activeCamera.attachControl(this._canvas);
  70296. }
  70297. this._btnVR = document.createElement("BUTTON");
  70298. this._btnVR.className = "babylonVRicon";
  70299. this._btnVR.id = "babylonVRiconbtn";
  70300. this._btnVR.title = "Click to switch to VR";
  70301. 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) }";
  70302. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  70303. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  70304. // css += ".babylonVRicon.vrdisplaysupported { }";
  70305. // css += ".babylonVRicon.vrdisplayready { }";
  70306. // css += ".babylonVRicon.vrdisplayrequesting { }";
  70307. var style = document.createElement('style');
  70308. style.appendChild(document.createTextNode(css));
  70309. document.getElementsByTagName('head')[0].appendChild(style);
  70310. if (this._canvas) {
  70311. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70312. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70313. this._btnVR.addEventListener("click", function () {
  70314. _this.enterVR();
  70315. });
  70316. window.addEventListener("resize", function () {
  70317. if (_this._canvas) {
  70318. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  70319. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  70320. }
  70321. if (_this._fullscreenVRpresenting && _this._webVRready) {
  70322. _this.exitVR();
  70323. }
  70324. });
  70325. }
  70326. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70327. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70328. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70329. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70330. document.body.appendChild(this._btnVR);
  70331. // Exiting VR mode using 'ESC' key on desktop
  70332. this._onKeyDown = function (event) {
  70333. if (event.keyCode === 27 && _this.isInVRMode()) {
  70334. _this.exitVR();
  70335. }
  70336. };
  70337. document.addEventListener("keydown", this._onKeyDown);
  70338. // Exiting VR mode double tapping the touch screen
  70339. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  70340. if (_this.isInVRMode()) {
  70341. _this.exitVR();
  70342. if (_this._fullscreenVRpresenting) {
  70343. _this._scene.getEngine().switchFullscreen(true);
  70344. }
  70345. }
  70346. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  70347. // Listen for WebVR display changes
  70348. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  70349. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  70350. this._onVRRequestPresentStart = function () {
  70351. _this._webVRrequesting = true;
  70352. _this.updateButtonVisibility();
  70353. };
  70354. this._onVRRequestPresentComplete = function (success) {
  70355. _this._webVRrequesting = false;
  70356. _this.updateButtonVisibility();
  70357. };
  70358. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  70359. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  70360. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  70361. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70362. // Create the cameras
  70363. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  70364. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  70365. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  70366. this.updateButtonVisibility();
  70367. }
  70368. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  70369. if (this.onControllerMeshLoaded) {
  70370. this.onControllerMeshLoaded(webVRController);
  70371. }
  70372. };
  70373. VRExperienceHelper.prototype._onFullscreenChange = function () {
  70374. if (document.fullscreen !== undefined) {
  70375. this._fullscreenVRpresenting = document.fullscreen;
  70376. }
  70377. else if (document.mozFullScreen !== undefined) {
  70378. this._fullscreenVRpresenting = document.mozFullScreen;
  70379. }
  70380. else if (document.webkitIsFullScreen !== undefined) {
  70381. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  70382. }
  70383. else if (document.msIsFullScreen !== undefined) {
  70384. this._fullscreenVRpresenting = document.msIsFullScreen;
  70385. }
  70386. if (!this._fullscreenVRpresenting && this._canvas) {
  70387. this.exitVR();
  70388. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70389. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70390. }
  70391. };
  70392. VRExperienceHelper.prototype.isInVRMode = function () {
  70393. return this._webVRpresenting || this._fullscreenVRpresenting;
  70394. };
  70395. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  70396. var vrDisplay = this._scene.getEngine().getVRDevice();
  70397. if (vrDisplay) {
  70398. var wasPresenting = this._webVRpresenting;
  70399. // A VR display is connected
  70400. this._webVRpresenting = vrDisplay.isPresenting;
  70401. if (wasPresenting && !this._webVRpresenting)
  70402. this.exitVR();
  70403. }
  70404. else {
  70405. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  70406. }
  70407. this.updateButtonVisibility();
  70408. };
  70409. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  70410. this._webVRsupported = eventArgs.vrSupported;
  70411. this._webVRready = !!eventArgs.vrDisplay;
  70412. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  70413. this.updateButtonVisibility();
  70414. };
  70415. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  70416. if (!this._btnVR) {
  70417. return;
  70418. }
  70419. this._btnVR.className = "babylonVRicon";
  70420. if (this.isInVRMode()) {
  70421. this._btnVR.className += " vrdisplaypresenting";
  70422. }
  70423. else {
  70424. if (this._webVRready)
  70425. this._btnVR.className += " vrdisplayready";
  70426. if (this._webVRsupported)
  70427. this._btnVR.className += " vrdisplaysupported";
  70428. if (this._webVRrequesting)
  70429. this._btnVR.className += " vrdisplayrequesting";
  70430. }
  70431. };
  70432. /**
  70433. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  70434. * Otherwise, will use the fullscreen API.
  70435. */
  70436. VRExperienceHelper.prototype.enterVR = function () {
  70437. if (this.onEnteringVR) {
  70438. this.onEnteringVR();
  70439. }
  70440. if (this._webVRrequesting)
  70441. return;
  70442. // If WebVR is supported and a headset is connected
  70443. if (this._webVRready) {
  70444. if (!this._webVRpresenting) {
  70445. this._webVRCamera.position = this._position;
  70446. this._scene.activeCamera = this._webVRCamera;
  70447. }
  70448. }
  70449. else {
  70450. this._vrDeviceOrientationCamera.position = this._position;
  70451. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  70452. this._scene.getEngine().switchFullscreen(true);
  70453. this.updateButtonVisibility();
  70454. }
  70455. if (this._scene.activeCamera && this._canvas) {
  70456. this._scene.activeCamera.attachControl(this._canvas);
  70457. }
  70458. };
  70459. /**
  70460. * Attempt to exit VR, or fullscreen.
  70461. */
  70462. VRExperienceHelper.prototype.exitVR = function () {
  70463. if (this.onExitingVR) {
  70464. this.onExitingVR();
  70465. }
  70466. if (this._webVRpresenting) {
  70467. this._scene.getEngine().disableVR();
  70468. }
  70469. if (this._scene.activeCamera) {
  70470. this._position = this._scene.activeCamera.position;
  70471. }
  70472. this._deviceOrientationCamera.position = this._position;
  70473. this._scene.activeCamera = this._deviceOrientationCamera;
  70474. if (this._canvas) {
  70475. this._scene.activeCamera.attachControl(this._canvas);
  70476. }
  70477. this.updateButtonVisibility();
  70478. };
  70479. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  70480. get: function () {
  70481. return this._position;
  70482. },
  70483. set: function (value) {
  70484. this._position = value;
  70485. if (this._scene.activeCamera) {
  70486. this._scene.activeCamera.position = value;
  70487. }
  70488. },
  70489. enumerable: true,
  70490. configurable: true
  70491. });
  70492. VRExperienceHelper.prototype.dispose = function () {
  70493. if (this.isInVRMode()) {
  70494. this.exitVR();
  70495. }
  70496. this._deviceOrientationCamera.dispose();
  70497. if (this._webVRCamera) {
  70498. this._webVRCamera.dispose();
  70499. }
  70500. if (this._vrDeviceOrientationCamera) {
  70501. this._vrDeviceOrientationCamera.dispose();
  70502. }
  70503. document.body.removeChild(this._btnVR);
  70504. document.removeEventListener("keydown", this._onKeyDown);
  70505. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70506. };
  70507. VRExperienceHelper.prototype.getClassName = function () {
  70508. return "VRExperienceHelper";
  70509. };
  70510. return VRExperienceHelper;
  70511. }());
  70512. BABYLON.VRExperienceHelper = VRExperienceHelper;
  70513. })(BABYLON || (BABYLON = {}));
  70514. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  70515. // Mainly based on these 2 articles :
  70516. // 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
  70517. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  70518. var BABYLON;
  70519. (function (BABYLON) {
  70520. var JoystickAxis;
  70521. (function (JoystickAxis) {
  70522. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  70523. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  70524. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  70525. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  70526. var VirtualJoystick = /** @class */ (function () {
  70527. function VirtualJoystick(leftJoystick) {
  70528. var _this = this;
  70529. if (leftJoystick) {
  70530. this._leftJoystick = true;
  70531. }
  70532. else {
  70533. this._leftJoystick = false;
  70534. }
  70535. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  70536. VirtualJoystick._globalJoystickIndex++;
  70537. // By default left & right arrow keys are moving the X
  70538. // and up & down keys are moving the Y
  70539. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70540. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70541. this.reverseLeftRight = false;
  70542. this.reverseUpDown = false;
  70543. // collections of pointers
  70544. this._touches = new BABYLON.StringDictionary();
  70545. this.deltaPosition = BABYLON.Vector3.Zero();
  70546. this._joystickSensibility = 25;
  70547. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70548. this._rotationSpeed = 25;
  70549. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  70550. this._rotateOnAxisRelativeToMesh = false;
  70551. this._onResize = function (evt) {
  70552. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70553. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70554. if (VirtualJoystick.vjCanvas) {
  70555. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  70556. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  70557. }
  70558. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  70559. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  70560. };
  70561. // injecting a canvas element on top of the canvas 3D game
  70562. if (!VirtualJoystick.vjCanvas) {
  70563. window.addEventListener("resize", this._onResize, false);
  70564. VirtualJoystick.vjCanvas = document.createElement("canvas");
  70565. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70566. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70567. VirtualJoystick.vjCanvas.width = window.innerWidth;
  70568. VirtualJoystick.vjCanvas.height = window.innerHeight;
  70569. VirtualJoystick.vjCanvas.style.width = "100%";
  70570. VirtualJoystick.vjCanvas.style.height = "100%";
  70571. VirtualJoystick.vjCanvas.style.position = "absolute";
  70572. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  70573. VirtualJoystick.vjCanvas.style.top = "0px";
  70574. VirtualJoystick.vjCanvas.style.left = "0px";
  70575. VirtualJoystick.vjCanvas.style.zIndex = "5";
  70576. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  70577. // Support for jQuery PEP polyfill
  70578. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  70579. var context = VirtualJoystick.vjCanvas.getContext('2d');
  70580. if (!context) {
  70581. throw new Error("Unable to create canvas for virtual joystick");
  70582. }
  70583. VirtualJoystick.vjCanvasContext = context;
  70584. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  70585. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70586. document.body.appendChild(VirtualJoystick.vjCanvas);
  70587. }
  70588. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  70589. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  70590. this.pressed = false;
  70591. // default joystick color
  70592. this._joystickColor = "cyan";
  70593. this._joystickPointerID = -1;
  70594. // current joystick position
  70595. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  70596. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  70597. // origin joystick position
  70598. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  70599. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  70600. this._onPointerDownHandlerRef = function (evt) {
  70601. _this._onPointerDown(evt);
  70602. };
  70603. this._onPointerMoveHandlerRef = function (evt) {
  70604. _this._onPointerMove(evt);
  70605. };
  70606. this._onPointerOutHandlerRef = function (evt) {
  70607. _this._onPointerUp(evt);
  70608. };
  70609. this._onPointerUpHandlerRef = function (evt) {
  70610. _this._onPointerUp(evt);
  70611. };
  70612. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  70613. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  70614. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  70615. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  70616. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  70617. evt.preventDefault(); // Disables system menu
  70618. }, false);
  70619. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70620. }
  70621. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  70622. this._joystickSensibility = newJoystickSensibility;
  70623. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70624. };
  70625. VirtualJoystick.prototype._onPointerDown = function (e) {
  70626. var positionOnScreenCondition;
  70627. e.preventDefault();
  70628. if (this._leftJoystick === true) {
  70629. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  70630. }
  70631. else {
  70632. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  70633. }
  70634. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  70635. // First contact will be dedicated to the virtual joystick
  70636. this._joystickPointerID = e.pointerId;
  70637. this._joystickPointerStartPos.x = e.clientX;
  70638. this._joystickPointerStartPos.y = e.clientY;
  70639. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  70640. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  70641. this._deltaJoystickVector.x = 0;
  70642. this._deltaJoystickVector.y = 0;
  70643. this.pressed = true;
  70644. this._touches.add(e.pointerId.toString(), e);
  70645. }
  70646. else {
  70647. // You can only trigger the action buttons with a joystick declared
  70648. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  70649. this._action();
  70650. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  70651. }
  70652. }
  70653. };
  70654. VirtualJoystick.prototype._onPointerMove = function (e) {
  70655. // If the current pointer is the one associated to the joystick (first touch contact)
  70656. if (this._joystickPointerID == e.pointerId) {
  70657. this._joystickPointerPos.x = e.clientX;
  70658. this._joystickPointerPos.y = e.clientY;
  70659. this._deltaJoystickVector = this._joystickPointerPos.clone();
  70660. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  70661. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  70662. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  70663. switch (this._axisTargetedByLeftAndRight) {
  70664. case JoystickAxis.X:
  70665. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  70666. break;
  70667. case JoystickAxis.Y:
  70668. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  70669. break;
  70670. case JoystickAxis.Z:
  70671. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  70672. break;
  70673. }
  70674. var directionUpDown = this.reverseUpDown ? 1 : -1;
  70675. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  70676. switch (this._axisTargetedByUpAndDown) {
  70677. case JoystickAxis.X:
  70678. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  70679. break;
  70680. case JoystickAxis.Y:
  70681. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  70682. break;
  70683. case JoystickAxis.Z:
  70684. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  70685. break;
  70686. }
  70687. }
  70688. else {
  70689. var data = this._touches.get(e.pointerId.toString());
  70690. if (data) {
  70691. data.x = e.clientX;
  70692. data.y = e.clientY;
  70693. }
  70694. }
  70695. };
  70696. VirtualJoystick.prototype._onPointerUp = function (e) {
  70697. if (this._joystickPointerID == e.pointerId) {
  70698. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  70699. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  70700. this._joystickPointerID = -1;
  70701. this.pressed = false;
  70702. }
  70703. else {
  70704. var touch = this._touches.get(e.pointerId.toString());
  70705. if (touch) {
  70706. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70707. }
  70708. }
  70709. this._deltaJoystickVector.x = 0;
  70710. this._deltaJoystickVector.y = 0;
  70711. this._touches.remove(e.pointerId.toString());
  70712. };
  70713. /**
  70714. * Change the color of the virtual joystick
  70715. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  70716. */
  70717. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  70718. this._joystickColor = newColor;
  70719. };
  70720. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  70721. this._action = action;
  70722. };
  70723. // Define which axis you'd like to control for left & right
  70724. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  70725. switch (axis) {
  70726. case JoystickAxis.X:
  70727. case JoystickAxis.Y:
  70728. case JoystickAxis.Z:
  70729. this._axisTargetedByLeftAndRight = axis;
  70730. break;
  70731. default:
  70732. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70733. break;
  70734. }
  70735. };
  70736. // Define which axis you'd like to control for up & down
  70737. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  70738. switch (axis) {
  70739. case JoystickAxis.X:
  70740. case JoystickAxis.Y:
  70741. case JoystickAxis.Z:
  70742. this._axisTargetedByUpAndDown = axis;
  70743. break;
  70744. default:
  70745. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70746. break;
  70747. }
  70748. };
  70749. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  70750. var _this = this;
  70751. if (this.pressed) {
  70752. this._touches.forEach(function (key, touch) {
  70753. if (touch.pointerId === _this._joystickPointerID) {
  70754. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  70755. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  70756. VirtualJoystick.vjCanvasContext.beginPath();
  70757. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70758. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70759. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  70760. VirtualJoystick.vjCanvasContext.stroke();
  70761. VirtualJoystick.vjCanvasContext.closePath();
  70762. VirtualJoystick.vjCanvasContext.beginPath();
  70763. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70764. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70765. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  70766. VirtualJoystick.vjCanvasContext.stroke();
  70767. VirtualJoystick.vjCanvasContext.closePath();
  70768. VirtualJoystick.vjCanvasContext.beginPath();
  70769. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70770. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  70771. VirtualJoystick.vjCanvasContext.stroke();
  70772. VirtualJoystick.vjCanvasContext.closePath();
  70773. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  70774. }
  70775. else {
  70776. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70777. VirtualJoystick.vjCanvasContext.beginPath();
  70778. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  70779. VirtualJoystick.vjCanvasContext.beginPath();
  70780. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  70781. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70782. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  70783. VirtualJoystick.vjCanvasContext.stroke();
  70784. VirtualJoystick.vjCanvasContext.closePath();
  70785. touch.prevX = touch.x;
  70786. touch.prevY = touch.y;
  70787. }
  70788. ;
  70789. });
  70790. }
  70791. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70792. };
  70793. VirtualJoystick.prototype.releaseCanvas = function () {
  70794. if (VirtualJoystick.vjCanvas) {
  70795. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  70796. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  70797. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  70798. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  70799. window.removeEventListener("resize", this._onResize);
  70800. document.body.removeChild(VirtualJoystick.vjCanvas);
  70801. VirtualJoystick.vjCanvas = null;
  70802. }
  70803. };
  70804. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  70805. VirtualJoystick._globalJoystickIndex = 0;
  70806. return VirtualJoystick;
  70807. }());
  70808. BABYLON.VirtualJoystick = VirtualJoystick;
  70809. })(BABYLON || (BABYLON = {}));
  70810. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70811. var BABYLON;
  70812. (function (BABYLON) {
  70813. // We're mainly based on the logic defined into the FreeCamera code
  70814. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70815. __extends(VirtualJoysticksCamera, _super);
  70816. function VirtualJoysticksCamera(name, position, scene) {
  70817. var _this = _super.call(this, name, position, scene) || this;
  70818. _this.inputs.addVirtualJoystick();
  70819. return _this;
  70820. }
  70821. VirtualJoysticksCamera.prototype.getClassName = function () {
  70822. return "VirtualJoysticksCamera";
  70823. };
  70824. return VirtualJoysticksCamera;
  70825. }(BABYLON.FreeCamera));
  70826. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70827. })(BABYLON || (BABYLON = {}));
  70828. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70829. var BABYLON;
  70830. (function (BABYLON) {
  70831. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70832. function FreeCameraVirtualJoystickInput() {
  70833. }
  70834. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70835. return this._leftjoystick;
  70836. };
  70837. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70838. return this._rightjoystick;
  70839. };
  70840. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70841. if (this._leftjoystick) {
  70842. var camera = this.camera;
  70843. var speed = camera._computeLocalCameraSpeed() * 50;
  70844. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70845. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70846. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70847. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70848. if (!this._leftjoystick.pressed) {
  70849. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70850. }
  70851. if (!this._rightjoystick.pressed) {
  70852. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70853. }
  70854. }
  70855. };
  70856. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70857. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70858. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70859. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70860. this._leftjoystick.setJoystickSensibility(0.15);
  70861. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70862. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70863. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70864. this._rightjoystick.reverseUpDown = true;
  70865. this._rightjoystick.setJoystickSensibility(0.05);
  70866. this._rightjoystick.setJoystickColor("yellow");
  70867. };
  70868. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70869. this._leftjoystick.releaseCanvas();
  70870. this._rightjoystick.releaseCanvas();
  70871. };
  70872. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70873. return "FreeCameraVirtualJoystickInput";
  70874. };
  70875. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70876. return "virtualJoystick";
  70877. };
  70878. return FreeCameraVirtualJoystickInput;
  70879. }());
  70880. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70881. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70882. })(BABYLON || (BABYLON = {}));
  70883. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70884. var BABYLON;
  70885. (function (BABYLON) {
  70886. var SimplificationSettings = /** @class */ (function () {
  70887. function SimplificationSettings(quality, distance, optimizeMesh) {
  70888. this.quality = quality;
  70889. this.distance = distance;
  70890. this.optimizeMesh = optimizeMesh;
  70891. }
  70892. return SimplificationSettings;
  70893. }());
  70894. BABYLON.SimplificationSettings = SimplificationSettings;
  70895. var SimplificationQueue = /** @class */ (function () {
  70896. function SimplificationQueue() {
  70897. this.running = false;
  70898. this._simplificationArray = [];
  70899. }
  70900. SimplificationQueue.prototype.addTask = function (task) {
  70901. this._simplificationArray.push(task);
  70902. };
  70903. SimplificationQueue.prototype.executeNext = function () {
  70904. var task = this._simplificationArray.pop();
  70905. if (task) {
  70906. this.running = true;
  70907. this.runSimplification(task);
  70908. }
  70909. else {
  70910. this.running = false;
  70911. }
  70912. };
  70913. SimplificationQueue.prototype.runSimplification = function (task) {
  70914. var _this = this;
  70915. if (task.parallelProcessing) {
  70916. //parallel simplifier
  70917. task.settings.forEach(function (setting) {
  70918. var simplifier = _this.getSimplifier(task);
  70919. simplifier.simplify(setting, function (newMesh) {
  70920. task.mesh.addLODLevel(setting.distance, newMesh);
  70921. newMesh.isVisible = true;
  70922. //check if it is the last
  70923. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70924. //all done, run the success callback.
  70925. task.successCallback();
  70926. }
  70927. _this.executeNext();
  70928. });
  70929. });
  70930. }
  70931. else {
  70932. //single simplifier.
  70933. var simplifier = this.getSimplifier(task);
  70934. var runDecimation = function (setting, callback) {
  70935. simplifier.simplify(setting, function (newMesh) {
  70936. task.mesh.addLODLevel(setting.distance, newMesh);
  70937. newMesh.isVisible = true;
  70938. //run the next quality level
  70939. callback();
  70940. });
  70941. };
  70942. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70943. runDecimation(task.settings[loop.index], function () {
  70944. loop.executeNext();
  70945. });
  70946. }, function () {
  70947. //execution ended, run the success callback.
  70948. if (task.successCallback) {
  70949. task.successCallback();
  70950. }
  70951. _this.executeNext();
  70952. });
  70953. }
  70954. };
  70955. SimplificationQueue.prototype.getSimplifier = function (task) {
  70956. switch (task.simplificationType) {
  70957. case SimplificationType.QUADRATIC:
  70958. default:
  70959. return new QuadraticErrorSimplification(task.mesh);
  70960. }
  70961. };
  70962. return SimplificationQueue;
  70963. }());
  70964. BABYLON.SimplificationQueue = SimplificationQueue;
  70965. /**
  70966. * The implemented types of simplification.
  70967. * At the moment only Quadratic Error Decimation is implemented.
  70968. */
  70969. var SimplificationType;
  70970. (function (SimplificationType) {
  70971. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70972. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70973. var DecimationTriangle = /** @class */ (function () {
  70974. function DecimationTriangle(vertices) {
  70975. this.vertices = vertices;
  70976. this.error = new Array(4);
  70977. this.deleted = false;
  70978. this.isDirty = false;
  70979. this.deletePending = false;
  70980. this.borderFactor = 0;
  70981. }
  70982. return DecimationTriangle;
  70983. }());
  70984. BABYLON.DecimationTriangle = DecimationTriangle;
  70985. var DecimationVertex = /** @class */ (function () {
  70986. function DecimationVertex(position, id) {
  70987. this.position = position;
  70988. this.id = id;
  70989. this.isBorder = true;
  70990. this.q = new QuadraticMatrix();
  70991. this.triangleCount = 0;
  70992. this.triangleStart = 0;
  70993. this.originalOffsets = [];
  70994. }
  70995. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70996. this.position.copyFrom(newPosition);
  70997. };
  70998. return DecimationVertex;
  70999. }());
  71000. BABYLON.DecimationVertex = DecimationVertex;
  71001. var QuadraticMatrix = /** @class */ (function () {
  71002. function QuadraticMatrix(data) {
  71003. this.data = new Array(10);
  71004. for (var i = 0; i < 10; ++i) {
  71005. if (data && data[i]) {
  71006. this.data[i] = data[i];
  71007. }
  71008. else {
  71009. this.data[i] = 0;
  71010. }
  71011. }
  71012. }
  71013. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  71014. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  71015. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  71016. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  71017. return det;
  71018. };
  71019. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  71020. for (var i = 0; i < 10; ++i) {
  71021. this.data[i] += matrix.data[i];
  71022. }
  71023. };
  71024. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  71025. for (var i = 0; i < 10; ++i) {
  71026. this.data[i] += data[i];
  71027. }
  71028. };
  71029. QuadraticMatrix.prototype.add = function (matrix) {
  71030. var m = new QuadraticMatrix();
  71031. for (var i = 0; i < 10; ++i) {
  71032. m.data[i] = this.data[i] + matrix.data[i];
  71033. }
  71034. return m;
  71035. };
  71036. QuadraticMatrix.FromData = function (a, b, c, d) {
  71037. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  71038. };
  71039. //returning an array to avoid garbage collection
  71040. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  71041. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  71042. };
  71043. return QuadraticMatrix;
  71044. }());
  71045. BABYLON.QuadraticMatrix = QuadraticMatrix;
  71046. var Reference = /** @class */ (function () {
  71047. function Reference(vertexId, triangleId) {
  71048. this.vertexId = vertexId;
  71049. this.triangleId = triangleId;
  71050. }
  71051. return Reference;
  71052. }());
  71053. BABYLON.Reference = Reference;
  71054. /**
  71055. * An implementation of the Quadratic Error simplification algorithm.
  71056. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  71057. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  71058. * @author RaananW
  71059. */
  71060. var QuadraticErrorSimplification = /** @class */ (function () {
  71061. function QuadraticErrorSimplification(_mesh) {
  71062. this._mesh = _mesh;
  71063. this.initialized = false;
  71064. this.syncIterations = 5000;
  71065. this.aggressiveness = 7;
  71066. this.decimationIterations = 100;
  71067. this.boundingBoxEpsilon = BABYLON.Epsilon;
  71068. }
  71069. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  71070. var _this = this;
  71071. this.initDecimatedMesh();
  71072. //iterating through the submeshes array, one after the other.
  71073. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  71074. _this.initWithMesh(loop.index, function () {
  71075. _this.runDecimation(settings, loop.index, function () {
  71076. loop.executeNext();
  71077. });
  71078. }, settings.optimizeMesh);
  71079. }, function () {
  71080. setTimeout(function () {
  71081. successCallback(_this._reconstructedMesh);
  71082. }, 0);
  71083. });
  71084. };
  71085. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  71086. var _this = this;
  71087. var targetCount = ~~(this.triangles.length * settings.quality);
  71088. var deletedTriangles = 0;
  71089. var triangleCount = this.triangles.length;
  71090. var iterationFunction = function (iteration, callback) {
  71091. setTimeout(function () {
  71092. if (iteration % 5 === 0) {
  71093. _this.updateMesh(iteration === 0);
  71094. }
  71095. for (var i = 0; i < _this.triangles.length; ++i) {
  71096. _this.triangles[i].isDirty = false;
  71097. }
  71098. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  71099. var trianglesIterator = function (i) {
  71100. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  71101. var t = _this.triangles[tIdx];
  71102. if (!t)
  71103. return;
  71104. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  71105. return;
  71106. }
  71107. for (var j = 0; j < 3; ++j) {
  71108. if (t.error[j] < threshold) {
  71109. var deleted0 = [];
  71110. var deleted1 = [];
  71111. var v0 = t.vertices[j];
  71112. var v1 = t.vertices[(j + 1) % 3];
  71113. if (v0.isBorder || v1.isBorder)
  71114. continue;
  71115. var p = BABYLON.Vector3.Zero();
  71116. var n = BABYLON.Vector3.Zero();
  71117. var uv = BABYLON.Vector2.Zero();
  71118. var color = new BABYLON.Color4(0, 0, 0, 1);
  71119. _this.calculateError(v0, v1, p, n, uv, color);
  71120. var delTr = new Array();
  71121. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  71122. continue;
  71123. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  71124. continue;
  71125. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  71126. continue;
  71127. var uniqueArray = new Array();
  71128. delTr.forEach(function (deletedT) {
  71129. if (uniqueArray.indexOf(deletedT) === -1) {
  71130. deletedT.deletePending = true;
  71131. uniqueArray.push(deletedT);
  71132. }
  71133. });
  71134. if (uniqueArray.length % 2 !== 0) {
  71135. continue;
  71136. }
  71137. v0.q = v1.q.add(v0.q);
  71138. v0.updatePosition(p);
  71139. var tStart = _this.references.length;
  71140. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  71141. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  71142. var tCount = _this.references.length - tStart;
  71143. if (tCount <= v0.triangleCount) {
  71144. if (tCount) {
  71145. for (var c = 0; c < tCount; c++) {
  71146. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  71147. }
  71148. }
  71149. }
  71150. else {
  71151. v0.triangleStart = tStart;
  71152. }
  71153. v0.triangleCount = tCount;
  71154. break;
  71155. }
  71156. }
  71157. };
  71158. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  71159. }, 0);
  71160. };
  71161. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  71162. if (triangleCount - deletedTriangles <= targetCount)
  71163. loop.breakLoop();
  71164. else {
  71165. iterationFunction(loop.index, function () {
  71166. loop.executeNext();
  71167. });
  71168. }
  71169. }, function () {
  71170. setTimeout(function () {
  71171. //reconstruct this part of the mesh
  71172. _this.reconstructMesh(submeshIndex);
  71173. successCallback();
  71174. }, 0);
  71175. });
  71176. };
  71177. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  71178. var _this = this;
  71179. this.vertices = [];
  71180. this.triangles = [];
  71181. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71182. var indices = this._mesh.getIndices();
  71183. var submesh = this._mesh.subMeshes[submeshIndex];
  71184. var findInVertices = function (positionToSearch) {
  71185. if (optimizeMesh) {
  71186. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  71187. if (_this.vertices[ii].position.equals(positionToSearch)) {
  71188. return _this.vertices[ii];
  71189. }
  71190. }
  71191. }
  71192. return null;
  71193. };
  71194. var vertexReferences = [];
  71195. var vertexInit = function (i) {
  71196. if (!positionData) {
  71197. return;
  71198. }
  71199. var offset = i + submesh.verticesStart;
  71200. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  71201. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  71202. vertex.originalOffsets.push(offset);
  71203. if (vertex.id === _this.vertices.length) {
  71204. _this.vertices.push(vertex);
  71205. }
  71206. vertexReferences.push(vertex.id);
  71207. };
  71208. //var totalVertices = mesh.getTotalVertices();
  71209. var totalVertices = submesh.verticesCount;
  71210. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  71211. var indicesInit = function (i) {
  71212. if (!indices) {
  71213. return;
  71214. }
  71215. var offset = (submesh.indexStart / 3) + i;
  71216. var pos = (offset * 3);
  71217. var i0 = indices[pos + 0];
  71218. var i1 = indices[pos + 1];
  71219. var i2 = indices[pos + 2];
  71220. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  71221. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  71222. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  71223. var triangle = new DecimationTriangle([v0, v1, v2]);
  71224. triangle.originalOffset = pos;
  71225. _this.triangles.push(triangle);
  71226. };
  71227. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  71228. _this.init(callback);
  71229. });
  71230. });
  71231. };
  71232. QuadraticErrorSimplification.prototype.init = function (callback) {
  71233. var _this = this;
  71234. var triangleInit1 = function (i) {
  71235. var t = _this.triangles[i];
  71236. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  71237. for (var j = 0; j < 3; j++) {
  71238. 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))));
  71239. }
  71240. };
  71241. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  71242. var triangleInit2 = function (i) {
  71243. var t = _this.triangles[i];
  71244. for (var j = 0; j < 3; ++j) {
  71245. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  71246. }
  71247. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  71248. };
  71249. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  71250. _this.initialized = true;
  71251. callback();
  71252. });
  71253. });
  71254. };
  71255. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  71256. var newTriangles = [];
  71257. var i;
  71258. for (i = 0; i < this.vertices.length; ++i) {
  71259. this.vertices[i].triangleCount = 0;
  71260. }
  71261. var t;
  71262. var j;
  71263. for (i = 0; i < this.triangles.length; ++i) {
  71264. if (!this.triangles[i].deleted) {
  71265. t = this.triangles[i];
  71266. for (j = 0; j < 3; ++j) {
  71267. t.vertices[j].triangleCount = 1;
  71268. }
  71269. newTriangles.push(t);
  71270. }
  71271. }
  71272. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  71273. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  71274. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  71275. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  71276. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  71277. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  71278. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  71279. var vertexCount = 0;
  71280. for (i = 0; i < this.vertices.length; ++i) {
  71281. var vertex = this.vertices[i];
  71282. vertex.id = vertexCount;
  71283. if (vertex.triangleCount) {
  71284. vertex.originalOffsets.forEach(function (originalOffset) {
  71285. if (!normalData) {
  71286. return;
  71287. }
  71288. newPositionData.push(vertex.position.x);
  71289. newPositionData.push(vertex.position.y);
  71290. newPositionData.push(vertex.position.z);
  71291. newNormalData.push(normalData[originalOffset * 3]);
  71292. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  71293. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  71294. if (uvs && uvs.length) {
  71295. newUVsData.push(uvs[(originalOffset * 2)]);
  71296. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  71297. }
  71298. else if (colorsData && colorsData.length) {
  71299. newColorsData.push(colorsData[(originalOffset * 4)]);
  71300. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  71301. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  71302. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  71303. }
  71304. ++vertexCount;
  71305. });
  71306. }
  71307. }
  71308. var startingIndex = this._reconstructedMesh.getTotalIndices();
  71309. var startingVertex = this._reconstructedMesh.getTotalVertices();
  71310. var submeshesArray = this._reconstructedMesh.subMeshes;
  71311. this._reconstructedMesh.subMeshes = [];
  71312. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  71313. var originalIndices = this._mesh.getIndices();
  71314. for (i = 0; i < newTriangles.length; ++i) {
  71315. t = newTriangles[i]; //now get the new referencing point for each vertex
  71316. [0, 1, 2].forEach(function (idx) {
  71317. var id = originalIndices[t.originalOffset + idx];
  71318. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  71319. if (offset < 0)
  71320. offset = 0;
  71321. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  71322. });
  71323. }
  71324. //overwriting the old vertex buffers and indices.
  71325. this._reconstructedMesh.setIndices(newIndicesArray);
  71326. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  71327. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  71328. if (newUVsData.length > 0)
  71329. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  71330. if (newColorsData.length > 0)
  71331. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  71332. //create submesh
  71333. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  71334. if (submeshIndex > 0) {
  71335. this._reconstructedMesh.subMeshes = [];
  71336. submeshesArray.forEach(function (submesh) {
  71337. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  71338. });
  71339. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  71340. }
  71341. };
  71342. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  71343. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  71344. this._reconstructedMesh.material = this._mesh.material;
  71345. this._reconstructedMesh.parent = this._mesh.parent;
  71346. this._reconstructedMesh.isVisible = false;
  71347. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  71348. };
  71349. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  71350. for (var i = 0; i < vertex1.triangleCount; ++i) {
  71351. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  71352. if (t.deleted)
  71353. continue;
  71354. var s = this.references[vertex1.triangleStart + i].vertexId;
  71355. var v1 = t.vertices[(s + 1) % 3];
  71356. var v2 = t.vertices[(s + 2) % 3];
  71357. if ((v1 === vertex2 || v2 === vertex2)) {
  71358. deletedArray[i] = true;
  71359. delTr.push(t);
  71360. continue;
  71361. }
  71362. var d1 = v1.position.subtract(point);
  71363. d1 = d1.normalize();
  71364. var d2 = v2.position.subtract(point);
  71365. d2 = d2.normalize();
  71366. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  71367. return true;
  71368. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  71369. deletedArray[i] = false;
  71370. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  71371. return true;
  71372. }
  71373. return false;
  71374. };
  71375. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  71376. var newDeleted = deletedTriangles;
  71377. for (var i = 0; i < vertex.triangleCount; ++i) {
  71378. var ref = this.references[vertex.triangleStart + i];
  71379. var t = this.triangles[ref.triangleId];
  71380. if (t.deleted)
  71381. continue;
  71382. if (deletedArray[i] && t.deletePending) {
  71383. t.deleted = true;
  71384. newDeleted++;
  71385. continue;
  71386. }
  71387. t.vertices[ref.vertexId] = origVertex;
  71388. t.isDirty = true;
  71389. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  71390. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  71391. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  71392. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  71393. this.references.push(ref);
  71394. }
  71395. return newDeleted;
  71396. };
  71397. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  71398. for (var i = 0; i < this.vertices.length; ++i) {
  71399. var vCount = [];
  71400. var vId = [];
  71401. var v = this.vertices[i];
  71402. var j;
  71403. for (j = 0; j < v.triangleCount; ++j) {
  71404. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  71405. for (var ii = 0; ii < 3; ii++) {
  71406. var ofs = 0;
  71407. var vv = triangle.vertices[ii];
  71408. while (ofs < vCount.length) {
  71409. if (vId[ofs] === vv.id)
  71410. break;
  71411. ++ofs;
  71412. }
  71413. if (ofs === vCount.length) {
  71414. vCount.push(1);
  71415. vId.push(vv.id);
  71416. }
  71417. else {
  71418. vCount[ofs]++;
  71419. }
  71420. }
  71421. }
  71422. for (j = 0; j < vCount.length; ++j) {
  71423. if (vCount[j] === 1) {
  71424. this.vertices[vId[j]].isBorder = true;
  71425. }
  71426. else {
  71427. this.vertices[vId[j]].isBorder = false;
  71428. }
  71429. }
  71430. }
  71431. };
  71432. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  71433. if (identifyBorders === void 0) { identifyBorders = false; }
  71434. var i;
  71435. if (!identifyBorders) {
  71436. var newTrianglesVector = [];
  71437. for (i = 0; i < this.triangles.length; ++i) {
  71438. if (!this.triangles[i].deleted) {
  71439. newTrianglesVector.push(this.triangles[i]);
  71440. }
  71441. }
  71442. this.triangles = newTrianglesVector;
  71443. }
  71444. for (i = 0; i < this.vertices.length; ++i) {
  71445. this.vertices[i].triangleCount = 0;
  71446. this.vertices[i].triangleStart = 0;
  71447. }
  71448. var t;
  71449. var j;
  71450. var v;
  71451. for (i = 0; i < this.triangles.length; ++i) {
  71452. t = this.triangles[i];
  71453. for (j = 0; j < 3; ++j) {
  71454. v = t.vertices[j];
  71455. v.triangleCount++;
  71456. }
  71457. }
  71458. var tStart = 0;
  71459. for (i = 0; i < this.vertices.length; ++i) {
  71460. this.vertices[i].triangleStart = tStart;
  71461. tStart += this.vertices[i].triangleCount;
  71462. this.vertices[i].triangleCount = 0;
  71463. }
  71464. var newReferences = new Array(this.triangles.length * 3);
  71465. for (i = 0; i < this.triangles.length; ++i) {
  71466. t = this.triangles[i];
  71467. for (j = 0; j < 3; ++j) {
  71468. v = t.vertices[j];
  71469. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  71470. v.triangleCount++;
  71471. }
  71472. }
  71473. this.references = newReferences;
  71474. if (identifyBorders) {
  71475. this.identifyBorder();
  71476. }
  71477. };
  71478. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  71479. var x = point.x;
  71480. var y = point.y;
  71481. var z = point.z;
  71482. 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
  71483. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  71484. };
  71485. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  71486. var q = vertex1.q.add(vertex2.q);
  71487. var border = vertex1.isBorder && vertex2.isBorder;
  71488. var error = 0;
  71489. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  71490. if (qDet !== 0 && !border) {
  71491. if (!pointResult) {
  71492. pointResult = BABYLON.Vector3.Zero();
  71493. }
  71494. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  71495. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  71496. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  71497. error = this.vertexError(q, pointResult);
  71498. }
  71499. else {
  71500. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  71501. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  71502. var error1 = this.vertexError(q, vertex1.position);
  71503. var error2 = this.vertexError(q, vertex2.position);
  71504. var error3 = this.vertexError(q, p3);
  71505. error = Math.min(error1, error2, error3);
  71506. if (error === error1) {
  71507. if (pointResult) {
  71508. pointResult.copyFrom(vertex1.position);
  71509. }
  71510. }
  71511. else if (error === error2) {
  71512. if (pointResult) {
  71513. pointResult.copyFrom(vertex2.position);
  71514. }
  71515. }
  71516. else {
  71517. if (pointResult) {
  71518. pointResult.copyFrom(p3);
  71519. }
  71520. }
  71521. }
  71522. return error;
  71523. };
  71524. return QuadraticErrorSimplification;
  71525. }());
  71526. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  71527. })(BABYLON || (BABYLON = {}));
  71528. //# sourceMappingURL=babylon.meshSimplification.js.map
  71529. var BABYLON;
  71530. (function (BABYLON) {
  71531. var Internals;
  71532. (function (Internals) {
  71533. var MeshLODLevel = /** @class */ (function () {
  71534. function MeshLODLevel(distance, mesh) {
  71535. this.distance = distance;
  71536. this.mesh = mesh;
  71537. }
  71538. return MeshLODLevel;
  71539. }());
  71540. Internals.MeshLODLevel = MeshLODLevel;
  71541. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  71542. })(BABYLON || (BABYLON = {}));
  71543. //# sourceMappingURL=babylon.meshLODLevel.js.map
  71544. var BABYLON;
  71545. (function (BABYLON) {
  71546. // Standard optimizations
  71547. var SceneOptimization = /** @class */ (function () {
  71548. function SceneOptimization(priority) {
  71549. if (priority === void 0) { priority = 0; }
  71550. this.priority = priority;
  71551. this.apply = function (scene) {
  71552. return true; // Return true if everything that can be done was applied
  71553. };
  71554. }
  71555. return SceneOptimization;
  71556. }());
  71557. BABYLON.SceneOptimization = SceneOptimization;
  71558. var TextureOptimization = /** @class */ (function (_super) {
  71559. __extends(TextureOptimization, _super);
  71560. function TextureOptimization(priority, maximumSize) {
  71561. if (priority === void 0) { priority = 0; }
  71562. if (maximumSize === void 0) { maximumSize = 1024; }
  71563. var _this = _super.call(this, priority) || this;
  71564. _this.priority = priority;
  71565. _this.maximumSize = maximumSize;
  71566. _this.apply = function (scene) {
  71567. var allDone = true;
  71568. for (var index = 0; index < scene.textures.length; index++) {
  71569. var texture = scene.textures[index];
  71570. if (!texture.canRescale || texture.getContext) {
  71571. continue;
  71572. }
  71573. var currentSize = texture.getSize();
  71574. var maxDimension = Math.max(currentSize.width, currentSize.height);
  71575. if (maxDimension > _this.maximumSize) {
  71576. texture.scale(0.5);
  71577. allDone = false;
  71578. }
  71579. }
  71580. return allDone;
  71581. };
  71582. return _this;
  71583. }
  71584. return TextureOptimization;
  71585. }(SceneOptimization));
  71586. BABYLON.TextureOptimization = TextureOptimization;
  71587. var HardwareScalingOptimization = /** @class */ (function (_super) {
  71588. __extends(HardwareScalingOptimization, _super);
  71589. function HardwareScalingOptimization(priority, maximumScale) {
  71590. if (priority === void 0) { priority = 0; }
  71591. if (maximumScale === void 0) { maximumScale = 2; }
  71592. var _this = _super.call(this, priority) || this;
  71593. _this.priority = priority;
  71594. _this.maximumScale = maximumScale;
  71595. _this._currentScale = 1;
  71596. _this.apply = function (scene) {
  71597. _this._currentScale++;
  71598. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  71599. return _this._currentScale >= _this.maximumScale;
  71600. };
  71601. return _this;
  71602. }
  71603. return HardwareScalingOptimization;
  71604. }(SceneOptimization));
  71605. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  71606. var ShadowsOptimization = /** @class */ (function (_super) {
  71607. __extends(ShadowsOptimization, _super);
  71608. function ShadowsOptimization() {
  71609. var _this = _super !== null && _super.apply(this, arguments) || this;
  71610. _this.apply = function (scene) {
  71611. scene.shadowsEnabled = false;
  71612. return true;
  71613. };
  71614. return _this;
  71615. }
  71616. return ShadowsOptimization;
  71617. }(SceneOptimization));
  71618. BABYLON.ShadowsOptimization = ShadowsOptimization;
  71619. var PostProcessesOptimization = /** @class */ (function (_super) {
  71620. __extends(PostProcessesOptimization, _super);
  71621. function PostProcessesOptimization() {
  71622. var _this = _super !== null && _super.apply(this, arguments) || this;
  71623. _this.apply = function (scene) {
  71624. scene.postProcessesEnabled = false;
  71625. return true;
  71626. };
  71627. return _this;
  71628. }
  71629. return PostProcessesOptimization;
  71630. }(SceneOptimization));
  71631. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  71632. var LensFlaresOptimization = /** @class */ (function (_super) {
  71633. __extends(LensFlaresOptimization, _super);
  71634. function LensFlaresOptimization() {
  71635. var _this = _super !== null && _super.apply(this, arguments) || this;
  71636. _this.apply = function (scene) {
  71637. scene.lensFlaresEnabled = false;
  71638. return true;
  71639. };
  71640. return _this;
  71641. }
  71642. return LensFlaresOptimization;
  71643. }(SceneOptimization));
  71644. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  71645. var ParticlesOptimization = /** @class */ (function (_super) {
  71646. __extends(ParticlesOptimization, _super);
  71647. function ParticlesOptimization() {
  71648. var _this = _super !== null && _super.apply(this, arguments) || this;
  71649. _this.apply = function (scene) {
  71650. scene.particlesEnabled = false;
  71651. return true;
  71652. };
  71653. return _this;
  71654. }
  71655. return ParticlesOptimization;
  71656. }(SceneOptimization));
  71657. BABYLON.ParticlesOptimization = ParticlesOptimization;
  71658. var RenderTargetsOptimization = /** @class */ (function (_super) {
  71659. __extends(RenderTargetsOptimization, _super);
  71660. function RenderTargetsOptimization() {
  71661. var _this = _super !== null && _super.apply(this, arguments) || this;
  71662. _this.apply = function (scene) {
  71663. scene.renderTargetsEnabled = false;
  71664. return true;
  71665. };
  71666. return _this;
  71667. }
  71668. return RenderTargetsOptimization;
  71669. }(SceneOptimization));
  71670. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  71671. var MergeMeshesOptimization = /** @class */ (function (_super) {
  71672. __extends(MergeMeshesOptimization, _super);
  71673. function MergeMeshesOptimization() {
  71674. var _this = _super !== null && _super.apply(this, arguments) || this;
  71675. _this._canBeMerged = function (abstractMesh) {
  71676. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  71677. return false;
  71678. }
  71679. var mesh = abstractMesh;
  71680. if (!mesh.isVisible || !mesh.isEnabled()) {
  71681. return false;
  71682. }
  71683. if (mesh.instances.length > 0) {
  71684. return false;
  71685. }
  71686. if (mesh.skeleton || mesh.hasLODLevels) {
  71687. return false;
  71688. }
  71689. if (mesh.parent) {
  71690. return false;
  71691. }
  71692. return true;
  71693. };
  71694. _this.apply = function (scene, updateSelectionTree) {
  71695. var globalPool = scene.meshes.slice(0);
  71696. var globalLength = globalPool.length;
  71697. for (var index = 0; index < globalLength; index++) {
  71698. var currentPool = new Array();
  71699. var current = globalPool[index];
  71700. // Checks
  71701. if (!_this._canBeMerged(current)) {
  71702. continue;
  71703. }
  71704. currentPool.push(current);
  71705. // Find compatible meshes
  71706. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  71707. var otherMesh = globalPool[subIndex];
  71708. if (!_this._canBeMerged(otherMesh)) {
  71709. continue;
  71710. }
  71711. if (otherMesh.material !== current.material) {
  71712. continue;
  71713. }
  71714. if (otherMesh.checkCollisions !== current.checkCollisions) {
  71715. continue;
  71716. }
  71717. currentPool.push(otherMesh);
  71718. globalLength--;
  71719. globalPool.splice(subIndex, 1);
  71720. subIndex--;
  71721. }
  71722. if (currentPool.length < 2) {
  71723. continue;
  71724. }
  71725. // Merge meshes
  71726. BABYLON.Mesh.MergeMeshes(currentPool);
  71727. }
  71728. if (updateSelectionTree != undefined) {
  71729. if (updateSelectionTree) {
  71730. scene.createOrUpdateSelectionOctree();
  71731. }
  71732. }
  71733. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  71734. scene.createOrUpdateSelectionOctree();
  71735. }
  71736. return true;
  71737. };
  71738. return _this;
  71739. }
  71740. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  71741. get: function () {
  71742. return MergeMeshesOptimization._UpdateSelectionTree;
  71743. },
  71744. set: function (value) {
  71745. MergeMeshesOptimization._UpdateSelectionTree = value;
  71746. },
  71747. enumerable: true,
  71748. configurable: true
  71749. });
  71750. MergeMeshesOptimization._UpdateSelectionTree = false;
  71751. return MergeMeshesOptimization;
  71752. }(SceneOptimization));
  71753. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  71754. // Options
  71755. var SceneOptimizerOptions = /** @class */ (function () {
  71756. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  71757. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  71758. if (trackerDuration === void 0) { trackerDuration = 2000; }
  71759. this.targetFrameRate = targetFrameRate;
  71760. this.trackerDuration = trackerDuration;
  71761. this.optimizations = new Array();
  71762. }
  71763. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  71764. var result = new SceneOptimizerOptions(targetFrameRate);
  71765. var priority = 0;
  71766. result.optimizations.push(new MergeMeshesOptimization(priority));
  71767. result.optimizations.push(new ShadowsOptimization(priority));
  71768. result.optimizations.push(new LensFlaresOptimization(priority));
  71769. // Next priority
  71770. priority++;
  71771. result.optimizations.push(new PostProcessesOptimization(priority));
  71772. result.optimizations.push(new ParticlesOptimization(priority));
  71773. // Next priority
  71774. priority++;
  71775. result.optimizations.push(new TextureOptimization(priority, 1024));
  71776. return result;
  71777. };
  71778. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  71779. var result = new SceneOptimizerOptions(targetFrameRate);
  71780. var priority = 0;
  71781. result.optimizations.push(new MergeMeshesOptimization(priority));
  71782. result.optimizations.push(new ShadowsOptimization(priority));
  71783. result.optimizations.push(new LensFlaresOptimization(priority));
  71784. // Next priority
  71785. priority++;
  71786. result.optimizations.push(new PostProcessesOptimization(priority));
  71787. result.optimizations.push(new ParticlesOptimization(priority));
  71788. // Next priority
  71789. priority++;
  71790. result.optimizations.push(new TextureOptimization(priority, 512));
  71791. // Next priority
  71792. priority++;
  71793. result.optimizations.push(new RenderTargetsOptimization(priority));
  71794. // Next priority
  71795. priority++;
  71796. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  71797. return result;
  71798. };
  71799. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  71800. var result = new SceneOptimizerOptions(targetFrameRate);
  71801. var priority = 0;
  71802. result.optimizations.push(new MergeMeshesOptimization(priority));
  71803. result.optimizations.push(new ShadowsOptimization(priority));
  71804. result.optimizations.push(new LensFlaresOptimization(priority));
  71805. // Next priority
  71806. priority++;
  71807. result.optimizations.push(new PostProcessesOptimization(priority));
  71808. result.optimizations.push(new ParticlesOptimization(priority));
  71809. // Next priority
  71810. priority++;
  71811. result.optimizations.push(new TextureOptimization(priority, 256));
  71812. // Next priority
  71813. priority++;
  71814. result.optimizations.push(new RenderTargetsOptimization(priority));
  71815. // Next priority
  71816. priority++;
  71817. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71818. return result;
  71819. };
  71820. return SceneOptimizerOptions;
  71821. }());
  71822. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71823. // Scene optimizer tool
  71824. var SceneOptimizer = /** @class */ (function () {
  71825. function SceneOptimizer() {
  71826. }
  71827. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71828. // TODO: add an epsilon
  71829. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71830. if (onSuccess) {
  71831. onSuccess();
  71832. }
  71833. return;
  71834. }
  71835. // Apply current level of optimizations
  71836. var allDone = true;
  71837. var noOptimizationApplied = true;
  71838. for (var index = 0; index < options.optimizations.length; index++) {
  71839. var optimization = options.optimizations[index];
  71840. if (optimization.priority === currentPriorityLevel) {
  71841. noOptimizationApplied = false;
  71842. allDone = allDone && optimization.apply(scene);
  71843. }
  71844. }
  71845. // If no optimization was applied, this is a failure :(
  71846. if (noOptimizationApplied) {
  71847. if (onFailure) {
  71848. onFailure();
  71849. }
  71850. return;
  71851. }
  71852. // If all optimizations were done, move to next level
  71853. if (allDone) {
  71854. currentPriorityLevel++;
  71855. }
  71856. // Let's the system running for a specific amount of time before checking FPS
  71857. scene.executeWhenReady(function () {
  71858. setTimeout(function () {
  71859. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71860. }, options.trackerDuration);
  71861. });
  71862. };
  71863. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71864. if (!options) {
  71865. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71866. }
  71867. // Let's the system running for a specific amount of time before checking FPS
  71868. scene.executeWhenReady(function () {
  71869. setTimeout(function () {
  71870. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71871. }, options.trackerDuration);
  71872. });
  71873. };
  71874. return SceneOptimizer;
  71875. }());
  71876. BABYLON.SceneOptimizer = SceneOptimizer;
  71877. })(BABYLON || (BABYLON = {}));
  71878. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71879. var BABYLON;
  71880. (function (BABYLON) {
  71881. var OutlineRenderer = /** @class */ (function () {
  71882. function OutlineRenderer(scene) {
  71883. this.zOffset = 1;
  71884. this._scene = scene;
  71885. }
  71886. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71887. var _this = this;
  71888. if (useOverlay === void 0) { useOverlay = false; }
  71889. var scene = this._scene;
  71890. var engine = this._scene.getEngine();
  71891. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71892. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71893. return;
  71894. }
  71895. var mesh = subMesh.getRenderingMesh();
  71896. var material = subMesh.getMaterial();
  71897. if (!material || !scene.activeCamera) {
  71898. return;
  71899. }
  71900. engine.enableEffect(this._effect);
  71901. // Logarithmic depth
  71902. if (material.useLogarithmicDepth) {
  71903. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71904. }
  71905. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71906. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71907. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71908. // Bones
  71909. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71910. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71911. }
  71912. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71913. // Alpha test
  71914. if (material && material.needAlphaTesting()) {
  71915. var alphaTexture = material.getAlphaTestTexture();
  71916. if (alphaTexture) {
  71917. this._effect.setTexture("diffuseSampler", alphaTexture);
  71918. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71919. }
  71920. }
  71921. engine.setZOffset(-this.zOffset);
  71922. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71923. engine.setZOffset(0);
  71924. };
  71925. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71926. var defines = [];
  71927. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71928. var mesh = subMesh.getMesh();
  71929. var material = subMesh.getMaterial();
  71930. if (material) {
  71931. // Alpha test
  71932. if (material.needAlphaTesting()) {
  71933. defines.push("#define ALPHATEST");
  71934. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71935. attribs.push(BABYLON.VertexBuffer.UVKind);
  71936. defines.push("#define UV1");
  71937. }
  71938. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71939. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71940. defines.push("#define UV2");
  71941. }
  71942. }
  71943. //Logarithmic depth
  71944. if (material.useLogarithmicDepth) {
  71945. defines.push("#define LOGARITHMICDEPTH");
  71946. }
  71947. }
  71948. // Bones
  71949. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71950. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71951. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71952. if (mesh.numBoneInfluencers > 4) {
  71953. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71954. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71955. }
  71956. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71957. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71958. }
  71959. else {
  71960. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71961. }
  71962. // Instances
  71963. if (useInstances) {
  71964. defines.push("#define INSTANCES");
  71965. attribs.push("world0");
  71966. attribs.push("world1");
  71967. attribs.push("world2");
  71968. attribs.push("world3");
  71969. }
  71970. // Get correct effect
  71971. var join = defines.join("\n");
  71972. if (this._cachedDefines !== join) {
  71973. this._cachedDefines = join;
  71974. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71975. }
  71976. return this._effect.isReady();
  71977. };
  71978. return OutlineRenderer;
  71979. }());
  71980. BABYLON.OutlineRenderer = OutlineRenderer;
  71981. })(BABYLON || (BABYLON = {}));
  71982. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71983. var BABYLON;
  71984. (function (BABYLON) {
  71985. var FaceAdjacencies = /** @class */ (function () {
  71986. function FaceAdjacencies() {
  71987. this.edges = new Array();
  71988. this.edgesConnectedCount = 0;
  71989. }
  71990. return FaceAdjacencies;
  71991. }());
  71992. var EdgesRenderer = /** @class */ (function () {
  71993. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71994. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71995. if (epsilon === void 0) { epsilon = 0.95; }
  71996. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71997. this.edgesWidthScalerForOrthographic = 1000.0;
  71998. this.edgesWidthScalerForPerspective = 50.0;
  71999. this._linesPositions = new Array();
  72000. this._linesNormals = new Array();
  72001. this._linesIndices = new Array();
  72002. this._buffers = {};
  72003. this._checkVerticesInsteadOfIndices = false;
  72004. this._source = source;
  72005. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  72006. this._epsilon = epsilon;
  72007. this._prepareRessources();
  72008. this._generateEdgesLines();
  72009. }
  72010. EdgesRenderer.prototype._prepareRessources = function () {
  72011. if (this._lineShader) {
  72012. return;
  72013. }
  72014. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  72015. attributes: ["position", "normal"],
  72016. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  72017. });
  72018. this._lineShader.disableDepthWrite = true;
  72019. this._lineShader.backFaceCulling = false;
  72020. };
  72021. EdgesRenderer.prototype._rebuild = function () {
  72022. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  72023. if (buffer) {
  72024. buffer._rebuild();
  72025. }
  72026. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  72027. if (buffer) {
  72028. buffer._rebuild();
  72029. }
  72030. var scene = this._source.getScene();
  72031. var engine = scene.getEngine();
  72032. this._ib = engine.createIndexBuffer(this._linesIndices);
  72033. };
  72034. EdgesRenderer.prototype.dispose = function () {
  72035. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  72036. if (buffer) {
  72037. buffer.dispose();
  72038. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  72039. }
  72040. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  72041. if (buffer) {
  72042. buffer.dispose();
  72043. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  72044. }
  72045. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  72046. this._lineShader.dispose();
  72047. };
  72048. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  72049. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  72050. return 0;
  72051. }
  72052. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  72053. return 1;
  72054. }
  72055. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  72056. return 2;
  72057. }
  72058. return -1;
  72059. };
  72060. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  72061. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  72062. return 0;
  72063. }
  72064. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  72065. return 1;
  72066. }
  72067. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  72068. return 2;
  72069. }
  72070. return -1;
  72071. };
  72072. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  72073. var needToCreateLine;
  72074. if (edge === undefined) {
  72075. needToCreateLine = true;
  72076. }
  72077. else {
  72078. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  72079. needToCreateLine = dotProduct < this._epsilon;
  72080. }
  72081. if (needToCreateLine) {
  72082. var offset = this._linesPositions.length / 3;
  72083. var normal = p0.subtract(p1);
  72084. normal.normalize();
  72085. // Positions
  72086. this._linesPositions.push(p0.x);
  72087. this._linesPositions.push(p0.y);
  72088. this._linesPositions.push(p0.z);
  72089. this._linesPositions.push(p0.x);
  72090. this._linesPositions.push(p0.y);
  72091. this._linesPositions.push(p0.z);
  72092. this._linesPositions.push(p1.x);
  72093. this._linesPositions.push(p1.y);
  72094. this._linesPositions.push(p1.z);
  72095. this._linesPositions.push(p1.x);
  72096. this._linesPositions.push(p1.y);
  72097. this._linesPositions.push(p1.z);
  72098. // Normals
  72099. this._linesNormals.push(p1.x);
  72100. this._linesNormals.push(p1.y);
  72101. this._linesNormals.push(p1.z);
  72102. this._linesNormals.push(-1);
  72103. this._linesNormals.push(p1.x);
  72104. this._linesNormals.push(p1.y);
  72105. this._linesNormals.push(p1.z);
  72106. this._linesNormals.push(1);
  72107. this._linesNormals.push(p0.x);
  72108. this._linesNormals.push(p0.y);
  72109. this._linesNormals.push(p0.z);
  72110. this._linesNormals.push(-1);
  72111. this._linesNormals.push(p0.x);
  72112. this._linesNormals.push(p0.y);
  72113. this._linesNormals.push(p0.z);
  72114. this._linesNormals.push(1);
  72115. // Indices
  72116. this._linesIndices.push(offset);
  72117. this._linesIndices.push(offset + 1);
  72118. this._linesIndices.push(offset + 2);
  72119. this._linesIndices.push(offset);
  72120. this._linesIndices.push(offset + 2);
  72121. this._linesIndices.push(offset + 3);
  72122. }
  72123. };
  72124. EdgesRenderer.prototype._generateEdgesLines = function () {
  72125. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  72126. var indices = this._source.getIndices();
  72127. if (!indices || !positions) {
  72128. return;
  72129. }
  72130. // First let's find adjacencies
  72131. var adjacencies = new Array();
  72132. var faceNormals = new Array();
  72133. var index;
  72134. var faceAdjacencies;
  72135. // Prepare faces
  72136. for (index = 0; index < indices.length; index += 3) {
  72137. faceAdjacencies = new FaceAdjacencies();
  72138. var p0Index = indices[index];
  72139. var p1Index = indices[index + 1];
  72140. var p2Index = indices[index + 2];
  72141. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  72142. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  72143. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  72144. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  72145. faceNormal.normalize();
  72146. faceNormals.push(faceNormal);
  72147. adjacencies.push(faceAdjacencies);
  72148. }
  72149. // Scan
  72150. for (index = 0; index < adjacencies.length; index++) {
  72151. faceAdjacencies = adjacencies[index];
  72152. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  72153. var otherFaceAdjacencies = adjacencies[otherIndex];
  72154. if (faceAdjacencies.edgesConnectedCount === 3) {
  72155. break;
  72156. }
  72157. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  72158. continue;
  72159. }
  72160. var otherP0 = indices[otherIndex * 3];
  72161. var otherP1 = indices[otherIndex * 3 + 1];
  72162. var otherP2 = indices[otherIndex * 3 + 2];
  72163. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  72164. var otherEdgeIndex = 0;
  72165. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  72166. continue;
  72167. }
  72168. switch (edgeIndex) {
  72169. case 0:
  72170. if (this._checkVerticesInsteadOfIndices) {
  72171. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72172. }
  72173. else {
  72174. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  72175. }
  72176. break;
  72177. case 1:
  72178. if (this._checkVerticesInsteadOfIndices) {
  72179. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72180. }
  72181. else {
  72182. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  72183. }
  72184. break;
  72185. case 2:
  72186. if (this._checkVerticesInsteadOfIndices) {
  72187. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72188. }
  72189. else {
  72190. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  72191. }
  72192. break;
  72193. }
  72194. if (otherEdgeIndex === -1) {
  72195. continue;
  72196. }
  72197. faceAdjacencies.edges[edgeIndex] = otherIndex;
  72198. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  72199. faceAdjacencies.edgesConnectedCount++;
  72200. otherFaceAdjacencies.edgesConnectedCount++;
  72201. if (faceAdjacencies.edgesConnectedCount === 3) {
  72202. break;
  72203. }
  72204. }
  72205. }
  72206. }
  72207. // Create lines
  72208. for (index = 0; index < adjacencies.length; index++) {
  72209. // 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
  72210. var current = adjacencies[index];
  72211. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  72212. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  72213. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  72214. }
  72215. // Merge into a single mesh
  72216. var engine = this._source.getScene().getEngine();
  72217. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  72218. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  72219. this._ib = engine.createIndexBuffer(this._linesIndices);
  72220. this._indicesCount = this._linesIndices.length;
  72221. };
  72222. EdgesRenderer.prototype.render = function () {
  72223. var scene = this._source.getScene();
  72224. if (!this._lineShader.isReady() || !scene.activeCamera) {
  72225. return;
  72226. }
  72227. var engine = scene.getEngine();
  72228. this._lineShader._preBind();
  72229. // VBOs
  72230. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  72231. scene.resetCachedMaterial();
  72232. this._lineShader.setColor4("color", this._source.edgesColor);
  72233. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  72234. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  72235. }
  72236. else {
  72237. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  72238. }
  72239. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  72240. this._lineShader.bind(this._source.getWorldMatrix());
  72241. // Draw order
  72242. engine.draw(true, 0, this._indicesCount);
  72243. this._lineShader.unbind();
  72244. engine.setDepthWrite(true);
  72245. };
  72246. return EdgesRenderer;
  72247. }());
  72248. BABYLON.EdgesRenderer = EdgesRenderer;
  72249. })(BABYLON || (BABYLON = {}));
  72250. //# sourceMappingURL=babylon.edgesRenderer.js.map
  72251. var BABYLON;
  72252. (function (BABYLON) {
  72253. /**
  72254. * Special Glow Blur post process only blurring the alpha channel
  72255. * It enforces keeping the most luminous color in the color channel.
  72256. */
  72257. var GlowBlurPostProcess = /** @class */ (function (_super) {
  72258. __extends(GlowBlurPostProcess, _super);
  72259. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  72260. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72261. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  72262. _this.direction = direction;
  72263. _this.kernel = kernel;
  72264. _this.onApplyObservable.add(function (effect) {
  72265. effect.setFloat2("screenSize", _this.width, _this.height);
  72266. effect.setVector2("direction", _this.direction);
  72267. effect.setFloat("blurWidth", _this.kernel);
  72268. });
  72269. return _this;
  72270. }
  72271. return GlowBlurPostProcess;
  72272. }(BABYLON.PostProcess));
  72273. /**
  72274. * The highlight layer Helps adding a glow effect around a mesh.
  72275. *
  72276. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  72277. * glowy meshes to your scene.
  72278. *
  72279. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  72280. */
  72281. var HighlightLayer = /** @class */ (function () {
  72282. /**
  72283. * Instantiates a new highlight Layer and references it to the scene..
  72284. * @param name The name of the layer
  72285. * @param scene The scene to use the layer in
  72286. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  72287. */
  72288. function HighlightLayer(name, scene, options) {
  72289. this.name = name;
  72290. this._vertexBuffers = {};
  72291. this._mainTextureDesiredSize = { width: 0, height: 0 };
  72292. this._meshes = {};
  72293. this._maxSize = 0;
  72294. this._shouldRender = false;
  72295. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  72296. this._excludedMeshes = {};
  72297. /**
  72298. * Specifies whether or not the inner glow is ACTIVE in the layer.
  72299. */
  72300. this.innerGlow = true;
  72301. /**
  72302. * Specifies whether or not the outer glow is ACTIVE in the layer.
  72303. */
  72304. this.outerGlow = true;
  72305. /**
  72306. * Specifies wether the highlight layer is enabled or not.
  72307. */
  72308. this.isEnabled = true;
  72309. /**
  72310. * An event triggered when the highlight layer has been disposed.
  72311. * @type {BABYLON.Observable}
  72312. */
  72313. this.onDisposeObservable = new BABYLON.Observable();
  72314. /**
  72315. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  72316. * @type {BABYLON.Observable}
  72317. */
  72318. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  72319. /**
  72320. * An event triggered when the highlight layer is being blurred.
  72321. * @type {BABYLON.Observable}
  72322. */
  72323. this.onBeforeBlurObservable = new BABYLON.Observable();
  72324. /**
  72325. * An event triggered when the highlight layer has been blurred.
  72326. * @type {BABYLON.Observable}
  72327. */
  72328. this.onAfterBlurObservable = new BABYLON.Observable();
  72329. /**
  72330. * An event triggered when the glowing blurred texture is being merged in the scene.
  72331. * @type {BABYLON.Observable}
  72332. */
  72333. this.onBeforeComposeObservable = new BABYLON.Observable();
  72334. /**
  72335. * An event triggered when the glowing blurred texture has been merged in the scene.
  72336. * @type {BABYLON.Observable}
  72337. */
  72338. this.onAfterComposeObservable = new BABYLON.Observable();
  72339. /**
  72340. * An event triggered when the highlight layer changes its size.
  72341. * @type {BABYLON.Observable}
  72342. */
  72343. this.onSizeChangedObservable = new BABYLON.Observable();
  72344. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72345. var engine = scene.getEngine();
  72346. this._engine = engine;
  72347. this._maxSize = this._engine.getCaps().maxTextureSize;
  72348. this._scene.highlightLayers.push(this);
  72349. // Warn on stencil.
  72350. if (!this._engine.isStencilEnable) {
  72351. 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 }");
  72352. }
  72353. // Adapt options
  72354. this._options = options || {
  72355. mainTextureRatio: 0.5,
  72356. blurTextureSizeRatio: 0.5,
  72357. blurHorizontalSize: 1.0,
  72358. blurVerticalSize: 1.0,
  72359. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  72360. camera: null
  72361. };
  72362. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  72363. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  72364. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  72365. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  72366. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  72367. // VBO
  72368. var vertices = [];
  72369. vertices.push(1, 1);
  72370. vertices.push(-1, 1);
  72371. vertices.push(-1, -1);
  72372. vertices.push(1, -1);
  72373. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72374. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  72375. this._createIndexBuffer();
  72376. // Effect
  72377. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  72378. // Render target
  72379. this.setMainTextureSize();
  72380. // Create Textures and post processes
  72381. this.createTextureAndPostProcesses();
  72382. }
  72383. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  72384. /**
  72385. * Gets the horizontal size of the blur.
  72386. */
  72387. get: function () {
  72388. return this._horizontalBlurPostprocess.kernel;
  72389. },
  72390. /**
  72391. * Specifies the horizontal size of the blur.
  72392. */
  72393. set: function (value) {
  72394. this._horizontalBlurPostprocess.kernel = value;
  72395. },
  72396. enumerable: true,
  72397. configurable: true
  72398. });
  72399. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  72400. /**
  72401. * Gets the vertical size of the blur.
  72402. */
  72403. get: function () {
  72404. return this._verticalBlurPostprocess.kernel;
  72405. },
  72406. /**
  72407. * Specifies the vertical size of the blur.
  72408. */
  72409. set: function (value) {
  72410. this._verticalBlurPostprocess.kernel = value;
  72411. },
  72412. enumerable: true,
  72413. configurable: true
  72414. });
  72415. Object.defineProperty(HighlightLayer.prototype, "camera", {
  72416. /**
  72417. * Gets the camera attached to the layer.
  72418. */
  72419. get: function () {
  72420. return this._options.camera;
  72421. },
  72422. enumerable: true,
  72423. configurable: true
  72424. });
  72425. HighlightLayer.prototype._createIndexBuffer = function () {
  72426. var engine = this._scene.getEngine();
  72427. // Indices
  72428. var indices = [];
  72429. indices.push(0);
  72430. indices.push(1);
  72431. indices.push(2);
  72432. indices.push(0);
  72433. indices.push(2);
  72434. indices.push(3);
  72435. this._indexBuffer = engine.createIndexBuffer(indices);
  72436. };
  72437. HighlightLayer.prototype._rebuild = function () {
  72438. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72439. if (vb) {
  72440. vb._rebuild();
  72441. }
  72442. this._createIndexBuffer();
  72443. };
  72444. /**
  72445. * Creates the render target textures and post processes used in the highlight layer.
  72446. */
  72447. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  72448. var _this = this;
  72449. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  72450. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  72451. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  72452. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  72453. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  72454. width: this._mainTextureDesiredSize.width,
  72455. height: this._mainTextureDesiredSize.height
  72456. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72457. this._mainTexture.activeCamera = this._options.camera;
  72458. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72459. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72460. this._mainTexture.anisotropicFilteringLevel = 1;
  72461. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72462. this._mainTexture.renderParticles = false;
  72463. this._mainTexture.renderList = null;
  72464. this._mainTexture.ignoreCameraViewport = true;
  72465. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  72466. width: blurTextureWidth,
  72467. height: blurTextureHeight
  72468. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72469. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72470. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72471. this._blurTexture.anisotropicFilteringLevel = 16;
  72472. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72473. this._blurTexture.renderParticles = false;
  72474. this._blurTexture.ignoreCameraViewport = true;
  72475. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72476. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  72477. effect.setTexture("textureSampler", _this._mainTexture);
  72478. });
  72479. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  72480. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72481. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72482. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72483. });
  72484. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72485. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72486. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72487. });
  72488. }
  72489. else {
  72490. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72491. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72492. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72493. });
  72494. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72495. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72496. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72497. });
  72498. }
  72499. this._mainTexture.onAfterUnbindObservable.add(function () {
  72500. _this.onBeforeBlurObservable.notifyObservers(_this);
  72501. var internalTexture = _this._blurTexture.getInternalTexture();
  72502. if (internalTexture) {
  72503. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  72504. }
  72505. _this.onAfterBlurObservable.notifyObservers(_this);
  72506. });
  72507. // Custom render function
  72508. var renderSubMesh = function (subMesh) {
  72509. if (!_this._meshes) {
  72510. return;
  72511. }
  72512. var material = subMesh.getMaterial();
  72513. var mesh = subMesh.getRenderingMesh();
  72514. var scene = _this._scene;
  72515. var engine = scene.getEngine();
  72516. if (!material) {
  72517. return;
  72518. }
  72519. // Culling
  72520. engine.setState(material.backFaceCulling);
  72521. // Managing instances
  72522. var batch = mesh._getInstancesRenderList(subMesh._id);
  72523. if (batch.mustReturn) {
  72524. return;
  72525. }
  72526. // Excluded Mesh
  72527. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72528. return;
  72529. }
  72530. ;
  72531. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72532. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  72533. var emissiveTexture = null;
  72534. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  72535. emissiveTexture = material.emissiveTexture;
  72536. }
  72537. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  72538. engine.enableEffect(_this._glowMapGenerationEffect);
  72539. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  72540. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  72541. if (highlightLayerMesh) {
  72542. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  72543. }
  72544. else {
  72545. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  72546. }
  72547. // Alpha test
  72548. if (material && material.needAlphaTesting()) {
  72549. var alphaTexture = material.getAlphaTestTexture();
  72550. if (alphaTexture) {
  72551. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  72552. var textureMatrix = alphaTexture.getTextureMatrix();
  72553. if (textureMatrix) {
  72554. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  72555. }
  72556. }
  72557. }
  72558. // Glow emissive only
  72559. if (emissiveTexture) {
  72560. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  72561. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  72562. }
  72563. // Bones
  72564. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72565. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72566. }
  72567. // Draw
  72568. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  72569. }
  72570. else {
  72571. // Need to reset refresh rate of the shadowMap
  72572. _this._mainTexture.resetRefreshCounter();
  72573. }
  72574. };
  72575. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72576. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  72577. var index;
  72578. var engine = _this._scene.getEngine();
  72579. if (depthOnlySubMeshes.length) {
  72580. engine.setColorWrite(false);
  72581. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72582. renderSubMesh(depthOnlySubMeshes.data[index]);
  72583. }
  72584. engine.setColorWrite(true);
  72585. }
  72586. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72587. renderSubMesh(opaqueSubMeshes.data[index]);
  72588. }
  72589. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72590. renderSubMesh(alphaTestSubMeshes.data[index]);
  72591. }
  72592. for (index = 0; index < transparentSubMeshes.length; index++) {
  72593. renderSubMesh(transparentSubMeshes.data[index]);
  72594. }
  72595. };
  72596. this._mainTexture.onClearObservable.add(function (engine) {
  72597. engine.clear(HighlightLayer.neutralColor, true, true, true);
  72598. });
  72599. };
  72600. /**
  72601. * Checks for the readiness of the element composing the layer.
  72602. * @param subMesh the mesh to check for
  72603. * @param useInstances specify wether or not to use instances to render the mesh
  72604. * @param emissiveTexture the associated emissive texture used to generate the glow
  72605. * @return true if ready otherwise, false
  72606. */
  72607. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  72608. var material = subMesh.getMaterial();
  72609. if (!material) {
  72610. return false;
  72611. }
  72612. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  72613. return false;
  72614. }
  72615. var defines = [];
  72616. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72617. var mesh = subMesh.getMesh();
  72618. var uv1 = false;
  72619. var uv2 = false;
  72620. // Alpha test
  72621. if (material && material.needAlphaTesting()) {
  72622. var alphaTexture = material.getAlphaTestTexture();
  72623. if (alphaTexture) {
  72624. defines.push("#define ALPHATEST");
  72625. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72626. alphaTexture.coordinatesIndex === 1) {
  72627. defines.push("#define DIFFUSEUV2");
  72628. uv2 = true;
  72629. }
  72630. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72631. defines.push("#define DIFFUSEUV1");
  72632. uv1 = true;
  72633. }
  72634. }
  72635. }
  72636. // Emissive
  72637. if (emissiveTexture) {
  72638. defines.push("#define EMISSIVE");
  72639. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72640. emissiveTexture.coordinatesIndex === 1) {
  72641. defines.push("#define EMISSIVEUV2");
  72642. uv2 = true;
  72643. }
  72644. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72645. defines.push("#define EMISSIVEUV1");
  72646. uv1 = true;
  72647. }
  72648. }
  72649. if (uv1) {
  72650. attribs.push(BABYLON.VertexBuffer.UVKind);
  72651. defines.push("#define UV1");
  72652. }
  72653. if (uv2) {
  72654. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72655. defines.push("#define UV2");
  72656. }
  72657. // Bones
  72658. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72659. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72660. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72661. if (mesh.numBoneInfluencers > 4) {
  72662. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72663. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72664. }
  72665. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72666. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72667. }
  72668. else {
  72669. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72670. }
  72671. // Instances
  72672. if (useInstances) {
  72673. defines.push("#define INSTANCES");
  72674. attribs.push("world0");
  72675. attribs.push("world1");
  72676. attribs.push("world2");
  72677. attribs.push("world3");
  72678. }
  72679. // Get correct effect
  72680. var join = defines.join("\n");
  72681. if (this._cachedDefines !== join) {
  72682. this._cachedDefines = join;
  72683. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  72684. }
  72685. return this._glowMapGenerationEffect.isReady();
  72686. };
  72687. /**
  72688. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  72689. */
  72690. HighlightLayer.prototype.render = function () {
  72691. var currentEffect = this._glowMapMergeEffect;
  72692. // Check
  72693. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  72694. return;
  72695. var engine = this._scene.getEngine();
  72696. this.onBeforeComposeObservable.notifyObservers(this);
  72697. // Render
  72698. engine.enableEffect(currentEffect);
  72699. engine.setState(false);
  72700. // Cache
  72701. var previousStencilBuffer = engine.getStencilBuffer();
  72702. var previousStencilFunction = engine.getStencilFunction();
  72703. var previousStencilMask = engine.getStencilMask();
  72704. var previousStencilOperationPass = engine.getStencilOperationPass();
  72705. var previousStencilOperationFail = engine.getStencilOperationFail();
  72706. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  72707. var previousAlphaMode = engine.getAlphaMode();
  72708. // Texture
  72709. currentEffect.setTexture("textureSampler", this._blurTexture);
  72710. // VBOs
  72711. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72712. // Stencil operations
  72713. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  72714. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  72715. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  72716. // Draw order
  72717. engine.setAlphaMode(this._options.alphaBlendingMode);
  72718. engine.setStencilMask(0x00);
  72719. engine.setStencilBuffer(true);
  72720. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  72721. if (this.outerGlow) {
  72722. currentEffect.setFloat("offset", 0);
  72723. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  72724. engine.draw(true, 0, 6);
  72725. }
  72726. if (this.innerGlow) {
  72727. currentEffect.setFloat("offset", 1);
  72728. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  72729. engine.draw(true, 0, 6);
  72730. }
  72731. // Restore Cache
  72732. engine.setStencilFunction(previousStencilFunction);
  72733. engine.setStencilMask(previousStencilMask);
  72734. engine.setAlphaMode(previousAlphaMode);
  72735. engine.setStencilBuffer(previousStencilBuffer);
  72736. engine.setStencilOperationPass(previousStencilOperationPass);
  72737. engine.setStencilOperationFail(previousStencilOperationFail);
  72738. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  72739. engine._stencilState.reset();
  72740. this.onAfterComposeObservable.notifyObservers(this);
  72741. // Handle size changes.
  72742. var size = this._mainTexture.getSize();
  72743. this.setMainTextureSize();
  72744. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  72745. // Recreate RTT and post processes on size change.
  72746. this.onSizeChangedObservable.notifyObservers(this);
  72747. this.disposeTextureAndPostProcesses();
  72748. this.createTextureAndPostProcesses();
  72749. }
  72750. };
  72751. /**
  72752. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  72753. * @param mesh The mesh to exclude from the highlight layer
  72754. */
  72755. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  72756. if (!this._excludedMeshes) {
  72757. return;
  72758. }
  72759. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72760. if (!meshExcluded) {
  72761. this._excludedMeshes[mesh.uniqueId] = {
  72762. mesh: mesh,
  72763. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  72764. mesh.getEngine().setStencilBuffer(false);
  72765. }),
  72766. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  72767. mesh.getEngine().setStencilBuffer(true);
  72768. }),
  72769. };
  72770. }
  72771. };
  72772. /**
  72773. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  72774. * @param mesh The mesh to highlight
  72775. */
  72776. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  72777. if (!this._excludedMeshes) {
  72778. return;
  72779. }
  72780. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72781. if (meshExcluded) {
  72782. if (meshExcluded.beforeRender) {
  72783. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  72784. }
  72785. if (meshExcluded.afterRender) {
  72786. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  72787. }
  72788. }
  72789. this._excludedMeshes[mesh.uniqueId] = null;
  72790. };
  72791. /**
  72792. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  72793. * @param mesh The mesh to highlight
  72794. * @param color The color of the highlight
  72795. * @param glowEmissiveOnly Extract the glow from the emissive texture
  72796. */
  72797. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  72798. var _this = this;
  72799. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  72800. if (!this._meshes) {
  72801. return;
  72802. }
  72803. var meshHighlight = this._meshes[mesh.uniqueId];
  72804. if (meshHighlight) {
  72805. meshHighlight.color = color;
  72806. }
  72807. else {
  72808. this._meshes[mesh.uniqueId] = {
  72809. mesh: mesh,
  72810. color: color,
  72811. // Lambda required for capture due to Observable this context
  72812. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72813. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72814. _this.defaultStencilReference(mesh);
  72815. }
  72816. else {
  72817. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72818. }
  72819. }),
  72820. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72821. glowEmissiveOnly: glowEmissiveOnly
  72822. };
  72823. }
  72824. this._shouldRender = true;
  72825. };
  72826. /**
  72827. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72828. * @param mesh The mesh to highlight
  72829. */
  72830. HighlightLayer.prototype.removeMesh = function (mesh) {
  72831. if (!this._meshes) {
  72832. return;
  72833. }
  72834. var meshHighlight = this._meshes[mesh.uniqueId];
  72835. if (meshHighlight) {
  72836. if (meshHighlight.observerHighlight) {
  72837. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72838. }
  72839. if (meshHighlight.observerDefault) {
  72840. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72841. }
  72842. }
  72843. this._meshes[mesh.uniqueId] = null;
  72844. this._shouldRender = false;
  72845. for (var meshHighlightToCheck in this._meshes) {
  72846. if (meshHighlightToCheck) {
  72847. this._shouldRender = true;
  72848. break;
  72849. }
  72850. }
  72851. };
  72852. /**
  72853. * Returns true if the layer contains information to display, otherwise false.
  72854. */
  72855. HighlightLayer.prototype.shouldRender = function () {
  72856. return this.isEnabled && this._shouldRender;
  72857. };
  72858. /**
  72859. * Sets the main texture desired size which is the closest power of two
  72860. * of the engine canvas size.
  72861. */
  72862. HighlightLayer.prototype.setMainTextureSize = function () {
  72863. if (this._options.mainTextureFixedSize) {
  72864. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72865. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72866. }
  72867. else {
  72868. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72869. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72870. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72871. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72872. }
  72873. };
  72874. /**
  72875. * Force the stencil to the normal expected value for none glowing parts
  72876. */
  72877. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72878. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72879. };
  72880. /**
  72881. * Dispose only the render target textures and post process.
  72882. */
  72883. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72884. this._blurTexture.dispose();
  72885. this._mainTexture.dispose();
  72886. this._downSamplePostprocess.dispose();
  72887. this._horizontalBlurPostprocess.dispose();
  72888. this._verticalBlurPostprocess.dispose();
  72889. };
  72890. /**
  72891. * Dispose the highlight layer and free resources.
  72892. */
  72893. HighlightLayer.prototype.dispose = function () {
  72894. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72895. if (vertexBuffer) {
  72896. vertexBuffer.dispose();
  72897. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72898. }
  72899. if (this._indexBuffer) {
  72900. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72901. this._indexBuffer = null;
  72902. }
  72903. // Clean textures and post processes
  72904. this.disposeTextureAndPostProcesses();
  72905. if (this._meshes) {
  72906. // Clean mesh references
  72907. for (var id in this._meshes) {
  72908. var meshHighlight = this._meshes[id];
  72909. if (meshHighlight && meshHighlight.mesh) {
  72910. if (meshHighlight.observerHighlight) {
  72911. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72912. }
  72913. if (meshHighlight.observerDefault) {
  72914. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72915. }
  72916. }
  72917. }
  72918. this._meshes = null;
  72919. }
  72920. if (this._excludedMeshes) {
  72921. for (var id in this._excludedMeshes) {
  72922. var meshHighlight = this._excludedMeshes[id];
  72923. if (meshHighlight) {
  72924. if (meshHighlight.beforeRender) {
  72925. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72926. }
  72927. if (meshHighlight.afterRender) {
  72928. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72929. }
  72930. }
  72931. }
  72932. this._excludedMeshes = null;
  72933. }
  72934. // Remove from scene
  72935. var index = this._scene.highlightLayers.indexOf(this, 0);
  72936. if (index > -1) {
  72937. this._scene.highlightLayers.splice(index, 1);
  72938. }
  72939. // Callback
  72940. this.onDisposeObservable.notifyObservers(this);
  72941. this.onDisposeObservable.clear();
  72942. this.onBeforeRenderMainTextureObservable.clear();
  72943. this.onBeforeBlurObservable.clear();
  72944. this.onBeforeComposeObservable.clear();
  72945. this.onAfterComposeObservable.clear();
  72946. this.onSizeChangedObservable.clear();
  72947. };
  72948. /**
  72949. * The neutral color used during the preparation of the glow effect.
  72950. * This is black by default as the blend operation is a blend operation.
  72951. */
  72952. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72953. /**
  72954. * Stencil value used for glowing meshes.
  72955. */
  72956. HighlightLayer.glowingMeshStencilReference = 0x02;
  72957. /**
  72958. * Stencil value used for the other meshes in the scene.
  72959. */
  72960. HighlightLayer.normalMeshStencilReference = 0x01;
  72961. return HighlightLayer;
  72962. }());
  72963. BABYLON.HighlightLayer = HighlightLayer;
  72964. })(BABYLON || (BABYLON = {}));
  72965. //# sourceMappingURL=babylon.highlightlayer.js.map
  72966. var BABYLON;
  72967. (function (BABYLON) {
  72968. var AssetTaskState;
  72969. (function (AssetTaskState) {
  72970. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72971. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72972. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72973. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72974. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72975. var AbstractAssetTask = /** @class */ (function () {
  72976. function AbstractAssetTask(name) {
  72977. this.name = name;
  72978. this.isCompleted = false;
  72979. this.taskState = AssetTaskState.INIT;
  72980. }
  72981. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72982. var _this = this;
  72983. this.taskState = AssetTaskState.RUNNING;
  72984. this.runTask(scene, function () {
  72985. _this.onDoneCallback(onSuccess, onError);
  72986. }, function (msg, exception) {
  72987. _this.onErrorCallback(onError, msg, exception);
  72988. });
  72989. };
  72990. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72991. throw new Error("runTask is not implemented");
  72992. };
  72993. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72994. this.taskState = AssetTaskState.ERROR;
  72995. this.errorObject = {
  72996. message: message,
  72997. exception: exception
  72998. };
  72999. if (this.onError) {
  73000. this.onError(this, message, exception);
  73001. }
  73002. onError();
  73003. };
  73004. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  73005. try {
  73006. this.taskState = AssetTaskState.DONE;
  73007. this.isCompleted = true;
  73008. if (this.onSuccess) {
  73009. this.onSuccess(this);
  73010. }
  73011. onSuccess();
  73012. }
  73013. catch (e) {
  73014. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  73015. }
  73016. };
  73017. return AbstractAssetTask;
  73018. }());
  73019. BABYLON.AbstractAssetTask = AbstractAssetTask;
  73020. var AssetsProgressEvent = /** @class */ (function () {
  73021. function AssetsProgressEvent(remainingCount, totalCount, task) {
  73022. this.remainingCount = remainingCount;
  73023. this.totalCount = totalCount;
  73024. this.task = task;
  73025. }
  73026. return AssetsProgressEvent;
  73027. }());
  73028. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  73029. var MeshAssetTask = /** @class */ (function (_super) {
  73030. __extends(MeshAssetTask, _super);
  73031. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  73032. var _this = _super.call(this, name) || this;
  73033. _this.name = name;
  73034. _this.meshesNames = meshesNames;
  73035. _this.rootUrl = rootUrl;
  73036. _this.sceneFilename = sceneFilename;
  73037. return _this;
  73038. }
  73039. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73040. var _this = this;
  73041. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  73042. _this.loadedMeshes = meshes;
  73043. _this.loadedParticleSystems = particleSystems;
  73044. _this.loadedSkeletons = skeletons;
  73045. onSuccess();
  73046. }, null, function (scene, message, exception) {
  73047. onError(message, exception);
  73048. });
  73049. };
  73050. return MeshAssetTask;
  73051. }(AbstractAssetTask));
  73052. BABYLON.MeshAssetTask = MeshAssetTask;
  73053. var TextFileAssetTask = /** @class */ (function (_super) {
  73054. __extends(TextFileAssetTask, _super);
  73055. function TextFileAssetTask(name, url) {
  73056. var _this = _super.call(this, name) || this;
  73057. _this.name = name;
  73058. _this.url = url;
  73059. return _this;
  73060. }
  73061. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73062. var _this = this;
  73063. BABYLON.Tools.LoadFile(this.url, function (data) {
  73064. _this.text = data;
  73065. onSuccess();
  73066. }, undefined, scene.database, false, function (request, exception) {
  73067. if (request) {
  73068. onError(request.status + " " + request.statusText, exception);
  73069. }
  73070. });
  73071. };
  73072. return TextFileAssetTask;
  73073. }(AbstractAssetTask));
  73074. BABYLON.TextFileAssetTask = TextFileAssetTask;
  73075. var BinaryFileAssetTask = /** @class */ (function (_super) {
  73076. __extends(BinaryFileAssetTask, _super);
  73077. function BinaryFileAssetTask(name, url) {
  73078. var _this = _super.call(this, name) || this;
  73079. _this.name = name;
  73080. _this.url = url;
  73081. return _this;
  73082. }
  73083. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73084. var _this = this;
  73085. BABYLON.Tools.LoadFile(this.url, function (data) {
  73086. _this.data = data;
  73087. onSuccess();
  73088. }, undefined, scene.database, true, function (request, exception) {
  73089. if (request) {
  73090. onError(request.status + " " + request.statusText, exception);
  73091. }
  73092. });
  73093. };
  73094. return BinaryFileAssetTask;
  73095. }(AbstractAssetTask));
  73096. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  73097. var ImageAssetTask = /** @class */ (function (_super) {
  73098. __extends(ImageAssetTask, _super);
  73099. function ImageAssetTask(name, url) {
  73100. var _this = _super.call(this, name) || this;
  73101. _this.name = name;
  73102. _this.url = url;
  73103. return _this;
  73104. }
  73105. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73106. var _this = this;
  73107. var img = new Image();
  73108. BABYLON.Tools.SetCorsBehavior(this.url, img);
  73109. img.onload = function () {
  73110. _this.image = img;
  73111. onSuccess();
  73112. };
  73113. img.onerror = function (err) {
  73114. onError("Error loading image", err);
  73115. };
  73116. img.src = this.url;
  73117. };
  73118. return ImageAssetTask;
  73119. }(AbstractAssetTask));
  73120. BABYLON.ImageAssetTask = ImageAssetTask;
  73121. var TextureAssetTask = /** @class */ (function (_super) {
  73122. __extends(TextureAssetTask, _super);
  73123. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  73124. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73125. var _this = _super.call(this, name) || this;
  73126. _this.name = name;
  73127. _this.url = url;
  73128. _this.noMipmap = noMipmap;
  73129. _this.invertY = invertY;
  73130. _this.samplingMode = samplingMode;
  73131. return _this;
  73132. }
  73133. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73134. var onload = function () {
  73135. onSuccess();
  73136. };
  73137. var onerror = function (msg, exception) {
  73138. onError(msg, exception);
  73139. };
  73140. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  73141. };
  73142. return TextureAssetTask;
  73143. }(AbstractAssetTask));
  73144. BABYLON.TextureAssetTask = TextureAssetTask;
  73145. var CubeTextureAssetTask = /** @class */ (function (_super) {
  73146. __extends(CubeTextureAssetTask, _super);
  73147. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  73148. var _this = _super.call(this, name) || this;
  73149. _this.name = name;
  73150. _this.url = url;
  73151. _this.extensions = extensions;
  73152. _this.noMipmap = noMipmap;
  73153. _this.files = files;
  73154. return _this;
  73155. }
  73156. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73157. var onload = function () {
  73158. onSuccess();
  73159. };
  73160. var onerror = function (msg, exception) {
  73161. onError(msg, exception);
  73162. };
  73163. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  73164. };
  73165. return CubeTextureAssetTask;
  73166. }(AbstractAssetTask));
  73167. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  73168. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  73169. __extends(HDRCubeTextureAssetTask, _super);
  73170. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  73171. if (noMipmap === void 0) { noMipmap = false; }
  73172. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73173. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73174. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73175. var _this = _super.call(this, name) || this;
  73176. _this.name = name;
  73177. _this.url = url;
  73178. _this.size = size;
  73179. _this.noMipmap = noMipmap;
  73180. _this.generateHarmonics = generateHarmonics;
  73181. _this.useInGammaSpace = useInGammaSpace;
  73182. _this.usePMREMGenerator = usePMREMGenerator;
  73183. return _this;
  73184. }
  73185. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  73186. var onload = function () {
  73187. onSuccess();
  73188. };
  73189. var onerror = function (message, exception) {
  73190. onError(message, exception);
  73191. };
  73192. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  73193. };
  73194. return HDRCubeTextureAssetTask;
  73195. }(AbstractAssetTask));
  73196. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  73197. var AssetsManager = /** @class */ (function () {
  73198. function AssetsManager(scene) {
  73199. this.tasks = new Array();
  73200. this.waitingTasksCount = 0;
  73201. //Observables
  73202. this.onTaskSuccessObservable = new BABYLON.Observable();
  73203. this.onTaskErrorObservable = new BABYLON.Observable();
  73204. this.onTasksDoneObservable = new BABYLON.Observable();
  73205. this.onProgressObservable = new BABYLON.Observable();
  73206. this.useDefaultLoadingScreen = true;
  73207. this._scene = scene;
  73208. }
  73209. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  73210. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  73211. this.tasks.push(task);
  73212. return task;
  73213. };
  73214. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  73215. var task = new TextFileAssetTask(taskName, url);
  73216. this.tasks.push(task);
  73217. return task;
  73218. };
  73219. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  73220. var task = new BinaryFileAssetTask(taskName, url);
  73221. this.tasks.push(task);
  73222. return task;
  73223. };
  73224. AssetsManager.prototype.addImageTask = function (taskName, url) {
  73225. var task = new ImageAssetTask(taskName, url);
  73226. this.tasks.push(task);
  73227. return task;
  73228. };
  73229. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  73230. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73231. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  73232. this.tasks.push(task);
  73233. return task;
  73234. };
  73235. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  73236. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  73237. this.tasks.push(task);
  73238. return task;
  73239. };
  73240. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  73241. if (noMipmap === void 0) { noMipmap = false; }
  73242. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73243. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73244. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73245. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  73246. this.tasks.push(task);
  73247. return task;
  73248. };
  73249. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  73250. this.waitingTasksCount--;
  73251. try {
  73252. if (this.onProgress) {
  73253. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  73254. }
  73255. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  73256. }
  73257. catch (e) {
  73258. BABYLON.Tools.Error("Error running progress callbacks.");
  73259. console.log(e);
  73260. }
  73261. if (this.waitingTasksCount === 0) {
  73262. try {
  73263. if (this.onFinish) {
  73264. this.onFinish(this.tasks);
  73265. }
  73266. this.onTasksDoneObservable.notifyObservers(this.tasks);
  73267. }
  73268. catch (e) {
  73269. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  73270. console.log(e);
  73271. }
  73272. this._scene.getEngine().hideLoadingUI();
  73273. }
  73274. };
  73275. AssetsManager.prototype._runTask = function (task) {
  73276. var _this = this;
  73277. var done = function () {
  73278. try {
  73279. if (_this.onTaskSuccess) {
  73280. _this.onTaskSuccess(task);
  73281. }
  73282. _this.onTaskSuccessObservable.notifyObservers(task);
  73283. _this._decreaseWaitingTasksCount(task);
  73284. }
  73285. catch (e) {
  73286. error("Error executing task success callbacks", e);
  73287. }
  73288. };
  73289. var error = function (message, exception) {
  73290. task.errorObject = task.errorObject || {
  73291. message: message,
  73292. exception: exception
  73293. };
  73294. if (_this.onTaskError) {
  73295. _this.onTaskError(task);
  73296. }
  73297. _this.onTaskErrorObservable.notifyObservers(task);
  73298. _this._decreaseWaitingTasksCount(task);
  73299. };
  73300. task.run(this._scene, done, error);
  73301. };
  73302. AssetsManager.prototype.reset = function () {
  73303. this.tasks = new Array();
  73304. return this;
  73305. };
  73306. AssetsManager.prototype.load = function () {
  73307. this.waitingTasksCount = this.tasks.length;
  73308. if (this.waitingTasksCount === 0) {
  73309. if (this.onFinish) {
  73310. this.onFinish(this.tasks);
  73311. }
  73312. this.onTasksDoneObservable.notifyObservers(this.tasks);
  73313. return this;
  73314. }
  73315. if (this.useDefaultLoadingScreen) {
  73316. this._scene.getEngine().displayLoadingUI();
  73317. }
  73318. for (var index = 0; index < this.tasks.length; index++) {
  73319. var task = this.tasks[index];
  73320. this._runTask(task);
  73321. }
  73322. return this;
  73323. };
  73324. return AssetsManager;
  73325. }());
  73326. BABYLON.AssetsManager = AssetsManager;
  73327. })(BABYLON || (BABYLON = {}));
  73328. //# sourceMappingURL=babylon.assetsManager.js.map
  73329. var BABYLON;
  73330. (function (BABYLON) {
  73331. var serializedGeometries = [];
  73332. var serializeGeometry = function (geometry, serializationGeometries) {
  73333. if (serializedGeometries[geometry.id]) {
  73334. return;
  73335. }
  73336. if (geometry.doNotSerialize) {
  73337. return;
  73338. }
  73339. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  73340. serializationGeometries.boxes.push(geometry.serialize());
  73341. }
  73342. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  73343. serializationGeometries.spheres.push(geometry.serialize());
  73344. }
  73345. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  73346. serializationGeometries.cylinders.push(geometry.serialize());
  73347. }
  73348. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  73349. serializationGeometries.toruses.push(geometry.serialize());
  73350. }
  73351. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  73352. serializationGeometries.grounds.push(geometry.serialize());
  73353. }
  73354. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  73355. serializationGeometries.planes.push(geometry.serialize());
  73356. }
  73357. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  73358. serializationGeometries.torusKnots.push(geometry.serialize());
  73359. }
  73360. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  73361. throw new Error("Unknown primitive type");
  73362. }
  73363. else {
  73364. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  73365. }
  73366. serializedGeometries[geometry.id] = true;
  73367. };
  73368. var serializeMesh = function (mesh, serializationScene) {
  73369. var serializationObject = {};
  73370. // Geometry
  73371. var geometry = mesh._geometry;
  73372. if (geometry) {
  73373. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  73374. // 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
  73375. serializeGeometry(geometry, serializationScene.geometries);
  73376. }
  73377. }
  73378. // Custom
  73379. if (mesh.serialize) {
  73380. mesh.serialize(serializationObject);
  73381. }
  73382. return serializationObject;
  73383. };
  73384. var finalizeSingleMesh = function (mesh, serializationObject) {
  73385. //only works if the mesh is already loaded
  73386. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73387. //serialize material
  73388. if (mesh.material) {
  73389. if (mesh.material instanceof BABYLON.StandardMaterial) {
  73390. serializationObject.materials = serializationObject.materials || [];
  73391. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  73392. serializationObject.materials.push(mesh.material.serialize());
  73393. }
  73394. }
  73395. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  73396. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  73397. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  73398. serializationObject.multiMaterials.push(mesh.material.serialize());
  73399. }
  73400. }
  73401. }
  73402. //serialize geometry
  73403. var geometry = mesh._geometry;
  73404. if (geometry) {
  73405. if (!serializationObject.geometries) {
  73406. serializationObject.geometries = {};
  73407. serializationObject.geometries.boxes = [];
  73408. serializationObject.geometries.spheres = [];
  73409. serializationObject.geometries.cylinders = [];
  73410. serializationObject.geometries.toruses = [];
  73411. serializationObject.geometries.grounds = [];
  73412. serializationObject.geometries.planes = [];
  73413. serializationObject.geometries.torusKnots = [];
  73414. serializationObject.geometries.vertexData = [];
  73415. }
  73416. serializeGeometry(geometry, serializationObject.geometries);
  73417. }
  73418. // Skeletons
  73419. if (mesh.skeleton) {
  73420. serializationObject.skeletons = serializationObject.skeletons || [];
  73421. serializationObject.skeletons.push(mesh.skeleton.serialize());
  73422. }
  73423. //serialize the actual mesh
  73424. serializationObject.meshes = serializationObject.meshes || [];
  73425. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73426. }
  73427. };
  73428. var SceneSerializer = /** @class */ (function () {
  73429. function SceneSerializer() {
  73430. }
  73431. SceneSerializer.ClearCache = function () {
  73432. serializedGeometries = [];
  73433. };
  73434. SceneSerializer.Serialize = function (scene) {
  73435. var serializationObject = {};
  73436. SceneSerializer.ClearCache();
  73437. // Scene
  73438. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  73439. serializationObject.autoClear = scene.autoClear;
  73440. serializationObject.clearColor = scene.clearColor.asArray();
  73441. serializationObject.ambientColor = scene.ambientColor.asArray();
  73442. serializationObject.gravity = scene.gravity.asArray();
  73443. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  73444. serializationObject.workerCollisions = scene.workerCollisions;
  73445. // Fog
  73446. if (scene.fogMode && scene.fogMode !== 0) {
  73447. serializationObject.fogMode = scene.fogMode;
  73448. serializationObject.fogColor = scene.fogColor.asArray();
  73449. serializationObject.fogStart = scene.fogStart;
  73450. serializationObject.fogEnd = scene.fogEnd;
  73451. serializationObject.fogDensity = scene.fogDensity;
  73452. }
  73453. //Physics
  73454. if (scene.isPhysicsEnabled()) {
  73455. var physicEngine = scene.getPhysicsEngine();
  73456. if (physicEngine) {
  73457. serializationObject.physicsEnabled = true;
  73458. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  73459. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  73460. }
  73461. }
  73462. // Metadata
  73463. if (scene.metadata) {
  73464. serializationObject.metadata = scene.metadata;
  73465. }
  73466. // Morph targets
  73467. serializationObject.morphTargetManagers = [];
  73468. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  73469. var abstractMesh = _a[_i];
  73470. var manager = abstractMesh.morphTargetManager;
  73471. if (manager) {
  73472. serializationObject.morphTargetManagers.push(manager.serialize());
  73473. }
  73474. }
  73475. // Lights
  73476. serializationObject.lights = [];
  73477. var index;
  73478. var light;
  73479. for (index = 0; index < scene.lights.length; index++) {
  73480. light = scene.lights[index];
  73481. if (!light.doNotSerialize) {
  73482. serializationObject.lights.push(light.serialize());
  73483. }
  73484. }
  73485. // Cameras
  73486. serializationObject.cameras = [];
  73487. for (index = 0; index < scene.cameras.length; index++) {
  73488. var camera = scene.cameras[index];
  73489. if (!camera.doNotSerialize) {
  73490. serializationObject.cameras.push(camera.serialize());
  73491. }
  73492. }
  73493. if (scene.activeCamera) {
  73494. serializationObject.activeCameraID = scene.activeCamera.id;
  73495. }
  73496. // Animations
  73497. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  73498. // Materials
  73499. serializationObject.materials = [];
  73500. serializationObject.multiMaterials = [];
  73501. var material;
  73502. for (index = 0; index < scene.materials.length; index++) {
  73503. material = scene.materials[index];
  73504. if (!material.doNotSerialize) {
  73505. serializationObject.materials.push(material.serialize());
  73506. }
  73507. }
  73508. // MultiMaterials
  73509. serializationObject.multiMaterials = [];
  73510. for (index = 0; index < scene.multiMaterials.length; index++) {
  73511. var multiMaterial = scene.multiMaterials[index];
  73512. serializationObject.multiMaterials.push(multiMaterial.serialize());
  73513. }
  73514. // Skeletons
  73515. serializationObject.skeletons = [];
  73516. for (index = 0; index < scene.skeletons.length; index++) {
  73517. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  73518. }
  73519. // Geometries
  73520. serializationObject.geometries = {};
  73521. serializationObject.geometries.boxes = [];
  73522. serializationObject.geometries.spheres = [];
  73523. serializationObject.geometries.cylinders = [];
  73524. serializationObject.geometries.toruses = [];
  73525. serializationObject.geometries.grounds = [];
  73526. serializationObject.geometries.planes = [];
  73527. serializationObject.geometries.torusKnots = [];
  73528. serializationObject.geometries.vertexData = [];
  73529. serializedGeometries = [];
  73530. var geometries = scene.getGeometries();
  73531. for (index = 0; index < geometries.length; index++) {
  73532. var geometry = geometries[index];
  73533. if (geometry.isReady()) {
  73534. serializeGeometry(geometry, serializationObject.geometries);
  73535. }
  73536. }
  73537. // Meshes
  73538. serializationObject.meshes = [];
  73539. for (index = 0; index < scene.meshes.length; index++) {
  73540. var abstractMesh = scene.meshes[index];
  73541. if (abstractMesh instanceof BABYLON.Mesh) {
  73542. var mesh = abstractMesh;
  73543. if (!mesh.doNotSerialize) {
  73544. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73545. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73546. }
  73547. }
  73548. }
  73549. }
  73550. // Particles Systems
  73551. serializationObject.particleSystems = [];
  73552. for (index = 0; index < scene.particleSystems.length; index++) {
  73553. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  73554. }
  73555. // Lens flares
  73556. serializationObject.lensFlareSystems = [];
  73557. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  73558. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  73559. }
  73560. // Shadows
  73561. serializationObject.shadowGenerators = [];
  73562. for (index = 0; index < scene.lights.length; index++) {
  73563. light = scene.lights[index];
  73564. var shadowGenerator = light.getShadowGenerator();
  73565. if (shadowGenerator) {
  73566. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73567. }
  73568. }
  73569. // Action Manager
  73570. if (scene.actionManager) {
  73571. serializationObject.actions = scene.actionManager.serialize("scene");
  73572. }
  73573. // Audio
  73574. serializationObject.sounds = [];
  73575. for (index = 0; index < scene.soundTracks.length; index++) {
  73576. var soundtrack = scene.soundTracks[index];
  73577. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  73578. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  73579. }
  73580. }
  73581. return serializationObject;
  73582. };
  73583. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  73584. if (withParents === void 0) { withParents = false; }
  73585. if (withChildren === void 0) { withChildren = false; }
  73586. var serializationObject = {};
  73587. SceneSerializer.ClearCache();
  73588. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  73589. if (withParents || withChildren) {
  73590. //deliberate for loop! not for each, appended should be processed as well.
  73591. for (var i = 0; i < toSerialize.length; ++i) {
  73592. if (withChildren) {
  73593. toSerialize[i].getDescendants().forEach(function (node) {
  73594. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  73595. toSerialize.push(node);
  73596. }
  73597. });
  73598. }
  73599. //make sure the array doesn't contain the object already
  73600. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  73601. toSerialize.push(toSerialize[i].parent);
  73602. }
  73603. }
  73604. }
  73605. toSerialize.forEach(function (mesh) {
  73606. finalizeSingleMesh(mesh, serializationObject);
  73607. });
  73608. return serializationObject;
  73609. };
  73610. return SceneSerializer;
  73611. }());
  73612. BABYLON.SceneSerializer = SceneSerializer;
  73613. })(BABYLON || (BABYLON = {}));
  73614. //# sourceMappingURL=babylon.sceneSerializer.js.map
  73615. var BABYLON;
  73616. (function (BABYLON) {
  73617. var ReflectionProbe = /** @class */ (function () {
  73618. function ReflectionProbe(name, size, scene, generateMipMaps) {
  73619. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73620. var _this = this;
  73621. this.name = name;
  73622. this._viewMatrix = BABYLON.Matrix.Identity();
  73623. this._target = BABYLON.Vector3.Zero();
  73624. this._add = BABYLON.Vector3.Zero();
  73625. this.invertYAxis = false;
  73626. this.position = BABYLON.Vector3.Zero();
  73627. this._scene = scene;
  73628. this._scene.reflectionProbes.push(this);
  73629. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  73630. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  73631. switch (faceIndex) {
  73632. case 0:
  73633. _this._add.copyFromFloats(1, 0, 0);
  73634. break;
  73635. case 1:
  73636. _this._add.copyFromFloats(-1, 0, 0);
  73637. break;
  73638. case 2:
  73639. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  73640. break;
  73641. case 3:
  73642. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  73643. break;
  73644. case 4:
  73645. _this._add.copyFromFloats(0, 0, 1);
  73646. break;
  73647. case 5:
  73648. _this._add.copyFromFloats(0, 0, -1);
  73649. break;
  73650. }
  73651. if (_this._attachedMesh) {
  73652. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  73653. }
  73654. _this.position.addToRef(_this._add, _this._target);
  73655. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  73656. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  73657. scene._forcedViewPosition = _this.position;
  73658. });
  73659. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  73660. scene._forcedViewPosition = null;
  73661. scene.updateTransformMatrix(true);
  73662. });
  73663. if (scene.activeCamera) {
  73664. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73665. }
  73666. }
  73667. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  73668. get: function () {
  73669. return this._renderTargetTexture.samples;
  73670. },
  73671. set: function (value) {
  73672. this._renderTargetTexture.samples = value;
  73673. },
  73674. enumerable: true,
  73675. configurable: true
  73676. });
  73677. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  73678. get: function () {
  73679. return this._renderTargetTexture.refreshRate;
  73680. },
  73681. set: function (value) {
  73682. this._renderTargetTexture.refreshRate = value;
  73683. },
  73684. enumerable: true,
  73685. configurable: true
  73686. });
  73687. ReflectionProbe.prototype.getScene = function () {
  73688. return this._scene;
  73689. };
  73690. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  73691. get: function () {
  73692. return this._renderTargetTexture;
  73693. },
  73694. enumerable: true,
  73695. configurable: true
  73696. });
  73697. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  73698. get: function () {
  73699. return this._renderTargetTexture.renderList;
  73700. },
  73701. enumerable: true,
  73702. configurable: true
  73703. });
  73704. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  73705. this._attachedMesh = mesh;
  73706. };
  73707. /**
  73708. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73709. *
  73710. * @param renderingGroupId The rendering group id corresponding to its index
  73711. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73712. */
  73713. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73714. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73715. };
  73716. ReflectionProbe.prototype.dispose = function () {
  73717. var index = this._scene.reflectionProbes.indexOf(this);
  73718. if (index !== -1) {
  73719. // Remove from the scene if found
  73720. this._scene.reflectionProbes.splice(index, 1);
  73721. }
  73722. if (this._renderTargetTexture) {
  73723. this._renderTargetTexture.dispose();
  73724. this._renderTargetTexture = null;
  73725. }
  73726. };
  73727. return ReflectionProbe;
  73728. }());
  73729. BABYLON.ReflectionProbe = ReflectionProbe;
  73730. })(BABYLON || (BABYLON = {}));
  73731. //# sourceMappingURL=babylon.reflectionProbe.js.map
  73732. var BABYLON;
  73733. (function (BABYLON) {
  73734. var Layer = /** @class */ (function () {
  73735. function Layer(name, imgUrl, scene, isBackground, color) {
  73736. this.name = name;
  73737. this.scale = new BABYLON.Vector2(1, 1);
  73738. this.offset = new BABYLON.Vector2(0, 0);
  73739. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  73740. this.layerMask = 0x0FFFFFFF;
  73741. this._vertexBuffers = {};
  73742. // Events
  73743. /**
  73744. * An event triggered when the layer is disposed.
  73745. * @type {BABYLON.Observable}
  73746. */
  73747. this.onDisposeObservable = new BABYLON.Observable();
  73748. /**
  73749. * An event triggered before rendering the scene
  73750. * @type {BABYLON.Observable}
  73751. */
  73752. this.onBeforeRenderObservable = new BABYLON.Observable();
  73753. /**
  73754. * An event triggered after rendering the scene
  73755. * @type {BABYLON.Observable}
  73756. */
  73757. this.onAfterRenderObservable = new BABYLON.Observable();
  73758. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  73759. this.isBackground = isBackground === undefined ? true : isBackground;
  73760. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  73761. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  73762. this._scene.layers.push(this);
  73763. var engine = this._scene.getEngine();
  73764. // VBO
  73765. var vertices = [];
  73766. vertices.push(1, 1);
  73767. vertices.push(-1, 1);
  73768. vertices.push(-1, -1);
  73769. vertices.push(1, -1);
  73770. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73771. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73772. this._createIndexBuffer();
  73773. // Effects
  73774. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  73775. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  73776. }
  73777. Object.defineProperty(Layer.prototype, "onDispose", {
  73778. set: function (callback) {
  73779. if (this._onDisposeObserver) {
  73780. this.onDisposeObservable.remove(this._onDisposeObserver);
  73781. }
  73782. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  73783. },
  73784. enumerable: true,
  73785. configurable: true
  73786. });
  73787. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  73788. set: function (callback) {
  73789. if (this._onBeforeRenderObserver) {
  73790. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73791. }
  73792. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73793. },
  73794. enumerable: true,
  73795. configurable: true
  73796. });
  73797. Object.defineProperty(Layer.prototype, "onAfterRender", {
  73798. set: function (callback) {
  73799. if (this._onAfterRenderObserver) {
  73800. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73801. }
  73802. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73803. },
  73804. enumerable: true,
  73805. configurable: true
  73806. });
  73807. Layer.prototype._createIndexBuffer = function () {
  73808. var engine = this._scene.getEngine();
  73809. // Indices
  73810. var indices = [];
  73811. indices.push(0);
  73812. indices.push(1);
  73813. indices.push(2);
  73814. indices.push(0);
  73815. indices.push(2);
  73816. indices.push(3);
  73817. this._indexBuffer = engine.createIndexBuffer(indices);
  73818. };
  73819. Layer.prototype._rebuild = function () {
  73820. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73821. if (vb) {
  73822. vb._rebuild();
  73823. }
  73824. this._createIndexBuffer();
  73825. };
  73826. Layer.prototype.render = function () {
  73827. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  73828. // Check
  73829. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73830. return;
  73831. var engine = this._scene.getEngine();
  73832. this.onBeforeRenderObservable.notifyObservers(this);
  73833. // Render
  73834. engine.enableEffect(currentEffect);
  73835. engine.setState(false);
  73836. // Texture
  73837. currentEffect.setTexture("textureSampler", this.texture);
  73838. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73839. // Color
  73840. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73841. // Scale / offset
  73842. currentEffect.setVector2("offset", this.offset);
  73843. currentEffect.setVector2("scale", this.scale);
  73844. // VBOs
  73845. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73846. // Draw order
  73847. if (!this.alphaTest) {
  73848. engine.setAlphaMode(this.alphaBlendingMode);
  73849. engine.draw(true, 0, 6);
  73850. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73851. }
  73852. else {
  73853. engine.draw(true, 0, 6);
  73854. }
  73855. this.onAfterRenderObservable.notifyObservers(this);
  73856. };
  73857. Layer.prototype.dispose = function () {
  73858. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73859. if (vertexBuffer) {
  73860. vertexBuffer.dispose();
  73861. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73862. }
  73863. if (this._indexBuffer) {
  73864. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73865. this._indexBuffer = null;
  73866. }
  73867. if (this.texture) {
  73868. this.texture.dispose();
  73869. this.texture = null;
  73870. }
  73871. // Remove from scene
  73872. var index = this._scene.layers.indexOf(this);
  73873. this._scene.layers.splice(index, 1);
  73874. // Callback
  73875. this.onDisposeObservable.notifyObservers(this);
  73876. this.onDisposeObservable.clear();
  73877. this.onAfterRenderObservable.clear();
  73878. this.onBeforeRenderObservable.clear();
  73879. };
  73880. return Layer;
  73881. }());
  73882. BABYLON.Layer = Layer;
  73883. })(BABYLON || (BABYLON = {}));
  73884. //# sourceMappingURL=babylon.layer.js.map
  73885. var BABYLON;
  73886. (function (BABYLON) {
  73887. var TextureTools = /** @class */ (function () {
  73888. function TextureTools() {
  73889. }
  73890. /**
  73891. * Uses the GPU to create a copy texture rescaled at a given size
  73892. * @param texture Texture to copy from
  73893. * @param width Desired width
  73894. * @param height Desired height
  73895. * @return Generated texture
  73896. */
  73897. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73898. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73899. var scene = texture.getScene();
  73900. var engine = scene.getEngine();
  73901. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73902. rtt.wrapU = texture.wrapU;
  73903. rtt.wrapV = texture.wrapV;
  73904. rtt.uOffset = texture.uOffset;
  73905. rtt.vOffset = texture.vOffset;
  73906. rtt.uScale = texture.uScale;
  73907. rtt.vScale = texture.vScale;
  73908. rtt.uAng = texture.uAng;
  73909. rtt.vAng = texture.vAng;
  73910. rtt.wAng = texture.wAng;
  73911. rtt.coordinatesIndex = texture.coordinatesIndex;
  73912. rtt.level = texture.level;
  73913. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73914. rtt._texture.isReady = false;
  73915. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73916. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73917. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73918. passPostProcess.getEffect().executeWhenCompiled(function () {
  73919. passPostProcess.onApply = function (effect) {
  73920. effect.setTexture("textureSampler", texture);
  73921. };
  73922. var internalTexture = rtt.getInternalTexture();
  73923. if (internalTexture) {
  73924. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73925. engine.unBindFramebuffer(internalTexture);
  73926. rtt.disposeFramebufferObjects();
  73927. passPostProcess.dispose();
  73928. internalTexture.isReady = true;
  73929. }
  73930. });
  73931. return rtt;
  73932. };
  73933. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73934. if (!scene._environmentBRDFTexture) {
  73935. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73936. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73937. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73938. scene._environmentBRDFTexture = texture;
  73939. }
  73940. return scene._environmentBRDFTexture;
  73941. };
  73942. 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=";
  73943. return TextureTools;
  73944. }());
  73945. BABYLON.TextureTools = TextureTools;
  73946. })(BABYLON || (BABYLON = {}));
  73947. //# sourceMappingURL=babylon.textureTools.js.map
  73948. var BABYLON;
  73949. (function (BABYLON) {
  73950. var FramingBehavior = /** @class */ (function () {
  73951. function FramingBehavior() {
  73952. this._mode = FramingBehavior.FitFrustumSidesMode;
  73953. this._radiusScale = 1.0;
  73954. this._positionScale = 0.5;
  73955. this._defaultElevation = 0.3;
  73956. this._elevationReturnTime = 1500;
  73957. this._elevationReturnWaitTime = 1000;
  73958. this._zoomStopsAnimation = false;
  73959. this._framingTime = 1500;
  73960. this._isPointerDown = false;
  73961. this._lastInteractionTime = -Infinity;
  73962. // Framing control
  73963. this._animatables = new Array();
  73964. this._betaIsAnimating = false;
  73965. }
  73966. Object.defineProperty(FramingBehavior.prototype, "name", {
  73967. get: function () {
  73968. return "Framing";
  73969. },
  73970. enumerable: true,
  73971. configurable: true
  73972. });
  73973. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73974. /**
  73975. * Gets current mode used by the behavior.
  73976. */
  73977. get: function () {
  73978. return this._mode;
  73979. },
  73980. /**
  73981. * Sets the current mode used by the behavior
  73982. */
  73983. set: function (mode) {
  73984. this._mode = mode;
  73985. },
  73986. enumerable: true,
  73987. configurable: true
  73988. });
  73989. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73990. /**
  73991. * Gets the scale applied to the radius
  73992. */
  73993. get: function () {
  73994. return this._radiusScale;
  73995. },
  73996. /**
  73997. * Sets the scale applied to the radius (1 by default)
  73998. */
  73999. set: function (radius) {
  74000. this._radiusScale = radius;
  74001. },
  74002. enumerable: true,
  74003. configurable: true
  74004. });
  74005. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  74006. /**
  74007. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  74008. */
  74009. get: function () {
  74010. return this._positionScale;
  74011. },
  74012. /**
  74013. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  74014. */
  74015. set: function (scale) {
  74016. this._positionScale = scale;
  74017. },
  74018. enumerable: true,
  74019. configurable: true
  74020. });
  74021. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  74022. /**
  74023. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  74024. * behaviour is triggered, in radians.
  74025. */
  74026. get: function () {
  74027. return this._defaultElevation;
  74028. },
  74029. /**
  74030. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  74031. * behaviour is triggered, in radians.
  74032. */
  74033. set: function (elevation) {
  74034. this._defaultElevation = elevation;
  74035. },
  74036. enumerable: true,
  74037. configurable: true
  74038. });
  74039. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  74040. /**
  74041. * Gets the time (in milliseconds) taken to return to the default beta position.
  74042. * Negative value indicates camera should not return to default.
  74043. */
  74044. get: function () {
  74045. return this._elevationReturnTime;
  74046. },
  74047. /**
  74048. * Sets the time (in milliseconds) taken to return to the default beta position.
  74049. * Negative value indicates camera should not return to default.
  74050. */
  74051. set: function (speed) {
  74052. this._elevationReturnTime = speed;
  74053. },
  74054. enumerable: true,
  74055. configurable: true
  74056. });
  74057. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  74058. /**
  74059. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  74060. */
  74061. get: function () {
  74062. return this._elevationReturnWaitTime;
  74063. },
  74064. /**
  74065. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  74066. */
  74067. set: function (time) {
  74068. this._elevationReturnWaitTime = time;
  74069. },
  74070. enumerable: true,
  74071. configurable: true
  74072. });
  74073. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  74074. /**
  74075. * Gets the flag that indicates if user zooming should stop animation.
  74076. */
  74077. get: function () {
  74078. return this._zoomStopsAnimation;
  74079. },
  74080. /**
  74081. * Sets the flag that indicates if user zooming should stop animation.
  74082. */
  74083. set: function (flag) {
  74084. this._zoomStopsAnimation = flag;
  74085. },
  74086. enumerable: true,
  74087. configurable: true
  74088. });
  74089. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  74090. /**
  74091. * Gets the transition time when framing the mesh, in milliseconds
  74092. */
  74093. get: function () {
  74094. return this._framingTime;
  74095. },
  74096. /**
  74097. * Sets the transition time when framing the mesh, in milliseconds
  74098. */
  74099. set: function (time) {
  74100. this._framingTime = time;
  74101. },
  74102. enumerable: true,
  74103. configurable: true
  74104. });
  74105. FramingBehavior.prototype.init = function () {
  74106. // Do notihng
  74107. };
  74108. FramingBehavior.prototype.attach = function (camera) {
  74109. var _this = this;
  74110. this._attachedCamera = camera;
  74111. var scene = this._attachedCamera.getScene();
  74112. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  74113. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74114. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74115. _this._isPointerDown = true;
  74116. return;
  74117. }
  74118. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74119. _this._isPointerDown = false;
  74120. }
  74121. });
  74122. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  74123. if (mesh) {
  74124. _this.zoomOnMesh(mesh);
  74125. }
  74126. });
  74127. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74128. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74129. _this._applyUserInteraction();
  74130. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  74131. // back to the default position after a given timeout
  74132. _this._maintainCameraAboveGround();
  74133. });
  74134. };
  74135. FramingBehavior.prototype.detach = function () {
  74136. if (!this._attachedCamera) {
  74137. return;
  74138. }
  74139. var scene = this._attachedCamera.getScene();
  74140. if (this._onPrePointerObservableObserver) {
  74141. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74142. }
  74143. if (this._onAfterCheckInputsObserver) {
  74144. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74145. }
  74146. if (this._onMeshTargetChangedObserver) {
  74147. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74148. }
  74149. this._attachedCamera = null;
  74150. };
  74151. /**
  74152. * Targets the given mesh and updates zoom level accordingly.
  74153. * @param mesh The mesh to target.
  74154. * @param radius Optional. If a cached radius position already exists, overrides default.
  74155. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  74156. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  74157. * @param onAnimationEnd Callback triggered at the end of the framing animation
  74158. */
  74159. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  74160. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  74161. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  74162. mesh.computeWorldMatrix(true);
  74163. var boundingBox = mesh.getBoundingInfo().boundingBox;
  74164. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  74165. };
  74166. /**
  74167. * Targets the given mesh and updates zoom level accordingly.
  74168. * @param mesh The mesh to target.
  74169. * @param radius Optional. If a cached radius position already exists, overrides default.
  74170. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  74171. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  74172. * @param onAnimationEnd Callback triggered at the end of the framing animation
  74173. */
  74174. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  74175. var _this = this;
  74176. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  74177. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  74178. var zoomTarget;
  74179. if (!this._attachedCamera) {
  74180. return;
  74181. }
  74182. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  74183. var bottom = minimumWorld.y;
  74184. var top = maximumWorld.y;
  74185. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  74186. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  74187. if (focusOnOriginXZ) {
  74188. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  74189. }
  74190. else {
  74191. var centerWorld = minimumWorld.add(radiusWorld);
  74192. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  74193. }
  74194. if (!this._vectorTransition) {
  74195. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  74196. }
  74197. this._betaIsAnimating = true;
  74198. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  74199. if (animatable) {
  74200. this._animatables.push(animatable);
  74201. }
  74202. // sets the radius and lower radius bounds
  74203. // Small delta ensures camera is not always at lower zoom limit.
  74204. var radius = 0;
  74205. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  74206. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  74207. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  74208. radius = position;
  74209. }
  74210. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  74211. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  74212. if (this._attachedCamera.lowerRadiusLimit === null) {
  74213. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  74214. }
  74215. }
  74216. // Set sensibilities
  74217. var extend = maximumWorld.subtract(minimumWorld).length();
  74218. this._attachedCamera.panningSensibility = 5000 / extend;
  74219. this._attachedCamera.wheelPrecision = 100 / radius;
  74220. // transition to new radius
  74221. if (!this._radiusTransition) {
  74222. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  74223. }
  74224. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  74225. if (onAnimationEnd) {
  74226. onAnimationEnd();
  74227. }
  74228. if (_this._attachedCamera) {
  74229. _this._attachedCamera.storeState();
  74230. }
  74231. });
  74232. if (animatable) {
  74233. this._animatables.push(animatable);
  74234. }
  74235. };
  74236. /**
  74237. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  74238. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  74239. * frustum width.
  74240. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  74241. * to fully enclose the mesh in the viewing frustum.
  74242. */
  74243. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  74244. var size = maximumWorld.subtract(minimumWorld);
  74245. var boxVectorGlobalDiagonal = size.length();
  74246. var frustumSlope = this._getFrustumSlope();
  74247. // Formula for setting distance
  74248. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  74249. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  74250. // Horizon distance
  74251. var radius = radiusWithoutFraming * this._radiusScale;
  74252. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  74253. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  74254. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  74255. var camera = this._attachedCamera;
  74256. if (!camera) {
  74257. return 0;
  74258. }
  74259. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  74260. // Don't exceed the requested limit
  74261. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  74262. }
  74263. // Don't exceed the upper radius limit
  74264. if (camera.upperRadiusLimit) {
  74265. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  74266. }
  74267. return distance;
  74268. };
  74269. /**
  74270. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  74271. * is automatically returned to its default position (expected to be above ground plane).
  74272. */
  74273. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  74274. var _this = this;
  74275. if (this._elevationReturnTime < 0) {
  74276. return;
  74277. }
  74278. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  74279. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  74280. var limitBeta = Math.PI * 0.5;
  74281. // Bring the camera back up if below the ground plane
  74282. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  74283. this._betaIsAnimating = true;
  74284. //Transition to new position
  74285. this.stopAllAnimations();
  74286. if (!this._betaTransition) {
  74287. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  74288. }
  74289. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  74290. _this._clearAnimationLocks();
  74291. _this.stopAllAnimations();
  74292. });
  74293. if (animatabe) {
  74294. this._animatables.push(animatabe);
  74295. }
  74296. }
  74297. };
  74298. /**
  74299. * Returns the frustum slope based on the canvas ratio and camera FOV
  74300. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  74301. */
  74302. FramingBehavior.prototype._getFrustumSlope = function () {
  74303. // Calculate the viewport ratio
  74304. // Aspect Ratio is Height/Width.
  74305. var camera = this._attachedCamera;
  74306. if (!camera) {
  74307. return BABYLON.Vector2.Zero();
  74308. }
  74309. var engine = camera.getScene().getEngine();
  74310. var aspectRatio = engine.getAspectRatio(camera);
  74311. // Camera FOV is the vertical field of view (top-bottom) in radians.
  74312. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  74313. var frustumSlopeY = Math.tan(camera.fov / 2);
  74314. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  74315. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  74316. // along the forward vector.
  74317. var frustumSlopeX = frustumSlopeY * aspectRatio;
  74318. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  74319. };
  74320. /**
  74321. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  74322. */
  74323. FramingBehavior.prototype._clearAnimationLocks = function () {
  74324. this._betaIsAnimating = false;
  74325. };
  74326. /**
  74327. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74328. */
  74329. FramingBehavior.prototype._applyUserInteraction = function () {
  74330. if (this.isUserIsMoving) {
  74331. this._lastInteractionTime = BABYLON.Tools.Now;
  74332. this.stopAllAnimations();
  74333. this._clearAnimationLocks();
  74334. }
  74335. };
  74336. /**
  74337. * Stops and removes all animations that have been applied to the camera
  74338. */
  74339. FramingBehavior.prototype.stopAllAnimations = function () {
  74340. if (this._attachedCamera) {
  74341. this._attachedCamera.animations = [];
  74342. }
  74343. while (this._animatables.length) {
  74344. if (this._animatables[0]) {
  74345. this._animatables[0].onAnimationEnd = null;
  74346. this._animatables[0].stop();
  74347. }
  74348. this._animatables.shift();
  74349. }
  74350. };
  74351. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  74352. /**
  74353. * Gets a value indicating if the user is moving the camera
  74354. */
  74355. get: function () {
  74356. if (!this._attachedCamera) {
  74357. return false;
  74358. }
  74359. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74360. this._attachedCamera.inertialBetaOffset !== 0 ||
  74361. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74362. this._attachedCamera.inertialPanningX !== 0 ||
  74363. this._attachedCamera.inertialPanningY !== 0 ||
  74364. this._isPointerDown;
  74365. },
  74366. enumerable: true,
  74367. configurable: true
  74368. });
  74369. /**
  74370. * The easing function used by animations
  74371. */
  74372. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  74373. /**
  74374. * The easing mode used by animations
  74375. */
  74376. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  74377. // Statics
  74378. /**
  74379. * The camera can move all the way towards the mesh.
  74380. */
  74381. FramingBehavior.IgnoreBoundsSizeMode = 0;
  74382. /**
  74383. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  74384. */
  74385. FramingBehavior.FitFrustumSidesMode = 1;
  74386. return FramingBehavior;
  74387. }());
  74388. BABYLON.FramingBehavior = FramingBehavior;
  74389. })(BABYLON || (BABYLON = {}));
  74390. //# sourceMappingURL=babylon.framingBehavior.js.map
  74391. var BABYLON;
  74392. (function (BABYLON) {
  74393. /**
  74394. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  74395. */
  74396. var BouncingBehavior = /** @class */ (function () {
  74397. function BouncingBehavior() {
  74398. /**
  74399. * The duration of the animation, in milliseconds
  74400. */
  74401. this.transitionDuration = 450;
  74402. /**
  74403. * Length of the distance animated by the transition when lower radius is reached
  74404. */
  74405. this.lowerRadiusTransitionRange = 2;
  74406. /**
  74407. * Length of the distance animated by the transition when upper radius is reached
  74408. */
  74409. this.upperRadiusTransitionRange = -2;
  74410. this._autoTransitionRange = false;
  74411. // Animations
  74412. this._radiusIsAnimating = false;
  74413. this._radiusBounceTransition = null;
  74414. this._animatables = new Array();
  74415. }
  74416. Object.defineProperty(BouncingBehavior.prototype, "name", {
  74417. get: function () {
  74418. return "Bouncing";
  74419. },
  74420. enumerable: true,
  74421. configurable: true
  74422. });
  74423. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  74424. /**
  74425. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74426. */
  74427. get: function () {
  74428. return this._autoTransitionRange;
  74429. },
  74430. /**
  74431. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74432. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  74433. */
  74434. set: function (value) {
  74435. var _this = this;
  74436. if (this._autoTransitionRange === value) {
  74437. return;
  74438. }
  74439. this._autoTransitionRange = value;
  74440. var camera = this._attachedCamera;
  74441. if (!camera) {
  74442. return;
  74443. }
  74444. if (value) {
  74445. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  74446. if (!mesh) {
  74447. return;
  74448. }
  74449. mesh.computeWorldMatrix(true);
  74450. var diagonal = mesh.getBoundingInfo().diagonalLength;
  74451. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  74452. _this.upperRadiusTransitionRange = diagonal * 0.05;
  74453. });
  74454. }
  74455. else if (this._onMeshTargetChangedObserver) {
  74456. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74457. }
  74458. },
  74459. enumerable: true,
  74460. configurable: true
  74461. });
  74462. BouncingBehavior.prototype.init = function () {
  74463. // Do notihng
  74464. };
  74465. BouncingBehavior.prototype.attach = function (camera) {
  74466. var _this = this;
  74467. this._attachedCamera = camera;
  74468. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74469. if (!_this._attachedCamera) {
  74470. return;
  74471. }
  74472. // Add the bounce animation to the lower radius limit
  74473. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  74474. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  74475. }
  74476. // Add the bounce animation to the upper radius limit
  74477. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  74478. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  74479. }
  74480. });
  74481. };
  74482. BouncingBehavior.prototype.detach = function () {
  74483. if (!this._attachedCamera) {
  74484. return;
  74485. }
  74486. if (this._onAfterCheckInputsObserver) {
  74487. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74488. }
  74489. if (this._onMeshTargetChangedObserver) {
  74490. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74491. }
  74492. this._attachedCamera = null;
  74493. };
  74494. /**
  74495. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  74496. * @param radiusLimit The limit to check against.
  74497. * @return Bool to indicate if at limit.
  74498. */
  74499. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  74500. if (!this._attachedCamera) {
  74501. return false;
  74502. }
  74503. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  74504. return true;
  74505. }
  74506. return false;
  74507. };
  74508. /**
  74509. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  74510. * @param radiusDelta The delta by which to animate to. Can be negative.
  74511. */
  74512. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  74513. var _this = this;
  74514. if (!this._attachedCamera) {
  74515. return;
  74516. }
  74517. if (!this._radiusBounceTransition) {
  74518. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  74519. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  74520. }
  74521. // Prevent zoom until bounce has completed
  74522. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  74523. this._attachedCamera.wheelPrecision = Infinity;
  74524. this._attachedCamera.inertialRadiusOffset = 0;
  74525. // Animate to the radius limit
  74526. this.stopAllAnimations();
  74527. this._radiusIsAnimating = true;
  74528. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  74529. if (animatable) {
  74530. this._animatables.push(animatable);
  74531. }
  74532. };
  74533. /**
  74534. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  74535. */
  74536. BouncingBehavior.prototype._clearAnimationLocks = function () {
  74537. this._radiusIsAnimating = false;
  74538. if (this._attachedCamera) {
  74539. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  74540. }
  74541. };
  74542. /**
  74543. * Stops and removes all animations that have been applied to the camera
  74544. */
  74545. BouncingBehavior.prototype.stopAllAnimations = function () {
  74546. if (this._attachedCamera) {
  74547. this._attachedCamera.animations = [];
  74548. }
  74549. while (this._animatables.length) {
  74550. this._animatables[0].onAnimationEnd = null;
  74551. this._animatables[0].stop();
  74552. this._animatables.shift();
  74553. }
  74554. };
  74555. /**
  74556. * The easing function used by animations
  74557. */
  74558. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  74559. /**
  74560. * The easing mode used by animations
  74561. */
  74562. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  74563. return BouncingBehavior;
  74564. }());
  74565. BABYLON.BouncingBehavior = BouncingBehavior;
  74566. })(BABYLON || (BABYLON = {}));
  74567. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  74568. var BABYLON;
  74569. (function (BABYLON) {
  74570. var AutoRotationBehavior = /** @class */ (function () {
  74571. function AutoRotationBehavior() {
  74572. this._zoomStopsAnimation = false;
  74573. this._idleRotationSpeed = 0.05;
  74574. this._idleRotationWaitTime = 2000;
  74575. this._idleRotationSpinupTime = 2000;
  74576. this._isPointerDown = false;
  74577. this._lastFrameTime = null;
  74578. this._lastInteractionTime = -Infinity;
  74579. this._cameraRotationSpeed = 0;
  74580. this._lastFrameRadius = 0;
  74581. }
  74582. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  74583. get: function () {
  74584. return "AutoRotation";
  74585. },
  74586. enumerable: true,
  74587. configurable: true
  74588. });
  74589. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  74590. /**
  74591. * Gets the flag that indicates if user zooming should stop animation.
  74592. */
  74593. get: function () {
  74594. return this._zoomStopsAnimation;
  74595. },
  74596. /**
  74597. * Sets the flag that indicates if user zooming should stop animation.
  74598. */
  74599. set: function (flag) {
  74600. this._zoomStopsAnimation = flag;
  74601. },
  74602. enumerable: true,
  74603. configurable: true
  74604. });
  74605. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  74606. /**
  74607. * Gets the default speed at which the camera rotates around the model.
  74608. */
  74609. get: function () {
  74610. return this._idleRotationSpeed;
  74611. },
  74612. /**
  74613. * Sets the default speed at which the camera rotates around the model.
  74614. */
  74615. set: function (speed) {
  74616. this._idleRotationSpeed = speed;
  74617. },
  74618. enumerable: true,
  74619. configurable: true
  74620. });
  74621. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  74622. /**
  74623. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  74624. */
  74625. get: function () {
  74626. return this._idleRotationWaitTime;
  74627. },
  74628. /**
  74629. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  74630. */
  74631. set: function (time) {
  74632. this._idleRotationWaitTime = time;
  74633. },
  74634. enumerable: true,
  74635. configurable: true
  74636. });
  74637. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  74638. /**
  74639. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74640. */
  74641. get: function () {
  74642. return this._idleRotationSpinupTime;
  74643. },
  74644. /**
  74645. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74646. */
  74647. set: function (time) {
  74648. this._idleRotationSpinupTime = time;
  74649. },
  74650. enumerable: true,
  74651. configurable: true
  74652. });
  74653. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  74654. /**
  74655. * Gets a value indicating if the camera is currently rotating because of this behavior
  74656. */
  74657. get: function () {
  74658. return Math.abs(this._cameraRotationSpeed) > 0;
  74659. },
  74660. enumerable: true,
  74661. configurable: true
  74662. });
  74663. AutoRotationBehavior.prototype.init = function () {
  74664. // Do notihng
  74665. };
  74666. AutoRotationBehavior.prototype.attach = function (camera) {
  74667. var _this = this;
  74668. this._attachedCamera = camera;
  74669. var scene = this._attachedCamera.getScene();
  74670. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74671. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74672. _this._isPointerDown = true;
  74673. return;
  74674. }
  74675. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74676. _this._isPointerDown = false;
  74677. }
  74678. });
  74679. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74680. var now = BABYLON.Tools.Now;
  74681. var dt = 0;
  74682. if (_this._lastFrameTime != null) {
  74683. dt = now - _this._lastFrameTime;
  74684. }
  74685. _this._lastFrameTime = now;
  74686. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74687. _this._applyUserInteraction();
  74688. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  74689. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  74690. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  74691. // Step camera rotation by rotation speed
  74692. if (_this._attachedCamera) {
  74693. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  74694. }
  74695. });
  74696. };
  74697. AutoRotationBehavior.prototype.detach = function () {
  74698. if (!this._attachedCamera) {
  74699. return;
  74700. }
  74701. var scene = this._attachedCamera.getScene();
  74702. if (this._onPrePointerObservableObserver) {
  74703. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74704. }
  74705. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74706. this._attachedCamera = null;
  74707. };
  74708. /**
  74709. * Returns true if user is scrolling.
  74710. * @return true if user is scrolling.
  74711. */
  74712. AutoRotationBehavior.prototype._userIsZooming = function () {
  74713. if (!this._attachedCamera) {
  74714. return false;
  74715. }
  74716. return this._attachedCamera.inertialRadiusOffset !== 0;
  74717. };
  74718. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  74719. if (!this._attachedCamera) {
  74720. return false;
  74721. }
  74722. var zoomHasHitLimit = false;
  74723. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  74724. zoomHasHitLimit = true;
  74725. }
  74726. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  74727. this._lastFrameRadius = this._attachedCamera.radius;
  74728. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  74729. };
  74730. /**
  74731. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74732. */
  74733. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  74734. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  74735. this._lastInteractionTime = BABYLON.Tools.Now;
  74736. }
  74737. };
  74738. // Tools
  74739. AutoRotationBehavior.prototype._userIsMoving = function () {
  74740. if (!this._attachedCamera) {
  74741. return false;
  74742. }
  74743. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74744. this._attachedCamera.inertialBetaOffset !== 0 ||
  74745. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74746. this._attachedCamera.inertialPanningX !== 0 ||
  74747. this._attachedCamera.inertialPanningY !== 0 ||
  74748. this._isPointerDown;
  74749. };
  74750. return AutoRotationBehavior;
  74751. }());
  74752. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  74753. })(BABYLON || (BABYLON = {}));
  74754. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  74755. var BABYLON;
  74756. (function (BABYLON) {
  74757. var NullEngineOptions = /** @class */ (function () {
  74758. function NullEngineOptions() {
  74759. this.renderWidth = 512;
  74760. this.renderHeight = 256;
  74761. this.textureSize = 512;
  74762. }
  74763. return NullEngineOptions;
  74764. }());
  74765. BABYLON.NullEngineOptions = NullEngineOptions;
  74766. /**
  74767. * The null engine class provides support for headless version of babylon.js.
  74768. * This can be used in server side scenario or for testing purposes
  74769. */
  74770. var NullEngine = /** @class */ (function (_super) {
  74771. __extends(NullEngine, _super);
  74772. function NullEngine(options) {
  74773. if (options === void 0) { options = new NullEngineOptions(); }
  74774. var _this = _super.call(this, null) || this;
  74775. _this._options = options;
  74776. // Init caps
  74777. // We consider we are on a webgl1 capable device
  74778. _this._caps = new BABYLON.EngineCapabilities();
  74779. _this._caps.maxTexturesImageUnits = 16;
  74780. _this._caps.maxVertexTextureImageUnits = 16;
  74781. _this._caps.maxTextureSize = 512;
  74782. _this._caps.maxCubemapTextureSize = 512;
  74783. _this._caps.maxRenderTextureSize = 512;
  74784. _this._caps.maxVertexAttribs = 16;
  74785. _this._caps.maxVaryingVectors = 16;
  74786. _this._caps.maxFragmentUniformVectors = 16;
  74787. _this._caps.maxVertexUniformVectors = 16;
  74788. // Extensions
  74789. _this._caps.standardDerivatives = false;
  74790. _this._caps.astc = null;
  74791. _this._caps.s3tc = null;
  74792. _this._caps.pvrtc = null;
  74793. _this._caps.etc1 = null;
  74794. _this._caps.etc2 = null;
  74795. _this._caps.textureAnisotropicFilterExtension = null;
  74796. _this._caps.maxAnisotropy = 0;
  74797. _this._caps.uintIndices = false;
  74798. _this._caps.fragmentDepthSupported = false;
  74799. _this._caps.highPrecisionShaderSupported = true;
  74800. _this._caps.colorBufferFloat = false;
  74801. _this._caps.textureFloat = false;
  74802. _this._caps.textureFloatLinearFiltering = false;
  74803. _this._caps.textureFloatRender = false;
  74804. _this._caps.textureHalfFloat = false;
  74805. _this._caps.textureHalfFloatLinearFiltering = false;
  74806. _this._caps.textureHalfFloatRender = false;
  74807. _this._caps.textureLOD = false;
  74808. _this._caps.drawBuffersExtension = false;
  74809. _this._caps.depthTextureExtension = false;
  74810. _this._caps.vertexArrayObject = false;
  74811. _this._caps.instancedArrays = false;
  74812. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  74813. // Wrappers
  74814. if (typeof URL === "undefined") {
  74815. URL = {
  74816. createObjectURL: function () { },
  74817. revokeObjectURL: function () { }
  74818. };
  74819. }
  74820. if (typeof Blob === "undefined") {
  74821. Blob = function () { };
  74822. }
  74823. return _this;
  74824. }
  74825. NullEngine.prototype.createVertexBuffer = function (vertices) {
  74826. return {
  74827. capacity: 0,
  74828. references: 1,
  74829. is32Bits: false
  74830. };
  74831. };
  74832. NullEngine.prototype.createIndexBuffer = function (indices) {
  74833. return {
  74834. capacity: 0,
  74835. references: 1,
  74836. is32Bits: false
  74837. };
  74838. };
  74839. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  74840. if (stencil === void 0) { stencil = false; }
  74841. };
  74842. NullEngine.prototype.getRenderWidth = function (useScreen) {
  74843. if (useScreen === void 0) { useScreen = false; }
  74844. if (!useScreen && this._currentRenderTarget) {
  74845. return this._currentRenderTarget.width;
  74846. }
  74847. return this._options.renderWidth;
  74848. };
  74849. NullEngine.prototype.getRenderHeight = function (useScreen) {
  74850. if (useScreen === void 0) { useScreen = false; }
  74851. if (!useScreen && this._currentRenderTarget) {
  74852. return this._currentRenderTarget.height;
  74853. }
  74854. return this._options.renderHeight;
  74855. };
  74856. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  74857. this._cachedViewport = viewport;
  74858. };
  74859. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  74860. return {
  74861. transformFeedback: null,
  74862. __SPECTOR_rebuildProgram: null
  74863. };
  74864. };
  74865. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  74866. return [];
  74867. };
  74868. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  74869. return [];
  74870. };
  74871. NullEngine.prototype.bindSamplers = function (effect) {
  74872. this._currentEffect = null;
  74873. };
  74874. NullEngine.prototype.enableEffect = function (effect) {
  74875. this._currentEffect = effect;
  74876. if (effect.onBind) {
  74877. effect.onBind(effect);
  74878. }
  74879. effect.onBindObservable.notifyObservers(effect);
  74880. };
  74881. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  74882. if (zOffset === void 0) { zOffset = 0; }
  74883. if (reverseSide === void 0) { reverseSide = false; }
  74884. };
  74885. NullEngine.prototype.setIntArray = function (uniform, array) {
  74886. };
  74887. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  74888. };
  74889. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  74890. };
  74891. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  74892. };
  74893. NullEngine.prototype.setFloatArray = function (uniform, array) {
  74894. };
  74895. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  74896. };
  74897. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  74898. };
  74899. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  74900. };
  74901. NullEngine.prototype.setArray = function (uniform, array) {
  74902. };
  74903. NullEngine.prototype.setArray2 = function (uniform, array) {
  74904. };
  74905. NullEngine.prototype.setArray3 = function (uniform, array) {
  74906. };
  74907. NullEngine.prototype.setArray4 = function (uniform, array) {
  74908. };
  74909. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  74910. };
  74911. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  74912. };
  74913. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  74914. };
  74915. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  74916. };
  74917. NullEngine.prototype.setFloat = function (uniform, value) {
  74918. };
  74919. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  74920. };
  74921. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  74922. };
  74923. NullEngine.prototype.setBool = function (uniform, bool) {
  74924. };
  74925. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  74926. };
  74927. NullEngine.prototype.setColor3 = function (uniform, color3) {
  74928. };
  74929. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  74930. };
  74931. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  74932. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  74933. if (this._alphaMode === mode) {
  74934. return;
  74935. }
  74936. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  74937. if (!noDepthWriteChange) {
  74938. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  74939. }
  74940. this._alphaMode = mode;
  74941. };
  74942. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  74943. };
  74944. NullEngine.prototype.wipeCaches = function (bruteForce) {
  74945. if (this.preventCacheWipeBetweenFrames) {
  74946. return;
  74947. }
  74948. this.resetTextureCache();
  74949. this._currentEffect = null;
  74950. if (bruteForce) {
  74951. this._currentProgram = null;
  74952. this._stencilState.reset();
  74953. this._depthCullingState.reset();
  74954. this.setDepthFunctionToLessOrEqual();
  74955. this._alphaState.reset();
  74956. }
  74957. this._cachedVertexBuffers = null;
  74958. this._cachedIndexBuffer = null;
  74959. this._cachedEffectForVertexBuffers = null;
  74960. };
  74961. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  74962. };
  74963. NullEngine.prototype._createTexture = function () {
  74964. return {};
  74965. };
  74966. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  74967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74968. if (onLoad === void 0) { onLoad = null; }
  74969. if (onError === void 0) { onError = null; }
  74970. if (buffer === void 0) { buffer = null; }
  74971. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  74972. var url = String(urlArg);
  74973. texture.url = url;
  74974. texture.generateMipMaps = !noMipmap;
  74975. texture.samplingMode = samplingMode;
  74976. texture.invertY = invertY;
  74977. texture.baseWidth = this._options.textureSize;
  74978. texture.baseHeight = this._options.textureSize;
  74979. texture.width = this._options.textureSize;
  74980. texture.height = this._options.textureSize;
  74981. if (format) {
  74982. texture.format = format;
  74983. }
  74984. texture.isReady = true;
  74985. if (onLoad) {
  74986. onLoad();
  74987. }
  74988. return texture;
  74989. };
  74990. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  74991. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  74992. if (options !== undefined && typeof options === "object") {
  74993. fullOptions.generateMipMaps = options.generateMipMaps;
  74994. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  74995. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  74996. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  74997. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  74998. }
  74999. else {
  75000. fullOptions.generateMipMaps = options;
  75001. fullOptions.generateDepthBuffer = true;
  75002. fullOptions.generateStencilBuffer = false;
  75003. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75004. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  75005. }
  75006. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  75007. var width = size.width || size;
  75008. var height = size.height || size;
  75009. texture._depthStencilBuffer = {};
  75010. texture._framebuffer = {};
  75011. texture.baseWidth = width;
  75012. texture.baseHeight = height;
  75013. texture.width = width;
  75014. texture.height = height;
  75015. texture.isReady = true;
  75016. texture.samples = 1;
  75017. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  75018. texture.samplingMode = fullOptions.samplingMode;
  75019. texture.type = fullOptions.type;
  75020. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  75021. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  75022. return texture;
  75023. };
  75024. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  75025. texture.samplingMode = samplingMode;
  75026. };
  75027. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  75028. if (this._currentRenderTarget) {
  75029. this.unBindFramebuffer(this._currentRenderTarget);
  75030. }
  75031. this._currentRenderTarget = texture;
  75032. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  75033. if (this._cachedViewport && !forceFullscreenViewport) {
  75034. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  75035. }
  75036. };
  75037. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  75038. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  75039. this._currentRenderTarget = null;
  75040. if (onBeforeUnbind) {
  75041. if (texture._MSAAFramebuffer) {
  75042. this._currentFramebuffer = texture._framebuffer;
  75043. }
  75044. onBeforeUnbind();
  75045. }
  75046. this._currentFramebuffer = null;
  75047. };
  75048. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  75049. var vbo = {
  75050. capacity: 1,
  75051. references: 1,
  75052. is32Bits: false
  75053. };
  75054. return vbo;
  75055. };
  75056. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  75057. if (offset === void 0) { offset = 0; }
  75058. };
  75059. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  75060. };
  75061. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  75062. if (this._activeTexturesCache[this._activeTextureChannel] !== texture) {
  75063. this._activeTexturesCache[this._activeTextureChannel] = texture;
  75064. }
  75065. };
  75066. NullEngine.prototype._bindTexture = function (channel, texture) {
  75067. if (channel < 0) {
  75068. return;
  75069. }
  75070. this._bindTextureDirectly(0, texture);
  75071. };
  75072. return NullEngine;
  75073. }(BABYLON.Engine));
  75074. BABYLON.NullEngine = NullEngine;
  75075. })(BABYLON || (BABYLON = {}));
  75076. //# sourceMappingURL=babylon.nullEngine.js.map
  75077. var BABYLON;
  75078. (function (BABYLON) {
  75079. /**
  75080. * This class can be used to get instrumentation data from a Babylon engine
  75081. */
  75082. var EngineInstrumentation = /** @class */ (function () {
  75083. function EngineInstrumentation(engine) {
  75084. this.engine = engine;
  75085. this._captureGPUFrameTime = false;
  75086. this._gpuFrameTime = new BABYLON.PerfCounter();
  75087. this._captureShaderCompilationTime = false;
  75088. this._shaderCompilationTime = new BABYLON.PerfCounter();
  75089. // Observers
  75090. this._onBeginFrameObserver = null;
  75091. this._onEndFrameObserver = null;
  75092. this._onBeforeShaderCompilationObserver = null;
  75093. this._onAfterShaderCompilationObserver = null;
  75094. }
  75095. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  75096. // Properties
  75097. /**
  75098. * Gets the perf counter used for GPU frame time
  75099. */
  75100. get: function () {
  75101. return this._gpuFrameTime;
  75102. },
  75103. enumerable: true,
  75104. configurable: true
  75105. });
  75106. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  75107. /**
  75108. * Gets the GPU frame time capture status
  75109. */
  75110. get: function () {
  75111. return this._captureGPUFrameTime;
  75112. },
  75113. /**
  75114. * Enable or disable the GPU frame time capture
  75115. */
  75116. set: function (value) {
  75117. var _this = this;
  75118. if (value === this._captureGPUFrameTime) {
  75119. return;
  75120. }
  75121. this._captureGPUFrameTime = value;
  75122. if (value) {
  75123. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  75124. if (!_this._gpuFrameTimeToken) {
  75125. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  75126. }
  75127. });
  75128. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  75129. if (!_this._gpuFrameTimeToken) {
  75130. return;
  75131. }
  75132. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  75133. if (time > -1) {
  75134. _this._gpuFrameTimeToken = null;
  75135. _this._gpuFrameTime.fetchNewFrame();
  75136. _this._gpuFrameTime.addCount(time, true);
  75137. }
  75138. });
  75139. }
  75140. else {
  75141. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  75142. this._onBeginFrameObserver = null;
  75143. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  75144. this._onEndFrameObserver = null;
  75145. }
  75146. },
  75147. enumerable: true,
  75148. configurable: true
  75149. });
  75150. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  75151. /**
  75152. * Gets the perf counter used for shader compilation time
  75153. */
  75154. get: function () {
  75155. return this._shaderCompilationTime;
  75156. },
  75157. enumerable: true,
  75158. configurable: true
  75159. });
  75160. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  75161. /**
  75162. * Gets the shader compilation time capture status
  75163. */
  75164. get: function () {
  75165. return this._captureShaderCompilationTime;
  75166. },
  75167. /**
  75168. * Enable or disable the shader compilation time capture
  75169. */
  75170. set: function (value) {
  75171. var _this = this;
  75172. if (value === this._captureShaderCompilationTime) {
  75173. return;
  75174. }
  75175. this._captureShaderCompilationTime = value;
  75176. if (value) {
  75177. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  75178. _this._shaderCompilationTime.fetchNewFrame();
  75179. _this._shaderCompilationTime.beginMonitoring();
  75180. });
  75181. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  75182. _this._shaderCompilationTime.endMonitoring();
  75183. });
  75184. }
  75185. else {
  75186. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  75187. this._onBeforeShaderCompilationObserver = null;
  75188. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  75189. this._onAfterShaderCompilationObserver = null;
  75190. }
  75191. },
  75192. enumerable: true,
  75193. configurable: true
  75194. });
  75195. EngineInstrumentation.prototype.dispose = function () {
  75196. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  75197. this._onBeginFrameObserver = null;
  75198. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  75199. this._onEndFrameObserver = null;
  75200. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  75201. this._onBeforeShaderCompilationObserver = null;
  75202. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  75203. this._onAfterShaderCompilationObserver = null;
  75204. this.engine = null;
  75205. };
  75206. return EngineInstrumentation;
  75207. }());
  75208. BABYLON.EngineInstrumentation = EngineInstrumentation;
  75209. })(BABYLON || (BABYLON = {}));
  75210. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  75211. var BABYLON;
  75212. (function (BABYLON) {
  75213. /**
  75214. * This class can be used to get instrumentation data from a Babylon engine
  75215. */
  75216. var SceneInstrumentation = /** @class */ (function () {
  75217. function SceneInstrumentation(scene) {
  75218. var _this = this;
  75219. this.scene = scene;
  75220. this._captureActiveMeshesEvaluationTime = false;
  75221. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  75222. this._captureRenderTargetsRenderTime = false;
  75223. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  75224. this._captureFrameTime = false;
  75225. this._frameTime = new BABYLON.PerfCounter();
  75226. this._captureRenderTime = false;
  75227. this._renderTime = new BABYLON.PerfCounter();
  75228. this._captureInterFrameTime = false;
  75229. this._interFrameTime = new BABYLON.PerfCounter();
  75230. this._captureParticlesRenderTime = false;
  75231. this._particlesRenderTime = new BABYLON.PerfCounter();
  75232. this._captureSpritesRenderTime = false;
  75233. this._spritesRenderTime = new BABYLON.PerfCounter();
  75234. this._capturePhysicsTime = false;
  75235. this._physicsTime = new BABYLON.PerfCounter();
  75236. this._captureAnimationsTime = false;
  75237. this._animationsTime = new BABYLON.PerfCounter();
  75238. // Observers
  75239. this._onBeforeActiveMeshesEvaluationObserver = null;
  75240. this._onAfterActiveMeshesEvaluationObserver = null;
  75241. this._onBeforeRenderTargetsRenderObserver = null;
  75242. this._onAfterRenderTargetsRenderObserver = null;
  75243. this._onAfterRenderObserver = null;
  75244. this._onBeforeDrawPhaseObserver = null;
  75245. this._onAfterDrawPhaseObserver = null;
  75246. this._onBeforeAnimationsObserver = null;
  75247. this._onBeforeParticlesRenderingObserver = null;
  75248. this._onAfterParticlesRenderingObserver = null;
  75249. this._onBeforeSpritesRenderingObserver = null;
  75250. this._onAfterSpritesRenderingObserver = null;
  75251. this._onBeforePhysicsObserver = null;
  75252. this._onAfterPhysicsObserver = null;
  75253. this._onAfterAnimationsObserver = null;
  75254. // Before render
  75255. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  75256. if (_this._captureActiveMeshesEvaluationTime) {
  75257. _this._activeMeshesEvaluationTime.fetchNewFrame();
  75258. }
  75259. if (_this._captureRenderTargetsRenderTime) {
  75260. _this._renderTargetsRenderTime.fetchNewFrame();
  75261. }
  75262. if (_this._captureFrameTime) {
  75263. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  75264. _this._frameTime.beginMonitoring();
  75265. }
  75266. if (_this._captureInterFrameTime) {
  75267. _this._interFrameTime.endMonitoring();
  75268. }
  75269. if (_this._captureParticlesRenderTime) {
  75270. _this._particlesRenderTime.fetchNewFrame();
  75271. }
  75272. if (_this._captureSpritesRenderTime) {
  75273. _this._spritesRenderTime.fetchNewFrame();
  75274. }
  75275. if (_this._captureAnimationsTime) {
  75276. _this._animationsTime.beginMonitoring();
  75277. }
  75278. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  75279. });
  75280. // After render
  75281. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  75282. if (_this._captureFrameTime) {
  75283. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  75284. _this._frameTime.endMonitoring();
  75285. }
  75286. if (_this._captureRenderTime) {
  75287. _this._renderTime.endMonitoring(false);
  75288. }
  75289. if (_this._captureInterFrameTime) {
  75290. _this._interFrameTime.beginMonitoring();
  75291. }
  75292. });
  75293. }
  75294. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  75295. // Properties
  75296. /**
  75297. * Gets the perf counter used for active meshes evaluation time
  75298. */
  75299. get: function () {
  75300. return this._activeMeshesEvaluationTime;
  75301. },
  75302. enumerable: true,
  75303. configurable: true
  75304. });
  75305. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  75306. /**
  75307. * Gets the active meshes evaluation time capture status
  75308. */
  75309. get: function () {
  75310. return this._captureActiveMeshesEvaluationTime;
  75311. },
  75312. /**
  75313. * Enable or disable the active meshes evaluation time capture
  75314. */
  75315. set: function (value) {
  75316. var _this = this;
  75317. if (value === this._captureActiveMeshesEvaluationTime) {
  75318. return;
  75319. }
  75320. this._captureActiveMeshesEvaluationTime = value;
  75321. if (value) {
  75322. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  75323. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  75324. _this._activeMeshesEvaluationTime.beginMonitoring();
  75325. });
  75326. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  75327. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  75328. _this._activeMeshesEvaluationTime.endMonitoring();
  75329. });
  75330. }
  75331. else {
  75332. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  75333. this._onBeforeActiveMeshesEvaluationObserver = null;
  75334. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  75335. this._onAfterActiveMeshesEvaluationObserver = null;
  75336. }
  75337. },
  75338. enumerable: true,
  75339. configurable: true
  75340. });
  75341. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  75342. /**
  75343. * Gets the perf counter used for render targets render time
  75344. */
  75345. get: function () {
  75346. return this._renderTargetsRenderTime;
  75347. },
  75348. enumerable: true,
  75349. configurable: true
  75350. });
  75351. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  75352. /**
  75353. * Gets the render targets render time capture status
  75354. */
  75355. get: function () {
  75356. return this._captureRenderTargetsRenderTime;
  75357. },
  75358. /**
  75359. * Enable or disable the render targets render time capture
  75360. */
  75361. set: function (value) {
  75362. var _this = this;
  75363. if (value === this._captureRenderTargetsRenderTime) {
  75364. return;
  75365. }
  75366. this._captureRenderTargetsRenderTime = value;
  75367. if (value) {
  75368. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  75369. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  75370. _this._renderTargetsRenderTime.beginMonitoring();
  75371. });
  75372. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  75373. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  75374. _this._renderTargetsRenderTime.endMonitoring(false);
  75375. });
  75376. }
  75377. else {
  75378. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  75379. this._onBeforeRenderTargetsRenderObserver = null;
  75380. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  75381. this._onAfterRenderTargetsRenderObserver = null;
  75382. }
  75383. },
  75384. enumerable: true,
  75385. configurable: true
  75386. });
  75387. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  75388. /**
  75389. * Gets the perf counter used for particles render time
  75390. */
  75391. get: function () {
  75392. return this._particlesRenderTime;
  75393. },
  75394. enumerable: true,
  75395. configurable: true
  75396. });
  75397. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  75398. /**
  75399. * Gets the particles render time capture status
  75400. */
  75401. get: function () {
  75402. return this._captureParticlesRenderTime;
  75403. },
  75404. /**
  75405. * Enable or disable the particles render time capture
  75406. */
  75407. set: function (value) {
  75408. var _this = this;
  75409. if (value === this._captureParticlesRenderTime) {
  75410. return;
  75411. }
  75412. this._captureParticlesRenderTime = value;
  75413. if (value) {
  75414. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  75415. BABYLON.Tools.StartPerformanceCounter("Particles");
  75416. _this._particlesRenderTime.beginMonitoring();
  75417. });
  75418. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  75419. BABYLON.Tools.EndPerformanceCounter("Particles");
  75420. _this._particlesRenderTime.endMonitoring(false);
  75421. });
  75422. }
  75423. else {
  75424. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  75425. this._onBeforeParticlesRenderingObserver = null;
  75426. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  75427. this._onAfterParticlesRenderingObserver = null;
  75428. }
  75429. },
  75430. enumerable: true,
  75431. configurable: true
  75432. });
  75433. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  75434. /**
  75435. * Gets the perf counter used for sprites render time
  75436. */
  75437. get: function () {
  75438. return this._spritesRenderTime;
  75439. },
  75440. enumerable: true,
  75441. configurable: true
  75442. });
  75443. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  75444. /**
  75445. * Gets the sprites render time capture status
  75446. */
  75447. get: function () {
  75448. return this._captureSpritesRenderTime;
  75449. },
  75450. /**
  75451. * Enable or disable the sprites render time capture
  75452. */
  75453. set: function (value) {
  75454. var _this = this;
  75455. if (value === this._captureSpritesRenderTime) {
  75456. return;
  75457. }
  75458. this._captureSpritesRenderTime = value;
  75459. if (value) {
  75460. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  75461. BABYLON.Tools.StartPerformanceCounter("Sprites");
  75462. _this._spritesRenderTime.beginMonitoring();
  75463. });
  75464. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  75465. BABYLON.Tools.EndPerformanceCounter("Sprites");
  75466. _this._spritesRenderTime.endMonitoring(false);
  75467. });
  75468. }
  75469. else {
  75470. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  75471. this._onBeforeSpritesRenderingObserver = null;
  75472. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  75473. this._onAfterSpritesRenderingObserver = null;
  75474. }
  75475. },
  75476. enumerable: true,
  75477. configurable: true
  75478. });
  75479. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  75480. /**
  75481. * Gets the perf counter used for physics time
  75482. */
  75483. get: function () {
  75484. return this._physicsTime;
  75485. },
  75486. enumerable: true,
  75487. configurable: true
  75488. });
  75489. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  75490. /**
  75491. * Gets the physics time capture status
  75492. */
  75493. get: function () {
  75494. return this._capturePhysicsTime;
  75495. },
  75496. /**
  75497. * Enable or disable the physics time capture
  75498. */
  75499. set: function (value) {
  75500. var _this = this;
  75501. if (value === this._capturePhysicsTime) {
  75502. return;
  75503. }
  75504. this._capturePhysicsTime = value;
  75505. if (value) {
  75506. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  75507. BABYLON.Tools.StartPerformanceCounter("Physics");
  75508. _this._physicsTime.beginMonitoring();
  75509. });
  75510. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  75511. BABYLON.Tools.EndPerformanceCounter("Physics");
  75512. _this._physicsTime.endMonitoring();
  75513. });
  75514. }
  75515. else {
  75516. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  75517. this._onBeforePhysicsObserver = null;
  75518. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  75519. this._onAfterPhysicsObserver = null;
  75520. }
  75521. },
  75522. enumerable: true,
  75523. configurable: true
  75524. });
  75525. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  75526. /**
  75527. * Gets the perf counter used for animations time
  75528. */
  75529. get: function () {
  75530. return this._animationsTime;
  75531. },
  75532. enumerable: true,
  75533. configurable: true
  75534. });
  75535. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  75536. /**
  75537. * Gets the animations time capture status
  75538. */
  75539. get: function () {
  75540. return this._captureAnimationsTime;
  75541. },
  75542. /**
  75543. * Enable or disable the animations time capture
  75544. */
  75545. set: function (value) {
  75546. var _this = this;
  75547. if (value === this._captureAnimationsTime) {
  75548. return;
  75549. }
  75550. this._captureAnimationsTime = value;
  75551. if (value) {
  75552. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  75553. _this._animationsTime.endMonitoring();
  75554. });
  75555. }
  75556. else {
  75557. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  75558. this._onAfterAnimationsObserver = null;
  75559. }
  75560. },
  75561. enumerable: true,
  75562. configurable: true
  75563. });
  75564. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  75565. /**
  75566. * Gets the perf counter used for frame time capture
  75567. */
  75568. get: function () {
  75569. return this._frameTime;
  75570. },
  75571. enumerable: true,
  75572. configurable: true
  75573. });
  75574. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  75575. /**
  75576. * Gets the frame time capture status
  75577. */
  75578. get: function () {
  75579. return this._captureFrameTime;
  75580. },
  75581. /**
  75582. * Enable or disable the frame time capture
  75583. */
  75584. set: function (value) {
  75585. this._captureFrameTime = value;
  75586. },
  75587. enumerable: true,
  75588. configurable: true
  75589. });
  75590. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  75591. /**
  75592. * Gets the perf counter used for inter-frames time capture
  75593. */
  75594. get: function () {
  75595. return this._interFrameTime;
  75596. },
  75597. enumerable: true,
  75598. configurable: true
  75599. });
  75600. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  75601. /**
  75602. * Gets the inter-frames time capture status
  75603. */
  75604. get: function () {
  75605. return this._captureInterFrameTime;
  75606. },
  75607. /**
  75608. * Enable or disable the inter-frames time capture
  75609. */
  75610. set: function (value) {
  75611. this._captureInterFrameTime = value;
  75612. },
  75613. enumerable: true,
  75614. configurable: true
  75615. });
  75616. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  75617. /**
  75618. * Gets the perf counter used for render time capture
  75619. */
  75620. get: function () {
  75621. return this._renderTime;
  75622. },
  75623. enumerable: true,
  75624. configurable: true
  75625. });
  75626. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  75627. /**
  75628. * Gets the render time capture status
  75629. */
  75630. get: function () {
  75631. return this._captureRenderTime;
  75632. },
  75633. /**
  75634. * Enable or disable the render time capture
  75635. */
  75636. set: function (value) {
  75637. var _this = this;
  75638. if (value === this._captureRenderTime) {
  75639. return;
  75640. }
  75641. this._captureRenderTime = value;
  75642. if (value) {
  75643. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  75644. _this._renderTime.beginMonitoring();
  75645. BABYLON.Tools.StartPerformanceCounter("Main render");
  75646. });
  75647. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  75648. _this._renderTime.endMonitoring(false);
  75649. BABYLON.Tools.EndPerformanceCounter("Main render");
  75650. });
  75651. }
  75652. else {
  75653. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  75654. this._onBeforeDrawPhaseObserver = null;
  75655. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  75656. this._onAfterDrawPhaseObserver = null;
  75657. }
  75658. },
  75659. enumerable: true,
  75660. configurable: true
  75661. });
  75662. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  75663. /**
  75664. * Gets the perf counter used for frame time capture
  75665. */
  75666. get: function () {
  75667. return this.scene.getEngine()._drawCalls;
  75668. },
  75669. enumerable: true,
  75670. configurable: true
  75671. });
  75672. SceneInstrumentation.prototype.dispose = function () {
  75673. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75674. this._onAfterRenderObserver = null;
  75675. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  75676. this._onBeforeActiveMeshesEvaluationObserver = null;
  75677. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  75678. this._onAfterActiveMeshesEvaluationObserver = null;
  75679. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  75680. this._onBeforeRenderTargetsRenderObserver = null;
  75681. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  75682. this._onAfterRenderTargetsRenderObserver = null;
  75683. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  75684. this._onBeforeAnimationsObserver = null;
  75685. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  75686. this._onBeforeParticlesRenderingObserver = null;
  75687. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  75688. this._onAfterParticlesRenderingObserver = null;
  75689. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  75690. this._onBeforeSpritesRenderingObserver = null;
  75691. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  75692. this._onAfterSpritesRenderingObserver = null;
  75693. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  75694. this._onBeforeDrawPhaseObserver = null;
  75695. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  75696. this._onAfterDrawPhaseObserver = null;
  75697. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  75698. this._onBeforePhysicsObserver = null;
  75699. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  75700. this._onAfterPhysicsObserver = null;
  75701. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  75702. this._onAfterAnimationsObserver = null;
  75703. this.scene = null;
  75704. };
  75705. return SceneInstrumentation;
  75706. }());
  75707. BABYLON.SceneInstrumentation = SceneInstrumentation;
  75708. })(BABYLON || (BABYLON = {}));
  75709. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  75710. var BABYLON;
  75711. (function (BABYLON) {
  75712. var _TimeToken = /** @class */ (function () {
  75713. function _TimeToken() {
  75714. this._timeElapsedQueryEnded = false;
  75715. }
  75716. return _TimeToken;
  75717. }());
  75718. BABYLON._TimeToken = _TimeToken;
  75719. })(BABYLON || (BABYLON = {}));
  75720. //# sourceMappingURL=babylon.timeToken.js.map
  75721. var BABYLON;
  75722. (function (BABYLON) {
  75723. /**
  75724. * Background material defines definition.
  75725. */
  75726. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  75727. __extends(BackgroundMaterialDefines, _super);
  75728. /**
  75729. * Constructor of the defines.
  75730. */
  75731. function BackgroundMaterialDefines() {
  75732. var _this = _super.call(this) || this;
  75733. /**
  75734. * True if the diffuse texture is in use.
  75735. */
  75736. _this.DIFFUSE = false;
  75737. /**
  75738. * The direct UV channel to use.
  75739. */
  75740. _this.DIFFUSEDIRECTUV = 0;
  75741. /**
  75742. * True if the diffuse texture is in gamma space.
  75743. */
  75744. _this.GAMMADIFFUSE = false;
  75745. /**
  75746. * True if the diffuse texture has opacity in the alpha channel.
  75747. */
  75748. _this.DIFFUSEHASALPHA = false;
  75749. /**
  75750. * True if you want the material to fade to transparent at grazing angle.
  75751. */
  75752. _this.OPACITYFRESNEL = false;
  75753. /**
  75754. * True if an extra blur needs to be added in the reflection.
  75755. */
  75756. _this.REFLECTIONBLUR = false;
  75757. /**
  75758. * True if you want the material to fade to reflection at grazing angle.
  75759. */
  75760. _this.REFLECTIONFRESNEL = false;
  75761. /**
  75762. * True if you want the material to falloff as far as you move away from the scene center.
  75763. */
  75764. _this.REFLECTIONFALLOFF = false;
  75765. /**
  75766. * False if the current Webgl implementation does not support the texture lod extension.
  75767. */
  75768. _this.TEXTURELODSUPPORT = false;
  75769. /**
  75770. * True to ensure the data are premultiplied.
  75771. */
  75772. _this.PREMULTIPLYALPHA = false;
  75773. /**
  75774. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  75775. */
  75776. _this.USERGBCOLOR = false;
  75777. // Image Processing Configuration.
  75778. _this.IMAGEPROCESSING = false;
  75779. _this.VIGNETTE = false;
  75780. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  75781. _this.VIGNETTEBLENDMODEOPAQUE = false;
  75782. _this.TONEMAPPING = false;
  75783. _this.CONTRAST = false;
  75784. _this.COLORCURVES = false;
  75785. _this.COLORGRADING = false;
  75786. _this.COLORGRADING3D = false;
  75787. _this.SAMPLER3DGREENDEPTH = false;
  75788. _this.SAMPLER3DBGRMAP = false;
  75789. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  75790. _this.EXPOSURE = false;
  75791. // Reflection.
  75792. _this.REFLECTION = false;
  75793. _this.REFLECTIONMAP_3D = false;
  75794. _this.REFLECTIONMAP_SPHERICAL = false;
  75795. _this.REFLECTIONMAP_PLANAR = false;
  75796. _this.REFLECTIONMAP_CUBIC = false;
  75797. _this.REFLECTIONMAP_PROJECTION = false;
  75798. _this.REFLECTIONMAP_SKYBOX = false;
  75799. _this.REFLECTIONMAP_EXPLICIT = false;
  75800. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75801. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75802. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75803. _this.INVERTCUBICMAP = false;
  75804. _this.REFLECTIONMAP_OPPOSITEZ = false;
  75805. _this.LODINREFLECTIONALPHA = false;
  75806. _this.GAMMAREFLECTION = false;
  75807. // Default BJS.
  75808. _this.MAINUV1 = false;
  75809. _this.MAINUV2 = false;
  75810. _this.UV1 = false;
  75811. _this.UV2 = false;
  75812. _this.CLIPPLANE = false;
  75813. _this.POINTSIZE = false;
  75814. _this.FOG = false;
  75815. _this.NORMAL = false;
  75816. _this.NUM_BONE_INFLUENCERS = 0;
  75817. _this.BonesPerMesh = 0;
  75818. _this.INSTANCES = false;
  75819. _this.SHADOWFLOAT = false;
  75820. _this.rebuild();
  75821. return _this;
  75822. }
  75823. return BackgroundMaterialDefines;
  75824. }(BABYLON.MaterialDefines));
  75825. /**
  75826. * Background material used to create an efficient environement around your scene.
  75827. */
  75828. var BackgroundMaterial = /** @class */ (function (_super) {
  75829. __extends(BackgroundMaterial, _super);
  75830. /**
  75831. * constructor
  75832. * @param name The name of the material
  75833. * @param scene The scene to add the material to
  75834. */
  75835. function BackgroundMaterial(name, scene) {
  75836. var _this = _super.call(this, name, scene) || this;
  75837. _this.primaryColor = BABYLON.Color3.White();
  75838. _this.primaryLevel = 1;
  75839. _this.secondaryColor = BABYLON.Color3.Gray();
  75840. _this.secondaryLevel = 1;
  75841. _this.tertiaryColor = BABYLON.Color3.Black();
  75842. _this.tertiaryLevel = 1;
  75843. _this.reflectionTexture = null;
  75844. _this.reflectionBlur = 0;
  75845. _this.diffuseTexture = null;
  75846. /**
  75847. * Specify the list of lights casting shadow on the material.
  75848. * All scene shadow lights will be included if null.
  75849. */
  75850. _this._shadowLights = null;
  75851. _this.shadowLights = null;
  75852. _this.shadowBlurScale = 1;
  75853. _this.shadowLevel = 0;
  75854. _this.sceneCenter = BABYLON.Vector3.Zero();
  75855. _this.opacityFresnel = true;
  75856. _this.reflectionFresnel = false;
  75857. _this.reflectionFalloffDistance = 0.0;
  75858. _this.reflectionAmount = 1.0;
  75859. _this.reflectionReflectance0 = 0.05;
  75860. _this.reflectionReflectance90 = 0.5;
  75861. _this.useRGBColor = true;
  75862. /**
  75863. * Number of Simultaneous lights allowed on the material.
  75864. */
  75865. _this._maxSimultaneousLights = 4;
  75866. _this.maxSimultaneousLights = 4;
  75867. /**
  75868. * Keep track of the image processing observer to allow dispose and replace.
  75869. */
  75870. _this._imageProcessingObserver = null;
  75871. // Temp values kept as cache in the material.
  75872. _this._renderTargets = new BABYLON.SmartArray(16);
  75873. _this._reflectionControls = BABYLON.Vector4.Zero();
  75874. // Setup the default processing configuration to the scene.
  75875. _this._attachImageProcessingConfiguration(null);
  75876. _this.getRenderTargetTextures = function () {
  75877. _this._renderTargets.reset();
  75878. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  75879. _this._renderTargets.push(_this._diffuseTexture);
  75880. }
  75881. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  75882. _this._renderTargets.push(_this._reflectionTexture);
  75883. }
  75884. return _this._renderTargets;
  75885. };
  75886. return _this;
  75887. }
  75888. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  75889. /**
  75890. * Sets the reflection reflectance fresnel values according to the default standard
  75891. * empirically know to work well :-)
  75892. */
  75893. set: function (value) {
  75894. var reflectionWeight = value;
  75895. if (reflectionWeight < 0.5) {
  75896. reflectionWeight = reflectionWeight * 2.0;
  75897. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  75898. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  75899. }
  75900. else {
  75901. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  75902. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  75903. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  75904. }
  75905. },
  75906. enumerable: true,
  75907. configurable: true
  75908. });
  75909. /**
  75910. * Attaches a new image processing configuration to the PBR Material.
  75911. * @param configuration (if null the scene configuration will be use)
  75912. */
  75913. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  75914. var _this = this;
  75915. if (configuration === this._imageProcessingConfiguration) {
  75916. return;
  75917. }
  75918. // Detaches observer.
  75919. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75920. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75921. }
  75922. // Pick the scene configuration if needed.
  75923. if (!configuration) {
  75924. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  75925. }
  75926. else {
  75927. this._imageProcessingConfiguration = configuration;
  75928. }
  75929. // Attaches observer.
  75930. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75931. _this._markAllSubMeshesAsImageProcessingDirty();
  75932. });
  75933. };
  75934. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  75935. /**
  75936. * Gets the image processing configuration used either in this material.
  75937. */
  75938. get: function () {
  75939. return this._imageProcessingConfiguration;
  75940. },
  75941. /**
  75942. * Sets the Default image processing configuration used either in the this material.
  75943. *
  75944. * If sets to null, the scene one is in use.
  75945. */
  75946. set: function (value) {
  75947. this._attachImageProcessingConfiguration(value);
  75948. // Ensure the effect will be rebuilt.
  75949. this._markAllSubMeshesAsTexturesDirty();
  75950. },
  75951. enumerable: true,
  75952. configurable: true
  75953. });
  75954. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  75955. /**
  75956. * Gets wether the color curves effect is enabled.
  75957. */
  75958. get: function () {
  75959. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75960. },
  75961. /**
  75962. * Sets wether the color curves effect is enabled.
  75963. */
  75964. set: function (value) {
  75965. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75966. },
  75967. enumerable: true,
  75968. configurable: true
  75969. });
  75970. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  75971. /**
  75972. * Gets wether the color grading effect is enabled.
  75973. */
  75974. get: function () {
  75975. return this.imageProcessingConfiguration.colorGradingEnabled;
  75976. },
  75977. /**
  75978. * Gets wether the color grading effect is enabled.
  75979. */
  75980. set: function (value) {
  75981. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75982. },
  75983. enumerable: true,
  75984. configurable: true
  75985. });
  75986. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  75987. /**
  75988. * Gets wether tonemapping is enabled or not.
  75989. */
  75990. get: function () {
  75991. return this._imageProcessingConfiguration.toneMappingEnabled;
  75992. },
  75993. /**
  75994. * Sets wether tonemapping is enabled or not
  75995. */
  75996. set: function (value) {
  75997. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75998. },
  75999. enumerable: true,
  76000. configurable: true
  76001. });
  76002. ;
  76003. ;
  76004. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  76005. /**
  76006. * The camera exposure used on this material.
  76007. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  76008. * This corresponds to a photographic exposure.
  76009. */
  76010. get: function () {
  76011. return this._imageProcessingConfiguration.exposure;
  76012. },
  76013. /**
  76014. * The camera exposure used on this material.
  76015. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  76016. * This corresponds to a photographic exposure.
  76017. */
  76018. set: function (value) {
  76019. this._imageProcessingConfiguration.exposure = value;
  76020. },
  76021. enumerable: true,
  76022. configurable: true
  76023. });
  76024. ;
  76025. ;
  76026. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  76027. /**
  76028. * Gets The camera contrast used on this material.
  76029. */
  76030. get: function () {
  76031. return this._imageProcessingConfiguration.contrast;
  76032. },
  76033. /**
  76034. * Sets The camera contrast used on this material.
  76035. */
  76036. set: function (value) {
  76037. this._imageProcessingConfiguration.contrast = value;
  76038. },
  76039. enumerable: true,
  76040. configurable: true
  76041. });
  76042. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  76043. /**
  76044. * Gets the Color Grading 2D Lookup Texture.
  76045. */
  76046. get: function () {
  76047. return this._imageProcessingConfiguration.colorGradingTexture;
  76048. },
  76049. /**
  76050. * Sets the Color Grading 2D Lookup Texture.
  76051. */
  76052. set: function (value) {
  76053. this.imageProcessingConfiguration.colorGradingTexture = value;
  76054. },
  76055. enumerable: true,
  76056. configurable: true
  76057. });
  76058. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  76059. /**
  76060. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76061. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76062. * 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;
  76063. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76064. */
  76065. get: function () {
  76066. return this.imageProcessingConfiguration.colorCurves;
  76067. },
  76068. /**
  76069. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76070. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76071. * 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;
  76072. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76073. */
  76074. set: function (value) {
  76075. this.imageProcessingConfiguration.colorCurves = value;
  76076. },
  76077. enumerable: true,
  76078. configurable: true
  76079. });
  76080. /**
  76081. * The entire material has been created in order to prevent overdraw.
  76082. * @returns false
  76083. */
  76084. BackgroundMaterial.prototype.needAlphaTesting = function () {
  76085. return false;
  76086. };
  76087. /**
  76088. * The entire material has been created in order to prevent overdraw.
  76089. * @returns true if blending is enable
  76090. */
  76091. BackgroundMaterial.prototype.needAlphaBlending = function () {
  76092. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  76093. };
  76094. /**
  76095. * Checks wether the material is ready to be rendered for a given mesh.
  76096. * @param mesh The mesh to render
  76097. * @param subMesh The submesh to check against
  76098. * @param useInstances Specify wether or not the material is used with instances
  76099. */
  76100. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  76101. var _this = this;
  76102. if (useInstances === void 0) { useInstances = false; }
  76103. if (subMesh.effect && this.isFrozen) {
  76104. if (this._wasPreviouslyReady) {
  76105. return true;
  76106. }
  76107. }
  76108. if (!subMesh._materialDefines) {
  76109. subMesh._materialDefines = new BackgroundMaterialDefines();
  76110. }
  76111. var scene = this.getScene();
  76112. var defines = subMesh._materialDefines;
  76113. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  76114. if (defines._renderId === scene.getRenderId()) {
  76115. return true;
  76116. }
  76117. }
  76118. var engine = scene.getEngine();
  76119. // Lights
  76120. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  76121. defines._needNormals = true;
  76122. // Textures
  76123. if (defines._areTexturesDirty) {
  76124. defines._needUVs = false;
  76125. if (scene.texturesEnabled) {
  76126. if (scene.getEngine().getCaps().textureLOD) {
  76127. defines.TEXTURELODSUPPORT = true;
  76128. }
  76129. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  76130. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  76131. return false;
  76132. }
  76133. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  76134. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  76135. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  76136. defines.OPACITYFRESNEL = this._opacityFresnel;
  76137. }
  76138. else {
  76139. defines.DIFFUSE = false;
  76140. defines.DIFFUSEHASALPHA = false;
  76141. defines.GAMMADIFFUSE = false;
  76142. defines.OPACITYFRESNEL = false;
  76143. }
  76144. var reflectionTexture = this._reflectionTexture;
  76145. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  76146. if (!reflectionTexture.isReadyOrNotBlocking()) {
  76147. return false;
  76148. }
  76149. defines.REFLECTION = true;
  76150. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  76151. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  76152. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  76153. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  76154. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  76155. defines.INVERTCUBICMAP = true;
  76156. }
  76157. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  76158. switch (reflectionTexture.coordinatesMode) {
  76159. case BABYLON.Texture.CUBIC_MODE:
  76160. case BABYLON.Texture.INVCUBIC_MODE:
  76161. defines.REFLECTIONMAP_CUBIC = true;
  76162. break;
  76163. case BABYLON.Texture.EXPLICIT_MODE:
  76164. defines.REFLECTIONMAP_EXPLICIT = true;
  76165. break;
  76166. case BABYLON.Texture.PLANAR_MODE:
  76167. defines.REFLECTIONMAP_PLANAR = true;
  76168. break;
  76169. case BABYLON.Texture.PROJECTION_MODE:
  76170. defines.REFLECTIONMAP_PROJECTION = true;
  76171. break;
  76172. case BABYLON.Texture.SKYBOX_MODE:
  76173. defines.REFLECTIONMAP_SKYBOX = true;
  76174. break;
  76175. case BABYLON.Texture.SPHERICAL_MODE:
  76176. defines.REFLECTIONMAP_SPHERICAL = true;
  76177. break;
  76178. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  76179. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  76180. break;
  76181. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  76182. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  76183. break;
  76184. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  76185. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  76186. break;
  76187. }
  76188. if (this.reflectionFresnel) {
  76189. defines.REFLECTIONFRESNEL = true;
  76190. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  76191. this._reflectionControls.x = this.reflectionAmount;
  76192. this._reflectionControls.y = this.reflectionReflectance0;
  76193. this._reflectionControls.z = this.reflectionReflectance90;
  76194. this._reflectionControls.w = this.reflectionFalloffDistance;
  76195. }
  76196. else {
  76197. defines.REFLECTIONFRESNEL = false;
  76198. defines.REFLECTIONFALLOFF = false;
  76199. }
  76200. }
  76201. else {
  76202. defines.REFLECTION = false;
  76203. defines.REFLECTIONFALLOFF = false;
  76204. defines.REFLECTIONBLUR = false;
  76205. defines.REFLECTIONMAP_3D = false;
  76206. defines.REFLECTIONMAP_SPHERICAL = false;
  76207. defines.REFLECTIONMAP_PLANAR = false;
  76208. defines.REFLECTIONMAP_CUBIC = false;
  76209. defines.REFLECTIONMAP_PROJECTION = false;
  76210. defines.REFLECTIONMAP_SKYBOX = false;
  76211. defines.REFLECTIONMAP_EXPLICIT = false;
  76212. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  76213. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  76214. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  76215. defines.INVERTCUBICMAP = false;
  76216. defines.REFLECTIONMAP_OPPOSITEZ = false;
  76217. defines.LODINREFLECTIONALPHA = false;
  76218. defines.GAMMAREFLECTION = false;
  76219. }
  76220. }
  76221. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  76222. defines.USERGBCOLOR = this._useRGBColor;
  76223. }
  76224. if (defines._areImageProcessingDirty) {
  76225. if (!this._imageProcessingConfiguration.isReady()) {
  76226. return false;
  76227. }
  76228. this._imageProcessingConfiguration.prepareDefines(defines);
  76229. }
  76230. // Misc.
  76231. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  76232. // Values that need to be evaluated on every frame
  76233. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  76234. // Attribs
  76235. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  76236. if (mesh) {
  76237. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76238. mesh.createNormals(true);
  76239. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  76240. }
  76241. }
  76242. }
  76243. // Get correct effect
  76244. if (defines.isDirty) {
  76245. defines.markAsProcessed();
  76246. scene.resetCachedMaterial();
  76247. // Fallbacks
  76248. var fallbacks = new BABYLON.EffectFallbacks();
  76249. if (defines.FOG) {
  76250. fallbacks.addFallback(0, "FOG");
  76251. }
  76252. if (defines.POINTSIZE) {
  76253. fallbacks.addFallback(1, "POINTSIZE");
  76254. }
  76255. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  76256. if (defines.NUM_BONE_INFLUENCERS > 0) {
  76257. fallbacks.addCPUSkinningFallback(0, mesh);
  76258. }
  76259. //Attributes
  76260. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76261. if (defines.NORMAL) {
  76262. attribs.push(BABYLON.VertexBuffer.NormalKind);
  76263. }
  76264. if (defines.UV1) {
  76265. attribs.push(BABYLON.VertexBuffer.UVKind);
  76266. }
  76267. if (defines.UV2) {
  76268. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76269. }
  76270. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  76271. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  76272. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  76273. "vFogInfos", "vFogColor", "pointSize",
  76274. "vClipPlane", "mBones",
  76275. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  76276. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  76277. "shadowLevel", "alpha",
  76278. "vBackgroundCenter", "vReflectionControl",
  76279. "vDiffuseInfos", "diffuseMatrix",
  76280. ];
  76281. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  76282. var uniformBuffers = ["Material", "Scene"];
  76283. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  76284. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  76285. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  76286. uniformsNames: uniforms,
  76287. uniformBuffersNames: uniformBuffers,
  76288. samplers: samplers,
  76289. defines: defines,
  76290. maxSimultaneousLights: this._maxSimultaneousLights
  76291. });
  76292. var onCompiled = function (effect) {
  76293. if (_this.onCompiled) {
  76294. _this.onCompiled(effect);
  76295. }
  76296. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  76297. };
  76298. var join = defines.toString();
  76299. subMesh.setEffect(scene.getEngine().createEffect("background", {
  76300. attributes: attribs,
  76301. uniformsNames: uniforms,
  76302. uniformBuffersNames: uniformBuffers,
  76303. samplers: samplers,
  76304. defines: join,
  76305. fallbacks: fallbacks,
  76306. onCompiled: onCompiled,
  76307. onError: this.onError,
  76308. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  76309. }, engine), defines);
  76310. this.buildUniformLayout();
  76311. }
  76312. if (!subMesh.effect || !subMesh.effect.isReady()) {
  76313. return false;
  76314. }
  76315. defines._renderId = scene.getRenderId();
  76316. this._wasPreviouslyReady = true;
  76317. return true;
  76318. };
  76319. /**
  76320. * Build the uniform buffer used in the material.
  76321. */
  76322. BackgroundMaterial.prototype.buildUniformLayout = function () {
  76323. // Order is important !
  76324. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  76325. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  76326. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  76327. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  76328. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  76329. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  76330. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  76331. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  76332. this._uniformBuffer.addUniform("pointSize", 1);
  76333. this._uniformBuffer.addUniform("shadowLevel", 1);
  76334. this._uniformBuffer.addUniform("alpha", 1);
  76335. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  76336. this._uniformBuffer.addUniform("vReflectionControl", 4);
  76337. this._uniformBuffer.create();
  76338. };
  76339. /**
  76340. * Unbind the material.
  76341. */
  76342. BackgroundMaterial.prototype.unbind = function () {
  76343. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  76344. this._uniformBuffer.setTexture("diffuseSampler", null);
  76345. }
  76346. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  76347. this._uniformBuffer.setTexture("reflectionSampler", null);
  76348. }
  76349. _super.prototype.unbind.call(this);
  76350. };
  76351. /**
  76352. * Bind only the world matrix to the material.
  76353. * @param world The world matrix to bind.
  76354. */
  76355. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  76356. this._activeEffect.setMatrix("world", world);
  76357. };
  76358. /**
  76359. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  76360. * @param world The world matrix to bind.
  76361. * @param subMesh The submesh to bind for.
  76362. */
  76363. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  76364. var scene = this.getScene();
  76365. var defines = subMesh._materialDefines;
  76366. if (!defines) {
  76367. return;
  76368. }
  76369. var effect = subMesh.effect;
  76370. if (!effect) {
  76371. return;
  76372. }
  76373. this._activeEffect = effect;
  76374. // Matrices
  76375. this.bindOnlyWorldMatrix(world);
  76376. // Bones
  76377. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  76378. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  76379. if (mustRebind) {
  76380. this._uniformBuffer.bindToEffect(effect, "Material");
  76381. this.bindViewProjection(effect);
  76382. var reflectionTexture = this._reflectionTexture;
  76383. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  76384. // Texture uniforms
  76385. if (scene.texturesEnabled) {
  76386. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  76387. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  76388. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  76389. }
  76390. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  76391. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  76392. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  76393. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  76394. }
  76395. }
  76396. if (this.shadowLevel > 0) {
  76397. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  76398. }
  76399. this._uniformBuffer.updateFloat("alpha", this.alpha);
  76400. // Point size
  76401. if (this.pointsCloud) {
  76402. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  76403. }
  76404. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  76405. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  76406. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  76407. }
  76408. // Textures
  76409. if (scene.texturesEnabled) {
  76410. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  76411. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  76412. }
  76413. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  76414. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  76415. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  76416. }
  76417. else if (!defines.REFLECTIONBLUR) {
  76418. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  76419. }
  76420. else {
  76421. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  76422. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  76423. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  76424. }
  76425. if (defines.REFLECTIONFRESNEL) {
  76426. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  76427. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  76428. }
  76429. }
  76430. }
  76431. // Clip plane
  76432. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  76433. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  76434. }
  76435. if (mustRebind || !this.isFrozen) {
  76436. if (scene.lightsEnabled) {
  76437. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  76438. }
  76439. // View
  76440. this.bindView(effect);
  76441. // Fog
  76442. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  76443. // image processing
  76444. this._imageProcessingConfiguration.bind(this._activeEffect);
  76445. }
  76446. this._uniformBuffer.update();
  76447. this._afterBind(mesh);
  76448. };
  76449. /**
  76450. * Dispose the material.
  76451. * @forceDisposeEffect Force disposal of the associated effect.
  76452. * @forceDisposeTextures Force disposal of the associated textures.
  76453. */
  76454. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  76455. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  76456. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  76457. if (forceDisposeTextures) {
  76458. if (this.diffuseTexture) {
  76459. this.diffuseTexture.dispose();
  76460. }
  76461. if (this.reflectionTexture) {
  76462. this.reflectionTexture.dispose();
  76463. }
  76464. }
  76465. this._renderTargets.dispose();
  76466. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76467. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76468. }
  76469. _super.prototype.dispose.call(this, forceDisposeEffect);
  76470. };
  76471. /**
  76472. * Clones the material.
  76473. * @name The cloned name.
  76474. * @returns The cloned material.
  76475. */
  76476. BackgroundMaterial.prototype.clone = function (name) {
  76477. var _this = this;
  76478. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  76479. };
  76480. /**
  76481. * Serializes the current material to its JSON representation.
  76482. * @returns The JSON representation.
  76483. */
  76484. BackgroundMaterial.prototype.serialize = function () {
  76485. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76486. serializationObject.customType = "BABYLON.BackgroundMaterial";
  76487. return serializationObject;
  76488. };
  76489. /**
  76490. * Gets the class name of the material
  76491. * @returns "BackgroundMaterial"
  76492. */
  76493. BackgroundMaterial.prototype.getClassName = function () {
  76494. return "BackgroundMaterial";
  76495. };
  76496. /**
  76497. * Parse a JSON input to create back a background material.
  76498. * @param source
  76499. * @param scene
  76500. * @param rootUrl
  76501. * @returns the instantiated BackgroundMaterial.
  76502. */
  76503. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  76504. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  76505. };
  76506. /**
  76507. * Standard reflectance value at parallel view angle.
  76508. */
  76509. BackgroundMaterial.standardReflectance0 = 0.05;
  76510. /**
  76511. * Standard reflectance value at grazing angle.
  76512. */
  76513. BackgroundMaterial.standardReflectance90 = 0.5;
  76514. __decorate([
  76515. BABYLON.serializeAsColor3()
  76516. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  76517. __decorate([
  76518. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76519. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  76520. __decorate([
  76521. BABYLON.serialize()
  76522. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  76523. __decorate([
  76524. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76525. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  76526. __decorate([
  76527. BABYLON.serializeAsColor3()
  76528. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  76529. __decorate([
  76530. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76531. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  76532. __decorate([
  76533. BABYLON.serialize()
  76534. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  76535. __decorate([
  76536. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76537. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  76538. __decorate([
  76539. BABYLON.serializeAsColor3()
  76540. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  76541. __decorate([
  76542. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76543. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  76544. __decorate([
  76545. BABYLON.serialize()
  76546. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  76547. __decorate([
  76548. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76549. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  76550. __decorate([
  76551. BABYLON.serializeAsTexture()
  76552. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  76553. __decorate([
  76554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76555. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  76556. __decorate([
  76557. BABYLON.serialize()
  76558. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  76559. __decorate([
  76560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76561. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  76562. __decorate([
  76563. BABYLON.serializeAsTexture()
  76564. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  76565. __decorate([
  76566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76567. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  76568. __decorate([
  76569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76570. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  76571. __decorate([
  76572. BABYLON.serialize()
  76573. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  76574. __decorate([
  76575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76576. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  76577. __decorate([
  76578. BABYLON.serialize()
  76579. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  76580. __decorate([
  76581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76582. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  76583. __decorate([
  76584. BABYLON.serializeAsVector3()
  76585. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  76586. __decorate([
  76587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76588. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  76589. __decorate([
  76590. BABYLON.serialize()
  76591. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  76592. __decorate([
  76593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76594. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  76595. __decorate([
  76596. BABYLON.serialize()
  76597. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  76598. __decorate([
  76599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76600. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  76601. __decorate([
  76602. BABYLON.serialize()
  76603. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  76604. __decorate([
  76605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76606. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  76607. __decorate([
  76608. BABYLON.serialize()
  76609. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  76610. __decorate([
  76611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76612. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  76613. __decorate([
  76614. BABYLON.serialize()
  76615. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  76616. __decorate([
  76617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76618. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  76619. __decorate([
  76620. BABYLON.serialize()
  76621. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  76622. __decorate([
  76623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76624. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  76625. __decorate([
  76626. BABYLON.serialize()
  76627. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  76628. __decorate([
  76629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76630. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  76631. __decorate([
  76632. BABYLON.serialize()
  76633. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  76634. __decorate([
  76635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76636. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  76637. __decorate([
  76638. BABYLON.serializeAsImageProcessingConfiguration()
  76639. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  76640. return BackgroundMaterial;
  76641. }(BABYLON.PushMaterial));
  76642. BABYLON.BackgroundMaterial = BackgroundMaterial;
  76643. })(BABYLON || (BABYLON = {}));
  76644. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  76645. var __assign = (this && this.__assign) || Object.assign || function(t) {
  76646. for (var s, i = 1, n = arguments.length; i < n; i++) {
  76647. s = arguments[i];
  76648. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  76649. t[p] = s[p];
  76650. }
  76651. return t;
  76652. };
  76653. var BABYLON;
  76654. (function (BABYLON) {
  76655. /**
  76656. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  76657. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  76658. * It also helps with the default setup of your imageProcessing configuration.
  76659. */
  76660. var EnvironmentHelper = /** @class */ (function () {
  76661. /**
  76662. * constructor
  76663. * @param options
  76664. * @param scene The scene to add the material to
  76665. */
  76666. function EnvironmentHelper(options, scene) {
  76667. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  76668. this._scene = scene;
  76669. this._setupBackground();
  76670. this._setupImageProcessing();
  76671. }
  76672. /**
  76673. * Creates the default options for the helper.
  76674. */
  76675. EnvironmentHelper._getDefaultOptions = function () {
  76676. return {
  76677. createGround: true,
  76678. groundSize: 15,
  76679. groundTexture: this._groundTextureCDNUrl,
  76680. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3),
  76681. groundOpacity: 1,
  76682. enableGroundShadow: true,
  76683. groundShadowLevel: 0.5,
  76684. enableGroundMirror: false,
  76685. groundMirrorSizeRatio: 0.3,
  76686. groundMirrorBlurKernel: 64,
  76687. groundMirrorAmount: 1,
  76688. groundMirrorFresnelWeight: 1,
  76689. groundMirrorFallOffDistance: 0,
  76690. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  76691. createSkybox: true,
  76692. skyboxSize: 20,
  76693. skyboxTexture: this._skyboxTextureCDNUrl,
  76694. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3),
  76695. backgroundYRotation: 0,
  76696. sizeAuto: true,
  76697. setupImageProcessing: true,
  76698. environmentTexture: this._environmentTextureCDNUrl,
  76699. cameraExposure: 0.8,
  76700. cameraContrast: 1.6,
  76701. toneMappingEnabled: true,
  76702. };
  76703. };
  76704. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  76705. /**
  76706. * Gets the root mesh created by the helper.
  76707. */
  76708. get: function () {
  76709. return this._rootMesh;
  76710. },
  76711. enumerable: true,
  76712. configurable: true
  76713. });
  76714. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  76715. /**
  76716. * Gets the skybox created by the helper.
  76717. */
  76718. get: function () {
  76719. return this._skybox;
  76720. },
  76721. enumerable: true,
  76722. configurable: true
  76723. });
  76724. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  76725. /**
  76726. * Gets the skybox texture created by the helper.
  76727. */
  76728. get: function () {
  76729. return this._skyboxTexture;
  76730. },
  76731. enumerable: true,
  76732. configurable: true
  76733. });
  76734. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  76735. /**
  76736. * Gets the skybox material created by the helper.
  76737. */
  76738. get: function () {
  76739. return this._skyboxMaterial;
  76740. },
  76741. enumerable: true,
  76742. configurable: true
  76743. });
  76744. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  76745. /**
  76746. * Gets the ground mesh created by the helper.
  76747. */
  76748. get: function () {
  76749. return this._ground;
  76750. },
  76751. enumerable: true,
  76752. configurable: true
  76753. });
  76754. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  76755. /**
  76756. * Gets the ground texture created by the helper.
  76757. */
  76758. get: function () {
  76759. return this._groundTexture;
  76760. },
  76761. enumerable: true,
  76762. configurable: true
  76763. });
  76764. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  76765. /**
  76766. * Gets the ground mirror created by the helper.
  76767. */
  76768. get: function () {
  76769. return this._groundMirror;
  76770. },
  76771. enumerable: true,
  76772. configurable: true
  76773. });
  76774. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  76775. /**
  76776. * Gets the ground mirror render list to helps pushing the meshes
  76777. * you wish in the ground reflection.
  76778. */
  76779. get: function () {
  76780. return this._groundMirror.renderList;
  76781. },
  76782. enumerable: true,
  76783. configurable: true
  76784. });
  76785. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  76786. /**
  76787. * Gets the ground material created by the helper.
  76788. */
  76789. get: function () {
  76790. return this._groundMaterial;
  76791. },
  76792. enumerable: true,
  76793. configurable: true
  76794. });
  76795. /**
  76796. * Updates the background according to the new options
  76797. * @param options
  76798. */
  76799. EnvironmentHelper.prototype.updateOptions = function (options) {
  76800. var newOptions = __assign({}, this._options, options);
  76801. if (this._ground && !newOptions.createGround) {
  76802. this._ground.dispose();
  76803. this._ground = null;
  76804. }
  76805. if (this._groundMaterial && !newOptions.createGround) {
  76806. this._groundMaterial.dispose();
  76807. this._groundMaterial = null;
  76808. }
  76809. if (this._options.groundTexture && !newOptions.groundTexture && this._groundTexture) {
  76810. this._groundTexture.dispose();
  76811. this._groundTexture = null;
  76812. }
  76813. if (this._skybox && !newOptions.createSkybox) {
  76814. this._skybox.dispose();
  76815. this._skybox = null;
  76816. }
  76817. if (this._skyboxMaterial && !newOptions.createSkybox) {
  76818. this._skyboxMaterial.dispose();
  76819. this._skyboxMaterial = null;
  76820. }
  76821. if (this._options.skyboxTexture && !newOptions.skyboxTexture && this._skyboxTexture) {
  76822. this._skyboxTexture.dispose();
  76823. this._skyboxTexture = null;
  76824. }
  76825. if (this._groundMirror && !newOptions.enableGroundMirror) {
  76826. this._groundMirror.dispose();
  76827. this._groundMirror = null;
  76828. }
  76829. this._setupBackground();
  76830. if (this._options.environmentTexture && !newOptions.environmentTexture && this._scene.environmentTexture) {
  76831. this._scene.environmentTexture.dispose();
  76832. }
  76833. this._setupImageProcessing();
  76834. };
  76835. /**
  76836. * Sets the primary color of all the available elements.
  76837. * @param color
  76838. */
  76839. EnvironmentHelper.prototype.setMainColor = function (color) {
  76840. if (this.groundMaterial) {
  76841. this.groundMaterial.primaryColor = color;
  76842. }
  76843. if (this.skyboxMaterial) {
  76844. this.skyboxMaterial.primaryColor = color;
  76845. }
  76846. if (this.groundMirror) {
  76847. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  76848. }
  76849. };
  76850. /**
  76851. * Setup the image processing according to the specified options.
  76852. */
  76853. EnvironmentHelper.prototype._setupImageProcessing = function () {
  76854. if (this._options.setupImageProcessing) {
  76855. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  76856. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  76857. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  76858. this._setupEnvironmentTexture();
  76859. }
  76860. };
  76861. /**
  76862. * Setup the environment texture according to the specified options.
  76863. */
  76864. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  76865. if (this._scene.environmentTexture) {
  76866. return;
  76867. }
  76868. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  76869. this._scene.environmentTexture = this._options.environmentTexture;
  76870. return;
  76871. }
  76872. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  76873. this._scene.environmentTexture = environmentTexture;
  76874. };
  76875. /**
  76876. * Setup the background according to the specified options.
  76877. */
  76878. EnvironmentHelper.prototype._setupBackground = function () {
  76879. if (!this._rootMesh) {
  76880. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  76881. }
  76882. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  76883. if (this._options.createGround) {
  76884. this._setupGround();
  76885. this._setupGroundMaterial();
  76886. this._setupGroundDiffuseTexture();
  76887. if (this._options.enableGroundMirror) {
  76888. this._setupGroundMirrorTexture();
  76889. this._setupMirrorInGroundMaterial();
  76890. }
  76891. }
  76892. if (this._options.createSkybox) {
  76893. this._setupSkybox();
  76894. this._setupSkyboxMaterial();
  76895. this._setupSkyboxReflectionTexture();
  76896. }
  76897. };
  76898. /**
  76899. * Setup the ground according to the specified options.
  76900. */
  76901. EnvironmentHelper.prototype._setupGround = function () {
  76902. if (!this._ground) {
  76903. var size = this._options.groundSize;
  76904. if (this._options.sizeAuto) {
  76905. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  76906. this._scene.activeCamera.upperRadiusLimit) {
  76907. size = this._scene.activeCamera.upperRadiusLimit * 0.9;
  76908. }
  76909. }
  76910. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", size, this._scene);
  76911. }
  76912. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  76913. this._ground.receiveShadows = this._options.enableGroundShadow;
  76914. this._ground.parent = this._rootMesh;
  76915. };
  76916. /**
  76917. * Setup the ground material according to the specified options.
  76918. */
  76919. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  76920. if (!this._groundMaterial) {
  76921. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  76922. }
  76923. this._groundMaterial.alpha = this._options.groundOpacity;
  76924. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  76925. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  76926. this._groundMaterial.primaryLevel = 1;
  76927. this._groundMaterial.primaryColor = this._options.groundColor;
  76928. this._groundMaterial.secondaryLevel = 0;
  76929. this._groundMaterial.tertiaryLevel = 0;
  76930. this._groundMaterial.useRGBColor = false;
  76931. if (this._ground) {
  76932. this._ground.material = this._groundMaterial;
  76933. }
  76934. };
  76935. /**
  76936. * Setup the ground diffuse texture according to the specified options.
  76937. */
  76938. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  76939. if (!this._groundMaterial) {
  76940. return;
  76941. }
  76942. if (this._groundTexture) {
  76943. return;
  76944. }
  76945. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  76946. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  76947. return;
  76948. }
  76949. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  76950. diffuseTexture.gammaSpace = false;
  76951. diffuseTexture.hasAlpha = true;
  76952. this._groundMaterial.diffuseTexture = diffuseTexture;
  76953. };
  76954. /**
  76955. * Setup the ground mirror texture according to the specified options.
  76956. */
  76957. EnvironmentHelper.prototype._setupGroundMirrorTexture = function () {
  76958. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76959. if (!this._groundMirror) {
  76960. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  76961. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, 0);
  76962. this._groundMirror.anisotropicFilteringLevel = 1;
  76963. this._groundMirror.wrapU = wrapping;
  76964. this._groundMirror.wrapV = wrapping;
  76965. }
  76966. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  76967. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  76968. };
  76969. /**
  76970. * Setup the ground to receive the mirror texture.
  76971. */
  76972. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  76973. if (this._groundMaterial) {
  76974. this._groundMaterial.reflectionTexture = this._groundMirror;
  76975. this._groundMaterial.reflectionFresnel = true;
  76976. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  76977. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  76978. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  76979. }
  76980. };
  76981. /**
  76982. * Setup the skybox according to the specified options.
  76983. */
  76984. EnvironmentHelper.prototype._setupSkybox = function () {
  76985. if (!this._skybox) {
  76986. var size = this._options.skyboxSize;
  76987. if (this._options.sizeAuto) {
  76988. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  76989. this._scene.activeCamera.upperRadiusLimit) {
  76990. size = this._scene.activeCamera.upperRadiusLimit;
  76991. }
  76992. }
  76993. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", size, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  76994. }
  76995. this._skybox.parent = this._rootMesh;
  76996. };
  76997. /**
  76998. * Setup the skybox material according to the specified options.
  76999. */
  77000. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  77001. if (!this._skybox) {
  77002. return;
  77003. }
  77004. if (!this._skyboxMaterial) {
  77005. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  77006. }
  77007. this._skyboxMaterial.useRGBColor = false;
  77008. this._skyboxMaterial.primaryLevel = 1;
  77009. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  77010. this._skyboxMaterial.secondaryLevel = 0;
  77011. this._skyboxMaterial.tertiaryLevel = 0;
  77012. this._skybox.material = this._skyboxMaterial;
  77013. };
  77014. /**
  77015. * Setup the skybox reflection texture according to the specified options.
  77016. */
  77017. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  77018. if (!this._skyboxMaterial) {
  77019. return;
  77020. }
  77021. if (this._skyboxTexture) {
  77022. return;
  77023. }
  77024. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  77025. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  77026. return;
  77027. }
  77028. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  77029. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  77030. this._skyboxTexture.gammaSpace = false;
  77031. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  77032. };
  77033. /**
  77034. * Dispose all the elements created by the Helper.
  77035. */
  77036. EnvironmentHelper.prototype.dispose = function () {
  77037. if (this._groundMaterial) {
  77038. this._groundMaterial.dispose(true, true);
  77039. }
  77040. if (this._skyboxMaterial) {
  77041. this._skyboxMaterial.dispose(true, true);
  77042. }
  77043. this._rootMesh.dispose(true);
  77044. };
  77045. /**
  77046. * Default ground texture URL.
  77047. */
  77048. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  77049. /**
  77050. * Default skybox texture URL.
  77051. */
  77052. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  77053. /**
  77054. * Default environment texture URL.
  77055. */
  77056. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  77057. return EnvironmentHelper;
  77058. }());
  77059. BABYLON.EnvironmentHelper = EnvironmentHelper;
  77060. })(BABYLON || (BABYLON = {}));
  77061. //# sourceMappingURL=babylon.environmentHelper.js.map
  77062. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\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 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>\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#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}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\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>\nvoid main(void) {\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\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\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#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\ngl_FragColor=color;\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;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*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 AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\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\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\nvoid main() {\ngl_PointSize=1.0;\ngl_Position=vec4(position,1.0);\n}","gpuRenderParticlesPixelShader":"void main() {\ngl_FragColor=vec4(1.0);\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float timeDelta;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec3 outVelocity;\nvoid main() {\nif (age>=life) {\n\noutPosition=vec3(0,0,0);\n\noutAge=0.0;\noutLife=life;\n\noutVelocity=vec3(0,1,0);\n} else {\noutPosition=position+velocity*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutVelocity=velocity;\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#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(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=abs(texture2D(textureSampler,vUV).r);\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,1.0);\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=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 screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\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);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/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;\n}\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}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\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#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 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}","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);\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\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\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\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#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\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\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\ngl_FragColor=color;\n}"};
  77063. 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}","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#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}\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 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#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;\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":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(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=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\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","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\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\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\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#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#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 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 PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\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;\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","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 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};"};
  77064. (function universalModuleDefinition(root, factory) {
  77065. var f = factory();
  77066. if (root && root["BABYLON"]) {
  77067. return;
  77068. }
  77069. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  77070. globalObject["BABYLON"] = f;
  77071. if(true)
  77072. module.exports = f;
  77073. else if(typeof define === 'function' && define.amd)
  77074. define(["BABYLON"], factory);
  77075. else if(typeof exports === 'object')
  77076. exports["BABYLON"] = f;
  77077. else {
  77078. root["BABYLON"] = f;
  77079. }
  77080. })(this, function() {
  77081. return BABYLON;
  77082. });
  77083. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  77084. /***/ }),
  77085. /* 1 */
  77086. /***/ (function(module, exports) {
  77087. var g;
  77088. // This works in non-strict mode
  77089. g = (function() {
  77090. return this;
  77091. })();
  77092. try {
  77093. // This works if eval is allowed (see CSP)
  77094. g = g || Function("return this")() || (1,eval)("this");
  77095. } catch(e) {
  77096. // This works if the window reference is available
  77097. if(typeof window === "object")
  77098. g = window;
  77099. }
  77100. // g can still be undefined, but nothing to do about it...
  77101. // We return undefined, instead of nothing here, so it's
  77102. // easier to handle this case. if(!global) { ...}
  77103. module.exports = g;
  77104. /***/ }),
  77105. /* 2 */
  77106. /***/ (function(module, exports, __webpack_require__) {
  77107. "use strict";
  77108. Object.defineProperty(exports, "__esModule", { value: true });
  77109. var babylonjs_1 = __webpack_require__(0);
  77110. var ViewerManager = (function () {
  77111. function ViewerManager() {
  77112. this.viewers = {};
  77113. this.onViewerAddedObservable = new babylonjs_1.Observable();
  77114. }
  77115. ViewerManager.prototype.addViewer = function (viewer) {
  77116. this.viewers[viewer.getBaseId()] = viewer;
  77117. this._onViewerAdded(viewer);
  77118. };
  77119. ViewerManager.prototype.getViewerById = function (id) {
  77120. return this.viewers[id];
  77121. };
  77122. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  77123. for (var id in this.viewers) {
  77124. if (this.viewers[id].containerElement === element) {
  77125. return this.getViewerById(id);
  77126. }
  77127. }
  77128. };
  77129. ViewerManager.prototype.getViewerPromiseById = function (id) {
  77130. var _this = this;
  77131. return new Promise(function (resolve, reject) {
  77132. var viewerFunction = function (viewer) {
  77133. if (viewer.getBaseId() === id) {
  77134. resolve(viewer);
  77135. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  77136. }
  77137. };
  77138. _this.onViewerAddedObservable.add(viewerFunction);
  77139. });
  77140. };
  77141. ViewerManager.prototype._onViewerAdded = function (viewer) {
  77142. this.onViewerAdded && this.onViewerAdded(viewer);
  77143. this.onViewerAddedObservable.notifyObservers(viewer);
  77144. };
  77145. return ViewerManager;
  77146. }());
  77147. exports.viewerManager = new ViewerManager();
  77148. /***/ }),
  77149. /* 3 */
  77150. /***/ (function(module, exports, __webpack_require__) {
  77151. "use strict";
  77152. var __extends = (this && this.__extends) || (function () {
  77153. var extendStatics = Object.setPrototypeOf ||
  77154. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  77155. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  77156. return function (d, b) {
  77157. extendStatics(d, b);
  77158. function __() { this.constructor = d; }
  77159. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  77160. };
  77161. })();
  77162. Object.defineProperty(exports, "__esModule", { value: true });
  77163. var viewer_1 = __webpack_require__(4);
  77164. var babylonjs_1 = __webpack_require__(0);
  77165. var BABYLON = __webpack_require__(0);
  77166. window['BABYLON'] = BABYLON;
  77167. var DefaultViewer = (function (_super) {
  77168. __extends(DefaultViewer, _super);
  77169. function DefaultViewer(containerElement, initialConfiguration) {
  77170. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  77171. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  77172. _this.containerElement = containerElement;
  77173. _this.onModelLoaded = function (meshes) {
  77174. _this.setModelMetaData();
  77175. setTimeout(function () {
  77176. _this.hideLoadingScreen();
  77177. }, 500);
  77178. _this.scene.createDefaultCameraOrLight(true, true, true);
  77179. _this.camera = _this.scene.activeCamera;
  77180. meshes[0].rotation.y += Math.PI;
  77181. _this.setupCamera(meshes);
  77182. _this.setupLights(meshes);
  77183. return _this.initEnvironment();
  77184. };
  77185. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  77186. return _this;
  77187. }
  77188. DefaultViewer.prototype.initScene = function () {
  77189. var _this = this;
  77190. return _super.prototype.initScene.call(this).then(function () {
  77191. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  77192. return _this.scene;
  77193. });
  77194. };
  77195. DefaultViewer.prototype.onTemplatesLoaded = function () {
  77196. var _this = this;
  77197. this.showLoadingScreen();
  77198. var viewerElement = this.templateManager.getTemplate('viewer');
  77199. var navbar = this.templateManager.getTemplate('navBar');
  77200. if (viewerElement && navbar) {
  77201. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  77202. var navbarShown_1 = true;
  77203. var timeoutCancel_1;
  77204. var triggerNavbar = function (show, evt) {
  77205. if (show === void 0) { show = false; }
  77206. if (!navbar || evt.button > 0)
  77207. return;
  77208. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  77209. if (show === navbarShown_1)
  77210. return;
  77211. if (show) {
  77212. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  77213. navbarShown_1 = show;
  77214. }
  77215. else {
  77216. var visibilityTimeout = 2000;
  77217. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  77218. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  77219. }
  77220. timeoutCancel_1 = setTimeout(function () {
  77221. if (navbar) {
  77222. navbar.parent.style.bottom = '-' + navbarHeight_1;
  77223. }
  77224. navbarShown_1 = show;
  77225. }, visibilityTimeout);
  77226. }
  77227. };
  77228. viewerElement.parent.addEventListener('pointerout', triggerNavbar.bind(this, false));
  77229. viewerElement.parent.addEventListener('pointerdown', triggerNavbar.bind(this, true));
  77230. viewerElement.parent.addEventListener('pointerup', triggerNavbar.bind(this, false));
  77231. navbar.parent.addEventListener('pointerover', triggerNavbar.bind(this, true));
  77232. this.registerNavbarButtons();
  77233. }
  77234. var closeButton = document.getElementById('close-button');
  77235. if (closeButton) {
  77236. closeButton.addEventListener('pointerdown', function () {
  77237. _this.hideOverlayScreen();
  77238. });
  77239. }
  77240. return _super.prototype.onTemplatesLoaded.call(this);
  77241. };
  77242. DefaultViewer.prototype.registerNavbarButtons = function () {
  77243. var _this = this;
  77244. var isFullscreen = false;
  77245. var navbar = this.templateManager.getTemplate('navBar');
  77246. var viewerTemplate = this.templateManager.getTemplate('viewer');
  77247. if (!navbar || !viewerTemplate)
  77248. return;
  77249. var viewerElement = viewerTemplate.parent;
  77250. navbar.onEventTriggered.add(function (data) {
  77251. switch (data.event.type) {
  77252. case 'pointerdown':
  77253. var event_1 = data.event;
  77254. if (event_1.button === 0) {
  77255. switch (data.selector) {
  77256. case '#fullscreen-button':
  77257. if (!isFullscreen) {
  77258. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  77259. requestFullScreen.call(viewerElement);
  77260. }
  77261. else {
  77262. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen;
  77263. exitFullscreen.call(document);
  77264. }
  77265. isFullscreen = !isFullscreen;
  77266. break;
  77267. case '#help-button':
  77268. _this.showOverlayScreen('help');
  77269. break;
  77270. }
  77271. }
  77272. break;
  77273. }
  77274. });
  77275. };
  77276. DefaultViewer.prototype.prepareContainerElement = function () {
  77277. this.containerElement.style.position = 'relative';
  77278. this.containerElement.style.display = 'flex';
  77279. };
  77280. DefaultViewer.prototype.loadModel = function (model) {
  77281. var _this = this;
  77282. if (model === void 0) { model = this.configuration.model; }
  77283. this.showLoadingScreen();
  77284. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  77285. console.log(error);
  77286. _this.hideLoadingScreen();
  77287. _this.showOverlayScreen('error');
  77288. return _this.scene;
  77289. });
  77290. };
  77291. DefaultViewer.prototype.setModelMetaData = function () {
  77292. var navbar = this.templateManager.getTemplate('navBar');
  77293. if (!navbar)
  77294. return;
  77295. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  77296. if (metadataContainer && typeof this.configuration.model === 'object') {
  77297. if (this.configuration.model.title) {
  77298. var element = metadataContainer.querySelector('span.model-title');
  77299. if (element) {
  77300. element.innerHTML = this.configuration.model.title;
  77301. }
  77302. }
  77303. if (this.configuration.model.subtitle) {
  77304. var element = metadataContainer.querySelector('span.model-subtitle');
  77305. if (element) {
  77306. element.innerHTML = this.configuration.model.subtitle;
  77307. }
  77308. }
  77309. if (this.configuration.model.thumbnail) {
  77310. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + this.configuration.model.thumbnail + "')";
  77311. }
  77312. }
  77313. };
  77314. DefaultViewer.prototype.initEnvironment = function () {
  77315. if (this.configuration.skybox) {
  77316. var texture = void 0;
  77317. if (this.configuration.skybox.cubeTexture) {
  77318. if (typeof this.configuration.skybox.cubeTexture.url === 'string') {
  77319. texture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(this.configuration.skybox.cubeTexture.url, this.scene);
  77320. }
  77321. else {
  77322. texture = babylonjs_1.CubeTexture.CreateFromImages(this.configuration.skybox.cubeTexture.url, this.scene, this.configuration.skybox.cubeTexture.noMipMap);
  77323. }
  77324. }
  77325. if (texture) {
  77326. this.extendClassWithConfig(texture, this.configuration.skybox.cubeTexture);
  77327. var scale = this.configuration.skybox.scale || this.scene.activeCamera && (this.scene.activeCamera.maxZ - this.scene.activeCamera.minZ) / 2 || 1;
  77328. var box = this.scene.createDefaultSkybox(texture, this.configuration.skybox.pbr, scale, this.configuration.skybox.blur);
  77329. if (this.configuration.skybox.material && this.configuration.skybox.material.imageProcessingConfiguration && box) {
  77330. box.material.imageProcessingConfiguration = new babylonjs_1.ImageProcessingConfiguration();
  77331. }
  77332. this.extendClassWithConfig(box, this.configuration.skybox);
  77333. }
  77334. }
  77335. if (this.configuration.ground) {
  77336. var groundConfig = (typeof this.configuration.ground === 'boolean') ? {} : this.configuration.ground;
  77337. var ground = babylonjs_1.Mesh.CreateGround('ground', groundConfig.size || 1000, groundConfig.size || 1000, 8, this.scene);
  77338. if (this.configuration.ground === true || groundConfig.shadowOnly) {
  77339. ground.material = new babylonjs_1.ShadowOnlyMaterial('groundmat', this.scene);
  77340. }
  77341. else {
  77342. ground.material = new babylonjs_1.StandardMaterial('groundmat', this.scene);
  77343. }
  77344. if (this.configuration.ground === true) {
  77345. ground.receiveShadows = true;
  77346. ground.material.alpha = 0.4;
  77347. }
  77348. this.extendClassWithConfig(ground, groundConfig);
  77349. }
  77350. return Promise.resolve(this.scene);
  77351. };
  77352. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  77353. var _this = this;
  77354. var template = this.templateManager.getTemplate('overlay');
  77355. if (!template)
  77356. return Promise.reject('Overlay template not found');
  77357. return template.show((function (template) {
  77358. var canvasRect = _this.containerElement.getBoundingClientRect();
  77359. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  77360. template.parent.style.display = 'flex';
  77361. template.parent.style.width = canvasRect.width + "px";
  77362. template.parent.style.height = canvasRect.height + "px";
  77363. template.parent.style.opacity = "1";
  77364. var subTemplate = _this.templateManager.getTemplate(subScreen);
  77365. if (!subTemplate) {
  77366. return Promise.reject(subScreen + ' template not found');
  77367. }
  77368. return subTemplate.show((function (template) {
  77369. template.parent.style.display = 'flex';
  77370. return Promise.resolve(template);
  77371. }));
  77372. }));
  77373. };
  77374. DefaultViewer.prototype.hideOverlayScreen = function () {
  77375. var template = this.templateManager.getTemplate('overlay');
  77376. if (!template)
  77377. return Promise.reject('Overlay template not found');
  77378. return template.hide((function (template) {
  77379. template.parent.style.opacity = "0";
  77380. var onTransitionEnd = function () {
  77381. template.parent.removeEventListener("transitionend", onTransitionEnd);
  77382. template.parent.style.display = 'none';
  77383. };
  77384. template.parent.addEventListener("transitionend", onTransitionEnd);
  77385. var overlays = template.parent.querySelectorAll('.overlay');
  77386. if (overlays) {
  77387. for (var i = 0; i < overlays.length; ++i) {
  77388. var htmlElement = overlays.item(i);
  77389. htmlElement.style.display = 'none';
  77390. }
  77391. }
  77392. return Promise.resolve(template);
  77393. }));
  77394. };
  77395. DefaultViewer.prototype.showLoadingScreen = function () {
  77396. var _this = this;
  77397. var template = this.templateManager.getTemplate('loadingScreen');
  77398. if (!template)
  77399. return Promise.reject('oading Screen template not found');
  77400. return template.show((function (template) {
  77401. var canvasRect = _this.containerElement.getBoundingClientRect();
  77402. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  77403. template.parent.style.display = 'flex';
  77404. template.parent.style.width = canvasRect.width + "px";
  77405. template.parent.style.height = canvasRect.height + "px";
  77406. template.parent.style.opacity = "1";
  77407. template.parent.style.backgroundColor = "black";
  77408. return Promise.resolve(template);
  77409. }));
  77410. };
  77411. DefaultViewer.prototype.hideLoadingScreen = function () {
  77412. var template = this.templateManager.getTemplate('loadingScreen');
  77413. if (!template)
  77414. return Promise.reject('oading Screen template not found');
  77415. return template.hide((function (template) {
  77416. template.parent.style.opacity = "0";
  77417. var onTransitionEnd = function () {
  77418. template.parent.removeEventListener("transitionend", onTransitionEnd);
  77419. template.parent.style.display = 'none';
  77420. };
  77421. template.parent.addEventListener("transitionend", onTransitionEnd);
  77422. return Promise.resolve(template);
  77423. }));
  77424. };
  77425. DefaultViewer.prototype.setupLights = function (focusMeshes) {
  77426. var _this = this;
  77427. if (focusMeshes === void 0) { focusMeshes = []; }
  77428. var sceneConfig = this.configuration.scene || { defaultLight: true };
  77429. if (!sceneConfig.defaultLight && (this.configuration.lights && Object.keys(this.configuration.lights).length)) {
  77430. this.scene.lights.forEach(function (l) {
  77431. l.dispose();
  77432. });
  77433. Object.keys(this.configuration.lights).forEach(function (name, idx) {
  77434. var lightConfig = _this.configuration.lights && _this.configuration.lights[name] || { name: name, type: 0 };
  77435. lightConfig.name = name;
  77436. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  77437. if (!constructor)
  77438. return;
  77439. var light = constructor();
  77440. if (light.isEnabled() !== !lightConfig.disabled) {
  77441. light.setEnabled(!lightConfig.disabled);
  77442. }
  77443. _this.extendClassWithConfig(light, lightConfig);
  77444. if (light instanceof babylonjs_1.ShadowLight) {
  77445. if (lightConfig.shadowEnabled) {
  77446. var shadowGenerator = new BABYLON.ShadowGenerator(512, light);
  77447. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  77448. var shadownMap = shadowGenerator.getShadowMap();
  77449. if (!shadownMap)
  77450. return;
  77451. var renderList = shadownMap.renderList;
  77452. for (var index = 0; index < focusMeshes.length; index++) {
  77453. renderList && renderList.push(focusMeshes[index]);
  77454. }
  77455. }
  77456. }
  77457. });
  77458. }
  77459. };
  77460. DefaultViewer.prototype.setupCamera = function (focusMeshes) {
  77461. if (focusMeshes === void 0) { focusMeshes = []; }
  77462. var sceneConfig = this.configuration.scene || { autoRotate: false, defaultCamera: true };
  77463. if (sceneConfig.defaultCamera) {
  77464. return;
  77465. }
  77466. var cameraConfig = this.configuration.camera || {};
  77467. if (cameraConfig.position) {
  77468. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  77469. }
  77470. if (cameraConfig.rotation) {
  77471. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  77472. }
  77473. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  77474. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  77475. if (cameraConfig.behaviors) {
  77476. for (var name_1 in cameraConfig.behaviors) {
  77477. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  77478. }
  77479. }
  77480. ;
  77481. if (sceneConfig.autoRotate) {
  77482. this.camera.useAutoRotationBehavior = true;
  77483. }
  77484. };
  77485. DefaultViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  77486. var behavior;
  77487. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  77488. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  77489. switch (type) {
  77490. case 0:
  77491. behavior = new babylonjs_1.AutoRotationBehavior();
  77492. break;
  77493. case 1:
  77494. behavior = new babylonjs_1.BouncingBehavior();
  77495. break;
  77496. case 2:
  77497. behavior = new babylonjs_1.FramingBehavior();
  77498. break;
  77499. default:
  77500. behavior = null;
  77501. break;
  77502. }
  77503. if (behavior) {
  77504. if (typeof behaviorConfig === "object") {
  77505. this.extendClassWithConfig(behavior, behaviorConfig);
  77506. }
  77507. this.camera.addBehavior(behavior);
  77508. }
  77509. switch (type) {
  77510. case 0:
  77511. break;
  77512. case 1:
  77513. break;
  77514. case 2:
  77515. if (config.zoomOnBoundingInfo) {
  77516. var meshes = payload;
  77517. var bounding = meshes[0].getHierarchyBoundingVectors();
  77518. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  77519. }
  77520. break;
  77521. }
  77522. };
  77523. DefaultViewer.prototype.extendClassWithConfig = function (object, config) {
  77524. var _this = this;
  77525. if (!config)
  77526. return;
  77527. Object.keys(config).forEach(function (key) {
  77528. if (key in object && typeof object[key] !== 'function') {
  77529. if (typeof object[key] === 'function')
  77530. return;
  77531. if (typeof object[key] === 'object') {
  77532. _this.extendClassWithConfig(object[key], config[key]);
  77533. }
  77534. else {
  77535. object[key] = config[key];
  77536. }
  77537. }
  77538. });
  77539. };
  77540. return DefaultViewer;
  77541. }(viewer_1.AbstractViewer));
  77542. exports.DefaultViewer = DefaultViewer;
  77543. /***/ }),
  77544. /* 4 */
  77545. /***/ (function(module, exports, __webpack_require__) {
  77546. "use strict";
  77547. Object.defineProperty(exports, "__esModule", { value: true });
  77548. var viewerManager_1 = __webpack_require__(2);
  77549. var templateManager_1 = __webpack_require__(17);
  77550. var loader_1 = __webpack_require__(19);
  77551. var babylonjs_1 = __webpack_require__(0);
  77552. var promiseObservable_1 = __webpack_require__(29);
  77553. var AbstractViewer = (function () {
  77554. function AbstractViewer(containerElement, initialConfiguration) {
  77555. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  77556. var _this = this;
  77557. this.containerElement = containerElement;
  77558. if (containerElement.id) {
  77559. this.baseId = containerElement.id;
  77560. }
  77561. else {
  77562. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  77563. }
  77564. this.onSceneInitObservable = new promiseObservable_1.PromiseObservable();
  77565. this.onEngineInitObservable = new promiseObservable_1.PromiseObservable();
  77566. this.onModelLoadedObservable = new promiseObservable_1.PromiseObservable();
  77567. viewerManager_1.viewerManager.addViewer(this);
  77568. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  77569. this.prepareContainerElement();
  77570. loader_1.default.loadConfiguration(initialConfiguration).then(function (configuration) {
  77571. _this.configuration = configuration;
  77572. if (_this.configuration.observers) {
  77573. if (_this.configuration.observers.onEngineInit) {
  77574. _this.onEngineInitObservable.add(window[_this.configuration.observers.onEngineInit]);
  77575. }
  77576. if (_this.configuration.observers.onSceneInit) {
  77577. _this.onSceneInitObservable.add(window[_this.configuration.observers.onSceneInit]);
  77578. }
  77579. if (_this.configuration.observers.onModelLoaded) {
  77580. _this.onModelLoadedObservable.add(window[_this.configuration.observers.onModelLoaded]);
  77581. }
  77582. }
  77583. var templateConfiguration = _this.configuration.templates || {};
  77584. _this.templateManager.initTemplate(templateConfiguration);
  77585. _this.templateManager.onAllLoaded.add(function () {
  77586. _this.onTemplatesLoaded();
  77587. });
  77588. });
  77589. }
  77590. AbstractViewer.prototype.getBaseId = function () {
  77591. return this.baseId;
  77592. };
  77593. AbstractViewer.prototype.onTemplatesLoaded = function () {
  77594. var _this = this;
  77595. return this.initEngine().then(function () {
  77596. return _this.loadModel();
  77597. }).then(function () {
  77598. return _this;
  77599. });
  77600. };
  77601. AbstractViewer.prototype.initEngine = function () {
  77602. var _this = this;
  77603. var canvasElement = this.templateManager.getCanvas();
  77604. if (!canvasElement) {
  77605. return Promise.reject('Canvas element not found!');
  77606. }
  77607. var config = this.configuration.engine || {};
  77608. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing);
  77609. babylonjs_1.Database.IDBStorageEnabled = false;
  77610. window.addEventListener('resize', function () {
  77611. _this.engine.resize();
  77612. });
  77613. this.engine.runRenderLoop(function () {
  77614. _this.scene && _this.scene.render();
  77615. });
  77616. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  77617. this.engine.setHardwareScalingLevel(scale);
  77618. return this.onEngineInitObservable.notifyWithPromise(this.engine).then(function () {
  77619. return _this.engine;
  77620. });
  77621. };
  77622. AbstractViewer.prototype.initScene = function () {
  77623. var _this = this;
  77624. if (this.scene) {
  77625. this.scene.dispose();
  77626. }
  77627. this.scene = new babylonjs_1.Scene(this.engine);
  77628. this.scene.createDefaultCameraOrLight(true, true, true);
  77629. if (this.configuration.scene && this.configuration.scene.debug) {
  77630. this.scene.debugLayer.show();
  77631. }
  77632. return this.onSceneInitObservable.notifyWithPromise(this.scene).then(function () {
  77633. return _this.scene;
  77634. });
  77635. };
  77636. AbstractViewer.prototype.loadModel = function (model, clearScene) {
  77637. var _this = this;
  77638. if (model === void 0) { model = this.configuration.model; }
  77639. if (clearScene === void 0) { clearScene = true; }
  77640. var modelUrl = (typeof model === 'string') ? model : model.url;
  77641. var parts = modelUrl.split('/');
  77642. var filename = parts.pop();
  77643. var base = parts.join('/') + '/';
  77644. var plugin = (typeof model === 'string') ? undefined : model.loader;
  77645. return Promise.resolve().then(function () {
  77646. if (!_this.scene || clearScene)
  77647. return _this.initScene();
  77648. else
  77649. return _this.scene;
  77650. }).then(function () {
  77651. return new Promise(function (resolve, reject) {
  77652. babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, _this.scene, function (meshes) {
  77653. resolve(meshes);
  77654. }, undefined, function (e, m, exception) {
  77655. console.log(m, exception);
  77656. reject(m);
  77657. }, plugin);
  77658. });
  77659. }).then(function (meshes) {
  77660. return _this.onModelLoadedObservable.notifyWithPromise(meshes).then(function () {
  77661. return _this.scene;
  77662. });
  77663. });
  77664. };
  77665. return AbstractViewer;
  77666. }());
  77667. exports.AbstractViewer = AbstractViewer;
  77668. /***/ }),
  77669. /* 5 */
  77670. /***/ (function(module, exports, __webpack_require__) {
  77671. "use strict";
  77672. Object.defineProperty(exports, "__esModule", { value: true });
  77673. function isUrl(urlToCheck) {
  77674. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  77675. return true;
  77676. }
  77677. return false;
  77678. }
  77679. exports.isUrl = isUrl;
  77680. function loadFile(url) {
  77681. return new Promise(function (resolve, reject) {
  77682. var xhr = new XMLHttpRequest();
  77683. xhr.open('GET', url);
  77684. xhr.send();
  77685. xhr.onreadystatechange = function () {
  77686. var DONE = 4;
  77687. var OK = 200;
  77688. if (xhr.readyState === DONE) {
  77689. if (xhr.status === OK) {
  77690. resolve(xhr.responseText);
  77691. }
  77692. }
  77693. else {
  77694. console.log('Error: ' + xhr.status, url);
  77695. reject('Error: ' + xhr.status);
  77696. }
  77697. };
  77698. });
  77699. }
  77700. exports.loadFile = loadFile;
  77701. function kebabToCamel(s) {
  77702. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  77703. }
  77704. exports.kebabToCamel = kebabToCamel;
  77705. function camelToKebab(str) {
  77706. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  77707. }
  77708. exports.camelToKebab = camelToKebab;
  77709. /***/ }),
  77710. /* 6 */
  77711. /***/ (function(module, exports, __webpack_require__) {
  77712. "use strict";
  77713. Object.defineProperty(exports, "__esModule", { value: true });
  77714. var babylonjs_1 = __webpack_require__(0);
  77715. var helper_1 = __webpack_require__(5);
  77716. var HTMLMapper = (function () {
  77717. function HTMLMapper() {
  77718. }
  77719. HTMLMapper.prototype.map = function (element) {
  77720. var config = {};
  77721. var _loop_1 = function (attrIdx) {
  77722. var attr = element.attributes.item(attrIdx);
  77723. var split = attr.nodeName.split('.');
  77724. split.reduce(function (currentConfig, key, idx) {
  77725. var camelKey = helper_1.kebabToCamel(key);
  77726. if (idx === split.length - 1) {
  77727. var val = attr.nodeValue;
  77728. if (val === "true") {
  77729. val = true;
  77730. }
  77731. else if (val === "false") {
  77732. val = false;
  77733. }
  77734. else {
  77735. var number = parseFloat(val);
  77736. if (!isNaN(number)) {
  77737. val = number;
  77738. }
  77739. }
  77740. currentConfig[camelKey] = val;
  77741. }
  77742. else {
  77743. currentConfig[camelKey] = currentConfig[camelKey] || {};
  77744. }
  77745. return currentConfig[camelKey];
  77746. }, config);
  77747. };
  77748. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  77749. _loop_1(attrIdx);
  77750. }
  77751. return config;
  77752. };
  77753. return HTMLMapper;
  77754. }());
  77755. var JSONMapper = (function () {
  77756. function JSONMapper() {
  77757. }
  77758. JSONMapper.prototype.map = function (rawSource) {
  77759. return JSON.parse(rawSource);
  77760. };
  77761. return JSONMapper;
  77762. }());
  77763. var DOMMapper = (function () {
  77764. function DOMMapper() {
  77765. }
  77766. DOMMapper.prototype.map = function (baseElement) {
  77767. var htmlMapper = new HTMLMapper();
  77768. var config = htmlMapper.map(baseElement);
  77769. var traverseChildren = function (element, partConfig) {
  77770. var children = element.children;
  77771. if (children.length) {
  77772. for (var i = 0; i < children.length; ++i) {
  77773. var item = children.item(i);
  77774. var configMapped = htmlMapper.map(item);
  77775. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  77776. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  77777. partConfig[key] = [];
  77778. }
  77779. else {
  77780. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  77781. partConfig.push(configMapped);
  77782. }
  77783. else if (partConfig[key]) {
  77784. element.setAttribute('array', 'true');
  77785. var oldItem = partConfig[key];
  77786. partConfig = [oldItem, configMapped];
  77787. }
  77788. else {
  77789. partConfig[key] = configMapped;
  77790. }
  77791. }
  77792. traverseChildren(item, partConfig[key] || configMapped);
  77793. }
  77794. }
  77795. return partConfig;
  77796. };
  77797. traverseChildren(baseElement, config);
  77798. return config;
  77799. };
  77800. return DOMMapper;
  77801. }());
  77802. var MapperManager = (function () {
  77803. function MapperManager() {
  77804. this.mappers = {
  77805. "html": new HTMLMapper(),
  77806. "json": new JSONMapper(),
  77807. "dom": new DOMMapper()
  77808. };
  77809. }
  77810. MapperManager.prototype.getMapper = function (type) {
  77811. if (!this.mappers[type]) {
  77812. babylonjs_1.Tools.Error("No mapper defined for " + type);
  77813. }
  77814. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  77815. };
  77816. MapperManager.prototype.registerMapper = function (type, mapper) {
  77817. this.mappers[type] = mapper;
  77818. };
  77819. MapperManager.DefaultMapper = 'json';
  77820. return MapperManager;
  77821. }());
  77822. exports.MapperManager = MapperManager;
  77823. exports.mapperManager = new MapperManager();
  77824. exports.default = exports.mapperManager;
  77825. /***/ }),
  77826. /* 7 */
  77827. /***/ (function(module, exports) {
  77828. module.exports = "<viewer></viewer>\r\n<loading-screen></loading-screen>\r\n<overlay></overlay>";
  77829. /***/ }),
  77830. /* 8 */
  77831. /***/ (function(module, exports) {
  77832. module.exports = "<style>\r\n /* Loading Screen element */\r\n\r\n loading-screen {\r\n position: absolute;\r\n z-index: 100;\r\n opacity: 1;\r\n pointer-events: none;\r\n display: flex;\r\n justify-content: center;\r\n align-items: center;\r\n -webkit-transition: opacity 2s ease;\r\n -moz-transition: opacity 2s ease;\r\n transition: opacity 2s ease;\r\n }\r\n\r\n img.loading-image {\r\n -webkit-animation: spin 2s linear infinite;\r\n animation: spin 2s linear infinite;\r\n }\r\n\r\n @-webkit-keyframes spin {\r\n 0% {\r\n -webkit-transform: rotate(0deg);\r\n }\r\n 100% {\r\n -webkit-transform: rotate(360deg);\r\n }\r\n }\r\n\r\n @keyframes spin {\r\n 0% {\r\n transform: rotate(0deg);\r\n }\r\n 100% {\r\n transform: rotate(360deg);\r\n }\r\n }\r\n</style>\r\n\r\n<img class=\"loading-image\" src=\"{{loadingImage}}\">";
  77833. /***/ }),
  77834. /* 9 */
  77835. /***/ (function(module, exports) {
  77836. module.exports = "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"
  77837. /***/ }),
  77838. /* 10 */
  77839. /***/ (function(module, exports) {
  77840. module.exports = "<style>\r\n viewer {\r\n position: relative;\r\n overflow: hidden;\r\n /* Start stage */\r\n flex: 1;\r\n z-index: 1;\r\n justify-content: center;\r\n align-items: center;\r\n\r\n width: 100%;\r\n height: 100%;\r\n }\r\n\r\n .babylonjs-canvas {\r\n flex: 1;\r\n width: 100%;\r\n height: 100%;\r\n touch-action: none;\r\n }\r\n</style>\r\n\r\n<canvas class=\"babylonjs-canvas\" id=\"{{canvasId}}\">\r\n</canvas>\r\n\r\n<nav-bar></nav-bar>";
  77841. /***/ }),
  77842. /* 11 */
  77843. /***/ (function(module, exports) {
  77844. module.exports = "<style>\r\n overlay {\r\n position: absolute;\r\n z-index: 99;\r\n opacity: 0;\r\n display: flex;\r\n justify-content: center;\r\n align-items: center;\r\n -webkit-transition: opacity 1s ease;\r\n -moz-transition: opacity 1s ease;\r\n transition: opacity 1s ease;\r\n }\r\n\r\n .overlay-item {\r\n width: 100%;\r\n height: 100%;\r\n display: none;\r\n align-items: center;\r\n justify-content: center;\r\n background-color: rgba(121, 121, 121, 0.3);\r\n }\r\n\r\n error.overlay-item {\r\n background-color: rgba(121, 121, 121, 1);\r\n }\r\n\r\n div#close-button {\r\n position: absolute;\r\n top: 10px;\r\n right: 10px;\r\n width: 30px;\r\n height: 30px;\r\n cursor: pointer;\r\n }\r\n\r\n div#close-button img {\r\n width: 100%;\r\n }\r\n</style>\r\n\r\n<div id=\"close-button\">\r\n <img src=\"{{closeImage}}\" alt=\"{{closeText}}\">\r\n</div>\r\n<help class=\"overlay-item\"></help>\r\n<error class=\"overlay-item\"></error>\r\n<share class=\"overlay-item\"></share>";
  77845. /***/ }),
  77846. /* 12 */
  77847. /***/ (function(module, exports) {
  77848. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAAASAAAAEgARslrPgAAAPpJREFUaN7tmEEOgjAQAFHwh4SD/s5IPPBDMRkPlqQhYCzdtYvZORJTZtrAEqvKcRzHcZydANTAFbgorN0Cd+CkKd/z5ikZEeTHsPagEhHJT4xAJ7BuF8lP9BoBLfCY3SjrJGY7H695Fg+Qjvi5vGREMXmJiOLyORFm5LdEmJNPiTAr/02EefkoYmkgjSvXsgegVsTSSdje+YQIFfmjUsch8boNVh7Y5GFXSn6/D/GnV2XKsDMnP/uNvYiUIWUuYsuENROxRd5MRI588QgJ+WIRkvJFIviDv1Vq4Cax8wtrxycxAI14QLhRE05C/FMgnESvJu84juM4jgIvJPHlXUrVOPYAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTctMTAtMzBUMTA6NTQ6NDArMDA6MDBIpOL5AAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE3LTEwLTMwVDEwOjU0OjQwKzAwOjAwOflaRQAAACh0RVh0c3ZnOmJhc2UtdXJpAGZpbGU6Ly8vdG1wL21hZ2ljay1GZmF2R0Zvc8JGurIAAAAASUVORK5CYII="
  77849. /***/ }),
  77850. /* 13 */
  77851. /***/ (function(module, exports) {
  77852. module.exports = "Error loading the model";
  77853. /***/ }),
  77854. /* 14 */
  77855. /***/ (function(module, exports, __webpack_require__) {
  77856. "use strict";
  77857. /* WEBPACK VAR INJECTION */(function(global) {
  77858. Object.defineProperty(exports, "__esModule", { value: true });
  77859. var viewerManager_1 = __webpack_require__(2);
  77860. exports.viewerManager = viewerManager_1.viewerManager;
  77861. var defaultViewer_1 = __webpack_require__(3);
  77862. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  77863. var viewer_1 = __webpack_require__(4);
  77864. exports.AbstractViewer = viewer_1.AbstractViewer;
  77865. __webpack_require__(0);
  77866. __webpack_require__(30);
  77867. __webpack_require__(31);
  77868. var initializer_1 = __webpack_require__(32);
  77869. exports.InitTags = initializer_1.InitTags;
  77870. global.Promise = Promise || __webpack_require__(33).Promise;
  77871. exports.disableInit = false;
  77872. setTimeout(function () {
  77873. if (exports.disableInit)
  77874. return;
  77875. initializer_1.InitTags();
  77876. });
  77877. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  77878. /***/ }),
  77879. /* 15 */
  77880. /***/ (function(module, exports, __webpack_require__) {
  77881. var require;var require;/*
  77882. * Copyright (c) 2015 cannon.js Authors
  77883. *
  77884. * Permission is hereby granted, free of charge, to any person
  77885. * obtaining a copy of this software and associated documentation
  77886. * files (the "Software"), to deal in the Software without
  77887. * restriction, including without limitation the rights to use, copy,
  77888. * modify, merge, publish, distribute, sublicense, and/or sell copies
  77889. * of the Software, and to permit persons to whom the Software is
  77890. * furnished to do so, subject to the following conditions:
  77891. *
  77892. * The above copyright notice and this permission notice shall be
  77893. * included in all copies or substantial portions of the Software.
  77894. *
  77895. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  77896. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  77897. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  77898. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  77899. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  77900. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  77901. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  77902. */
  77903. !function(e){if(true)module.exports=e();else if("function"==typeof define&&false)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.CANNON=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return require(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  77904. module.exports={
  77905. "name": "cannon",
  77906. "version": "0.6.2",
  77907. "description": "A lightweight 3D physics engine written in JavaScript.",
  77908. "homepage": "https://github.com/schteppe/cannon.js",
  77909. "author": "Stefan Hedman <schteppe@gmail.com> (http://steffe.se)",
  77910. "keywords": [
  77911. "cannon.js",
  77912. "cannon",
  77913. "physics",
  77914. "engine",
  77915. "3d"
  77916. ],
  77917. "main": "./build/cannon.js",
  77918. "engines": {
  77919. "node": "*"
  77920. },
  77921. "repository": {
  77922. "type": "git",
  77923. "url": "https://github.com/schteppe/cannon.js.git"
  77924. },
  77925. "bugs": {
  77926. "url": "https://github.com/schteppe/cannon.js/issues"
  77927. },
  77928. "licenses": [
  77929. {
  77930. "type": "MIT"
  77931. }
  77932. ],
  77933. "devDependencies": {
  77934. "jshint": "latest",
  77935. "uglify-js": "latest",
  77936. "nodeunit": "^0.9.0",
  77937. "grunt": "~0.4.0",
  77938. "grunt-contrib-jshint": "~0.1.1",
  77939. "grunt-contrib-nodeunit": "^0.4.1",
  77940. "grunt-contrib-concat": "~0.1.3",
  77941. "grunt-contrib-uglify": "^0.5.1",
  77942. "grunt-browserify": "^2.1.4",
  77943. "grunt-contrib-yuidoc": "^0.5.2",
  77944. "browserify": "*"
  77945. },
  77946. "dependencies": {}
  77947. }
  77948. },{}],2:[function(_dereq_,module,exports){
  77949. // Export classes
  77950. module.exports = {
  77951. version : _dereq_('../package.json').version,
  77952. AABB : _dereq_('./collision/AABB'),
  77953. ArrayCollisionMatrix : _dereq_('./collision/ArrayCollisionMatrix'),
  77954. Body : _dereq_('./objects/Body'),
  77955. Box : _dereq_('./shapes/Box'),
  77956. Broadphase : _dereq_('./collision/Broadphase'),
  77957. Constraint : _dereq_('./constraints/Constraint'),
  77958. ContactEquation : _dereq_('./equations/ContactEquation'),
  77959. Narrowphase : _dereq_('./world/Narrowphase'),
  77960. ConeTwistConstraint : _dereq_('./constraints/ConeTwistConstraint'),
  77961. ContactMaterial : _dereq_('./material/ContactMaterial'),
  77962. ConvexPolyhedron : _dereq_('./shapes/ConvexPolyhedron'),
  77963. Cylinder : _dereq_('./shapes/Cylinder'),
  77964. DistanceConstraint : _dereq_('./constraints/DistanceConstraint'),
  77965. Equation : _dereq_('./equations/Equation'),
  77966. EventTarget : _dereq_('./utils/EventTarget'),
  77967. FrictionEquation : _dereq_('./equations/FrictionEquation'),
  77968. GSSolver : _dereq_('./solver/GSSolver'),
  77969. GridBroadphase : _dereq_('./collision/GridBroadphase'),
  77970. Heightfield : _dereq_('./shapes/Heightfield'),
  77971. HingeConstraint : _dereq_('./constraints/HingeConstraint'),
  77972. LockConstraint : _dereq_('./constraints/LockConstraint'),
  77973. Mat3 : _dereq_('./math/Mat3'),
  77974. Material : _dereq_('./material/Material'),
  77975. NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'),
  77976. ObjectCollisionMatrix : _dereq_('./collision/ObjectCollisionMatrix'),
  77977. Pool : _dereq_('./utils/Pool'),
  77978. Particle : _dereq_('./shapes/Particle'),
  77979. Plane : _dereq_('./shapes/Plane'),
  77980. PointToPointConstraint : _dereq_('./constraints/PointToPointConstraint'),
  77981. Quaternion : _dereq_('./math/Quaternion'),
  77982. Ray : _dereq_('./collision/Ray'),
  77983. RaycastVehicle : _dereq_('./objects/RaycastVehicle'),
  77984. RaycastResult : _dereq_('./collision/RaycastResult'),
  77985. RigidVehicle : _dereq_('./objects/RigidVehicle'),
  77986. RotationalEquation : _dereq_('./equations/RotationalEquation'),
  77987. RotationalMotorEquation : _dereq_('./equations/RotationalMotorEquation'),
  77988. SAPBroadphase : _dereq_('./collision/SAPBroadphase'),
  77989. SPHSystem : _dereq_('./objects/SPHSystem'),
  77990. Shape : _dereq_('./shapes/Shape'),
  77991. Solver : _dereq_('./solver/Solver'),
  77992. Sphere : _dereq_('./shapes/Sphere'),
  77993. SplitSolver : _dereq_('./solver/SplitSolver'),
  77994. Spring : _dereq_('./objects/Spring'),
  77995. Trimesh : _dereq_('./shapes/Trimesh'),
  77996. Vec3 : _dereq_('./math/Vec3'),
  77997. Vec3Pool : _dereq_('./utils/Vec3Pool'),
  77998. World : _dereq_('./world/World'),
  77999. };
  78000. },{"../package.json":1,"./collision/AABB":3,"./collision/ArrayCollisionMatrix":4,"./collision/Broadphase":5,"./collision/GridBroadphase":6,"./collision/NaiveBroadphase":7,"./collision/ObjectCollisionMatrix":8,"./collision/Ray":9,"./collision/RaycastResult":10,"./collision/SAPBroadphase":11,"./constraints/ConeTwistConstraint":12,"./constraints/Constraint":13,"./constraints/DistanceConstraint":14,"./constraints/HingeConstraint":15,"./constraints/LockConstraint":16,"./constraints/PointToPointConstraint":17,"./equations/ContactEquation":19,"./equations/Equation":20,"./equations/FrictionEquation":21,"./equations/RotationalEquation":22,"./equations/RotationalMotorEquation":23,"./material/ContactMaterial":24,"./material/Material":25,"./math/Mat3":27,"./math/Quaternion":28,"./math/Vec3":30,"./objects/Body":31,"./objects/RaycastVehicle":32,"./objects/RigidVehicle":33,"./objects/SPHSystem":34,"./objects/Spring":35,"./shapes/Box":37,"./shapes/ConvexPolyhedron":38,"./shapes/Cylinder":39,"./shapes/Heightfield":40,"./shapes/Particle":41,"./shapes/Plane":42,"./shapes/Shape":43,"./shapes/Sphere":44,"./shapes/Trimesh":45,"./solver/GSSolver":46,"./solver/Solver":47,"./solver/SplitSolver":48,"./utils/EventTarget":49,"./utils/Pool":51,"./utils/Vec3Pool":54,"./world/Narrowphase":55,"./world/World":56}],3:[function(_dereq_,module,exports){
  78001. var Vec3 = _dereq_('../math/Vec3');
  78002. var Utils = _dereq_('../utils/Utils');
  78003. module.exports = AABB;
  78004. /**
  78005. * Axis aligned bounding box class.
  78006. * @class AABB
  78007. * @constructor
  78008. * @param {Object} [options]
  78009. * @param {Vec3} [options.upperBound]
  78010. * @param {Vec3} [options.lowerBound]
  78011. */
  78012. function AABB(options){
  78013. options = options || {};
  78014. /**
  78015. * The lower bound of the bounding box.
  78016. * @property lowerBound
  78017. * @type {Vec3}
  78018. */
  78019. this.lowerBound = new Vec3();
  78020. if(options.lowerBound){
  78021. this.lowerBound.copy(options.lowerBound);
  78022. }
  78023. /**
  78024. * The upper bound of the bounding box.
  78025. * @property upperBound
  78026. * @type {Vec3}
  78027. */
  78028. this.upperBound = new Vec3();
  78029. if(options.upperBound){
  78030. this.upperBound.copy(options.upperBound);
  78031. }
  78032. }
  78033. var tmp = new Vec3();
  78034. /**
  78035. * Set the AABB bounds from a set of points.
  78036. * @method setFromPoints
  78037. * @param {Array} points An array of Vec3's.
  78038. * @param {Vec3} position
  78039. * @param {Quaternion} quaternion
  78040. * @param {number} skinSize
  78041. * @return {AABB} The self object
  78042. */
  78043. AABB.prototype.setFromPoints = function(points, position, quaternion, skinSize){
  78044. var l = this.lowerBound,
  78045. u = this.upperBound,
  78046. q = quaternion;
  78047. // Set to the first point
  78048. l.copy(points[0]);
  78049. if(q){
  78050. q.vmult(l, l);
  78051. }
  78052. u.copy(l);
  78053. for(var i = 1; i<points.length; i++){
  78054. var p = points[i];
  78055. if(q){
  78056. q.vmult(p, tmp);
  78057. p = tmp;
  78058. }
  78059. if(p.x > u.x){ u.x = p.x; }
  78060. if(p.x < l.x){ l.x = p.x; }
  78061. if(p.y > u.y){ u.y = p.y; }
  78062. if(p.y < l.y){ l.y = p.y; }
  78063. if(p.z > u.z){ u.z = p.z; }
  78064. if(p.z < l.z){ l.z = p.z; }
  78065. }
  78066. // Add offset
  78067. if (position) {
  78068. position.vadd(l, l);
  78069. position.vadd(u, u);
  78070. }
  78071. if(skinSize){
  78072. l.x -= skinSize;
  78073. l.y -= skinSize;
  78074. l.z -= skinSize;
  78075. u.x += skinSize;
  78076. u.y += skinSize;
  78077. u.z += skinSize;
  78078. }
  78079. return this;
  78080. };
  78081. /**
  78082. * Copy bounds from an AABB to this AABB
  78083. * @method copy
  78084. * @param {AABB} aabb Source to copy from
  78085. * @return {AABB} The this object, for chainability
  78086. */
  78087. AABB.prototype.copy = function(aabb){
  78088. this.lowerBound.copy(aabb.lowerBound);
  78089. this.upperBound.copy(aabb.upperBound);
  78090. return this;
  78091. };
  78092. /**
  78093. * Clone an AABB
  78094. * @method clone
  78095. */
  78096. AABB.prototype.clone = function(){
  78097. return new AABB().copy(this);
  78098. };
  78099. /**
  78100. * Extend this AABB so that it covers the given AABB too.
  78101. * @method extend
  78102. * @param {AABB} aabb
  78103. */
  78104. AABB.prototype.extend = function(aabb){
  78105. // Extend lower bound
  78106. var l = aabb.lowerBound.x;
  78107. if(this.lowerBound.x > l){
  78108. this.lowerBound.x = l;
  78109. }
  78110. // Upper
  78111. var u = aabb.upperBound.x;
  78112. if(this.upperBound.x < u){
  78113. this.upperBound.x = u;
  78114. }
  78115. // Extend lower bound
  78116. var l = aabb.lowerBound.y;
  78117. if(this.lowerBound.y > l){
  78118. this.lowerBound.y = l;
  78119. }
  78120. // Upper
  78121. var u = aabb.upperBound.y;
  78122. if(this.upperBound.y < u){
  78123. this.upperBound.y = u;
  78124. }
  78125. // Extend lower bound
  78126. var l = aabb.lowerBound.z;
  78127. if(this.lowerBound.z > l){
  78128. this.lowerBound.z = l;
  78129. }
  78130. // Upper
  78131. var u = aabb.upperBound.z;
  78132. if(this.upperBound.z < u){
  78133. this.upperBound.z = u;
  78134. }
  78135. };
  78136. /**
  78137. * Returns true if the given AABB overlaps this AABB.
  78138. * @method overlaps
  78139. * @param {AABB} aabb
  78140. * @return {Boolean}
  78141. */
  78142. AABB.prototype.overlaps = function(aabb){
  78143. var l1 = this.lowerBound,
  78144. u1 = this.upperBound,
  78145. l2 = aabb.lowerBound,
  78146. u2 = aabb.upperBound;
  78147. // l2 u2
  78148. // |---------|
  78149. // |--------|
  78150. // l1 u1
  78151. return ((l2.x <= u1.x && u1.x <= u2.x) || (l1.x <= u2.x && u2.x <= u1.x)) &&
  78152. ((l2.y <= u1.y && u1.y <= u2.y) || (l1.y <= u2.y && u2.y <= u1.y)) &&
  78153. ((l2.z <= u1.z && u1.z <= u2.z) || (l1.z <= u2.z && u2.z <= u1.z));
  78154. };
  78155. /**
  78156. * Returns true if the given AABB is fully contained in this AABB.
  78157. * @method contains
  78158. * @param {AABB} aabb
  78159. * @return {Boolean}
  78160. */
  78161. AABB.prototype.contains = function(aabb){
  78162. var l1 = this.lowerBound,
  78163. u1 = this.upperBound,
  78164. l2 = aabb.lowerBound,
  78165. u2 = aabb.upperBound;
  78166. // l2 u2
  78167. // |---------|
  78168. // |---------------|
  78169. // l1 u1
  78170. return (
  78171. (l1.x <= l2.x && u1.x >= u2.x) &&
  78172. (l1.y <= l2.y && u1.y >= u2.y) &&
  78173. (l1.z <= l2.z && u1.z >= u2.z)
  78174. );
  78175. };
  78176. /**
  78177. * @method getCorners
  78178. * @param {Vec3} a
  78179. * @param {Vec3} b
  78180. * @param {Vec3} c
  78181. * @param {Vec3} d
  78182. * @param {Vec3} e
  78183. * @param {Vec3} f
  78184. * @param {Vec3} g
  78185. * @param {Vec3} h
  78186. */
  78187. AABB.prototype.getCorners = function(a, b, c, d, e, f, g, h){
  78188. var l = this.lowerBound,
  78189. u = this.upperBound;
  78190. a.copy(l);
  78191. b.set( u.x, l.y, l.z );
  78192. c.set( u.x, u.y, l.z );
  78193. d.set( l.x, u.y, u.z );
  78194. e.set( u.x, l.y, l.z );
  78195. f.set( l.x, u.y, l.z );
  78196. g.set( l.x, l.y, u.z );
  78197. h.copy(u);
  78198. };
  78199. var transformIntoFrame_corners = [
  78200. new Vec3(),
  78201. new Vec3(),
  78202. new Vec3(),
  78203. new Vec3(),
  78204. new Vec3(),
  78205. new Vec3(),
  78206. new Vec3(),
  78207. new Vec3()
  78208. ];
  78209. /**
  78210. * Get the representation of an AABB in another frame.
  78211. * @method toLocalFrame
  78212. * @param {Transform} frame
  78213. * @param {AABB} target
  78214. * @return {AABB} The "target" AABB object.
  78215. */
  78216. AABB.prototype.toLocalFrame = function(frame, target){
  78217. var corners = transformIntoFrame_corners;
  78218. var a = corners[0];
  78219. var b = corners[1];
  78220. var c = corners[2];
  78221. var d = corners[3];
  78222. var e = corners[4];
  78223. var f = corners[5];
  78224. var g = corners[6];
  78225. var h = corners[7];
  78226. // Get corners in current frame
  78227. this.getCorners(a, b, c, d, e, f, g, h);
  78228. // Transform them to new local frame
  78229. for(var i=0; i !== 8; i++){
  78230. var corner = corners[i];
  78231. frame.pointToLocal(corner, corner);
  78232. }
  78233. return target.setFromPoints(corners);
  78234. };
  78235. /**
  78236. * Get the representation of an AABB in the global frame.
  78237. * @method toWorldFrame
  78238. * @param {Transform} frame
  78239. * @param {AABB} target
  78240. * @return {AABB} The "target" AABB object.
  78241. */
  78242. AABB.prototype.toWorldFrame = function(frame, target){
  78243. var corners = transformIntoFrame_corners;
  78244. var a = corners[0];
  78245. var b = corners[1];
  78246. var c = corners[2];
  78247. var d = corners[3];
  78248. var e = corners[4];
  78249. var f = corners[5];
  78250. var g = corners[6];
  78251. var h = corners[7];
  78252. // Get corners in current frame
  78253. this.getCorners(a, b, c, d, e, f, g, h);
  78254. // Transform them to new local frame
  78255. for(var i=0; i !== 8; i++){
  78256. var corner = corners[i];
  78257. frame.pointToWorld(corner, corner);
  78258. }
  78259. return target.setFromPoints(corners);
  78260. };
  78261. },{"../math/Vec3":30,"../utils/Utils":53}],4:[function(_dereq_,module,exports){
  78262. module.exports = ArrayCollisionMatrix;
  78263. /**
  78264. * Collision "matrix". It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step
  78265. * @class ArrayCollisionMatrix
  78266. * @constructor
  78267. */
  78268. function ArrayCollisionMatrix() {
  78269. /**
  78270. * The matrix storage
  78271. * @property matrix
  78272. * @type {Array}
  78273. */
  78274. this.matrix = [];
  78275. }
  78276. /**
  78277. * Get an element
  78278. * @method get
  78279. * @param {Number} i
  78280. * @param {Number} j
  78281. * @return {Number}
  78282. */
  78283. ArrayCollisionMatrix.prototype.get = function(i, j) {
  78284. i = i.index;
  78285. j = j.index;
  78286. if (j > i) {
  78287. var temp = j;
  78288. j = i;
  78289. i = temp;
  78290. }
  78291. return this.matrix[(i*(i + 1)>>1) + j-1];
  78292. };
  78293. /**
  78294. * Set an element
  78295. * @method set
  78296. * @param {Number} i
  78297. * @param {Number} j
  78298. * @param {Number} value
  78299. */
  78300. ArrayCollisionMatrix.prototype.set = function(i, j, value) {
  78301. i = i.index;
  78302. j = j.index;
  78303. if (j > i) {
  78304. var temp = j;
  78305. j = i;
  78306. i = temp;
  78307. }
  78308. this.matrix[(i*(i + 1)>>1) + j-1] = value ? 1 : 0;
  78309. };
  78310. /**
  78311. * Sets all elements to zero
  78312. * @method reset
  78313. */
  78314. ArrayCollisionMatrix.prototype.reset = function() {
  78315. for (var i=0, l=this.matrix.length; i!==l; i++) {
  78316. this.matrix[i]=0;
  78317. }
  78318. };
  78319. /**
  78320. * Sets the max number of objects
  78321. * @method setNumObjects
  78322. * @param {Number} n
  78323. */
  78324. ArrayCollisionMatrix.prototype.setNumObjects = function(n) {
  78325. this.matrix.length = n*(n-1)>>1;
  78326. };
  78327. },{}],5:[function(_dereq_,module,exports){
  78328. var Body = _dereq_('../objects/Body');
  78329. var Vec3 = _dereq_('../math/Vec3');
  78330. var Quaternion = _dereq_('../math/Quaternion');
  78331. var Shape = _dereq_('../shapes/Shape');
  78332. var Plane = _dereq_('../shapes/Plane');
  78333. module.exports = Broadphase;
  78334. /**
  78335. * Base class for broadphase implementations
  78336. * @class Broadphase
  78337. * @constructor
  78338. * @author schteppe
  78339. */
  78340. function Broadphase(){
  78341. /**
  78342. * The world to search for collisions in.
  78343. * @property world
  78344. * @type {World}
  78345. */
  78346. this.world = null;
  78347. /**
  78348. * If set to true, the broadphase uses bounding boxes for intersection test, else it uses bounding spheres.
  78349. * @property useBoundingBoxes
  78350. * @type {Boolean}
  78351. */
  78352. this.useBoundingBoxes = false;
  78353. /**
  78354. * Set to true if the objects in the world moved.
  78355. * @property {Boolean} dirty
  78356. */
  78357. this.dirty = true;
  78358. }
  78359. /**
  78360. * Get the collision pairs from the world
  78361. * @method collisionPairs
  78362. * @param {World} world The world to search in
  78363. * @param {Array} p1 Empty array to be filled with body objects
  78364. * @param {Array} p2 Empty array to be filled with body objects
  78365. */
  78366. Broadphase.prototype.collisionPairs = function(world,p1,p2){
  78367. throw new Error("collisionPairs not implemented for this BroadPhase class!");
  78368. };
  78369. /**
  78370. * Check if a body pair needs to be intersection tested at all.
  78371. * @method needBroadphaseCollision
  78372. * @param {Body} bodyA
  78373. * @param {Body} bodyB
  78374. * @return {bool}
  78375. */
  78376. var Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC = Body.STATIC | Body.KINEMATIC;
  78377. Broadphase.prototype.needBroadphaseCollision = function(bodyA,bodyB){
  78378. // Check collision filter masks
  78379. if( (bodyA.collisionFilterGroup & bodyB.collisionFilterMask)===0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask)===0){
  78380. return false;
  78381. }
  78382. // Check types
  78383. if(((bodyA.type & Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC)!==0 || bodyA.sleepState === Body.SLEEPING) &&
  78384. ((bodyB.type & Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC)!==0 || bodyB.sleepState === Body.SLEEPING)) {
  78385. // Both bodies are static, kinematic or sleeping. Skip.
  78386. return false;
  78387. }
  78388. return true;
  78389. };
  78390. /**
  78391. * Check if the bounding volumes of two bodies intersect.
  78392. * @method intersectionTest
  78393. * @param {Body} bodyA
  78394. * @param {Body} bodyB
  78395. * @param {array} pairs1
  78396. * @param {array} pairs2
  78397. */
  78398. Broadphase.prototype.intersectionTest = function(bodyA, bodyB, pairs1, pairs2){
  78399. if(this.useBoundingBoxes){
  78400. this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2);
  78401. } else {
  78402. this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2);
  78403. }
  78404. };
  78405. /**
  78406. * Check if the bounding spheres of two bodies are intersecting.
  78407. * @method doBoundingSphereBroadphase
  78408. * @param {Body} bodyA
  78409. * @param {Body} bodyB
  78410. * @param {Array} pairs1 bodyA is appended to this array if intersection
  78411. * @param {Array} pairs2 bodyB is appended to this array if intersection
  78412. */
  78413. var Broadphase_collisionPairs_r = new Vec3(), // Temp objects
  78414. Broadphase_collisionPairs_normal = new Vec3(),
  78415. Broadphase_collisionPairs_quat = new Quaternion(),
  78416. Broadphase_collisionPairs_relpos = new Vec3();
  78417. Broadphase.prototype.doBoundingSphereBroadphase = function(bodyA,bodyB,pairs1,pairs2){
  78418. var r = Broadphase_collisionPairs_r;
  78419. bodyB.position.vsub(bodyA.position,r);
  78420. var boundingRadiusSum2 = Math.pow(bodyA.boundingRadius + bodyB.boundingRadius, 2);
  78421. var norm2 = r.norm2();
  78422. if(norm2 < boundingRadiusSum2){
  78423. pairs1.push(bodyA);
  78424. pairs2.push(bodyB);
  78425. }
  78426. };
  78427. /**
  78428. * Check if the bounding boxes of two bodies are intersecting.
  78429. * @method doBoundingBoxBroadphase
  78430. * @param {Body} bodyA
  78431. * @param {Body} bodyB
  78432. * @param {Array} pairs1
  78433. * @param {Array} pairs2
  78434. */
  78435. Broadphase.prototype.doBoundingBoxBroadphase = function(bodyA,bodyB,pairs1,pairs2){
  78436. if(bodyA.aabbNeedsUpdate){
  78437. bodyA.computeAABB();
  78438. }
  78439. if(bodyB.aabbNeedsUpdate){
  78440. bodyB.computeAABB();
  78441. }
  78442. // Check AABB / AABB
  78443. if(bodyA.aabb.overlaps(bodyB.aabb)){
  78444. pairs1.push(bodyA);
  78445. pairs2.push(bodyB);
  78446. }
  78447. };
  78448. /**
  78449. * Removes duplicate pairs from the pair arrays.
  78450. * @method makePairsUnique
  78451. * @param {Array} pairs1
  78452. * @param {Array} pairs2
  78453. */
  78454. var Broadphase_makePairsUnique_temp = { keys:[] },
  78455. Broadphase_makePairsUnique_p1 = [],
  78456. Broadphase_makePairsUnique_p2 = [];
  78457. Broadphase.prototype.makePairsUnique = function(pairs1,pairs2){
  78458. var t = Broadphase_makePairsUnique_temp,
  78459. p1 = Broadphase_makePairsUnique_p1,
  78460. p2 = Broadphase_makePairsUnique_p2,
  78461. N = pairs1.length;
  78462. for(var i=0; i!==N; i++){
  78463. p1[i] = pairs1[i];
  78464. p2[i] = pairs2[i];
  78465. }
  78466. pairs1.length = 0;
  78467. pairs2.length = 0;
  78468. for(var i=0; i!==N; i++){
  78469. var id1 = p1[i].id,
  78470. id2 = p2[i].id;
  78471. var key = id1 < id2 ? id1+","+id2 : id2+","+id1;
  78472. t[key] = i;
  78473. t.keys.push(key);
  78474. }
  78475. for(var i=0; i!==t.keys.length; i++){
  78476. var key = t.keys.pop(),
  78477. pairIndex = t[key];
  78478. pairs1.push(p1[pairIndex]);
  78479. pairs2.push(p2[pairIndex]);
  78480. delete t[key];
  78481. }
  78482. };
  78483. /**
  78484. * To be implemented by subcasses
  78485. * @method setWorld
  78486. * @param {World} world
  78487. */
  78488. Broadphase.prototype.setWorld = function(world){
  78489. };
  78490. /**
  78491. * Check if the bounding spheres of two bodies overlap.
  78492. * @method boundingSphereCheck
  78493. * @param {Body} bodyA
  78494. * @param {Body} bodyB
  78495. * @return {boolean}
  78496. */
  78497. var bsc_dist = new Vec3();
  78498. Broadphase.boundingSphereCheck = function(bodyA,bodyB){
  78499. var dist = bsc_dist;
  78500. bodyA.position.vsub(bodyB.position,dist);
  78501. return Math.pow(bodyA.shape.boundingSphereRadius + bodyB.shape.boundingSphereRadius,2) > dist.norm2();
  78502. };
  78503. /**
  78504. * Returns all the bodies within the AABB.
  78505. * @method aabbQuery
  78506. * @param {World} world
  78507. * @param {AABB} aabb
  78508. * @param {array} result An array to store resulting bodies in.
  78509. * @return {array}
  78510. */
  78511. Broadphase.prototype.aabbQuery = function(world, aabb, result){
  78512. console.warn('.aabbQuery is not implemented in this Broadphase subclass.');
  78513. return [];
  78514. };
  78515. },{"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Plane":42,"../shapes/Shape":43}],6:[function(_dereq_,module,exports){
  78516. module.exports = GridBroadphase;
  78517. var Broadphase = _dereq_('./Broadphase');
  78518. var Vec3 = _dereq_('../math/Vec3');
  78519. var Shape = _dereq_('../shapes/Shape');
  78520. /**
  78521. * Axis aligned uniform grid broadphase.
  78522. * @class GridBroadphase
  78523. * @constructor
  78524. * @extends Broadphase
  78525. * @todo Needs support for more than just planes and spheres.
  78526. * @param {Vec3} aabbMin
  78527. * @param {Vec3} aabbMax
  78528. * @param {Number} nx Number of boxes along x
  78529. * @param {Number} ny Number of boxes along y
  78530. * @param {Number} nz Number of boxes along z
  78531. */
  78532. function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){
  78533. Broadphase.apply(this);
  78534. this.nx = nx || 10;
  78535. this.ny = ny || 10;
  78536. this.nz = nz || 10;
  78537. this.aabbMin = aabbMin || new Vec3(100,100,100);
  78538. this.aabbMax = aabbMax || new Vec3(-100,-100,-100);
  78539. var nbins = this.nx * this.ny * this.nz;
  78540. if (nbins <= 0) {
  78541. throw "GridBroadphase: Each dimension's n must be >0";
  78542. }
  78543. this.bins = [];
  78544. this.binLengths = []; //Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow
  78545. this.bins.length = nbins;
  78546. this.binLengths.length = nbins;
  78547. for (var i=0;i<nbins;i++) {
  78548. this.bins[i]=[];
  78549. this.binLengths[i]=0;
  78550. }
  78551. }
  78552. GridBroadphase.prototype = new Broadphase();
  78553. GridBroadphase.prototype.constructor = GridBroadphase;
  78554. /**
  78555. * Get all the collision pairs in the physics world
  78556. * @method collisionPairs
  78557. * @param {World} world
  78558. * @param {Array} pairs1
  78559. * @param {Array} pairs2
  78560. */
  78561. var GridBroadphase_collisionPairs_d = new Vec3();
  78562. var GridBroadphase_collisionPairs_binPos = new Vec3();
  78563. GridBroadphase.prototype.collisionPairs = function(world,pairs1,pairs2){
  78564. var N = world.numObjects(),
  78565. bodies = world.bodies;
  78566. var max = this.aabbMax,
  78567. min = this.aabbMin,
  78568. nx = this.nx,
  78569. ny = this.ny,
  78570. nz = this.nz;
  78571. var xstep = ny*nz;
  78572. var ystep = nz;
  78573. var zstep = 1;
  78574. var xmax = max.x,
  78575. ymax = max.y,
  78576. zmax = max.z,
  78577. xmin = min.x,
  78578. ymin = min.y,
  78579. zmin = min.z;
  78580. var xmult = nx / (xmax-xmin),
  78581. ymult = ny / (ymax-ymin),
  78582. zmult = nz / (zmax-zmin);
  78583. var binsizeX = (xmax - xmin) / nx,
  78584. binsizeY = (ymax - ymin) / ny,
  78585. binsizeZ = (zmax - zmin) / nz;
  78586. var binRadius = Math.sqrt(binsizeX*binsizeX + binsizeY*binsizeY + binsizeZ*binsizeZ) * 0.5;
  78587. var types = Shape.types;
  78588. var SPHERE = types.SPHERE,
  78589. PLANE = types.PLANE,
  78590. BOX = types.BOX,
  78591. COMPOUND = types.COMPOUND,
  78592. CONVEXPOLYHEDRON = types.CONVEXPOLYHEDRON;
  78593. var bins=this.bins,
  78594. binLengths=this.binLengths,
  78595. Nbins=this.bins.length;
  78596. // Reset bins
  78597. for(var i=0; i!==Nbins; i++){
  78598. binLengths[i] = 0;
  78599. }
  78600. var ceil = Math.ceil;
  78601. var min = Math.min;
  78602. var max = Math.max;
  78603. function addBoxToBins(x0,y0,z0,x1,y1,z1,bi) {
  78604. var xoff0 = ((x0 - xmin) * xmult)|0,
  78605. yoff0 = ((y0 - ymin) * ymult)|0,
  78606. zoff0 = ((z0 - zmin) * zmult)|0,
  78607. xoff1 = ceil((x1 - xmin) * xmult),
  78608. yoff1 = ceil((y1 - ymin) * ymult),
  78609. zoff1 = ceil((z1 - zmin) * zmult);
  78610. if (xoff0 < 0) { xoff0 = 0; } else if (xoff0 >= nx) { xoff0 = nx - 1; }
  78611. if (yoff0 < 0) { yoff0 = 0; } else if (yoff0 >= ny) { yoff0 = ny - 1; }
  78612. if (zoff0 < 0) { zoff0 = 0; } else if (zoff0 >= nz) { zoff0 = nz - 1; }
  78613. if (xoff1 < 0) { xoff1 = 0; } else if (xoff1 >= nx) { xoff1 = nx - 1; }
  78614. if (yoff1 < 0) { yoff1 = 0; } else if (yoff1 >= ny) { yoff1 = ny - 1; }
  78615. if (zoff1 < 0) { zoff1 = 0; } else if (zoff1 >= nz) { zoff1 = nz - 1; }
  78616. xoff0 *= xstep;
  78617. yoff0 *= ystep;
  78618. zoff0 *= zstep;
  78619. xoff1 *= xstep;
  78620. yoff1 *= ystep;
  78621. zoff1 *= zstep;
  78622. for (var xoff = xoff0; xoff <= xoff1; xoff += xstep) {
  78623. for (var yoff = yoff0; yoff <= yoff1; yoff += ystep) {
  78624. for (var zoff = zoff0; zoff <= zoff1; zoff += zstep) {
  78625. var idx = xoff+yoff+zoff;
  78626. bins[idx][binLengths[idx]++] = bi;
  78627. }
  78628. }
  78629. }
  78630. }
  78631. // Put all bodies into the bins
  78632. for(var i=0; i!==N; i++){
  78633. var bi = bodies[i];
  78634. var si = bi.shape;
  78635. switch(si.type){
  78636. case SPHERE:
  78637. // Put in bin
  78638. // check if overlap with other bins
  78639. var x = bi.position.x,
  78640. y = bi.position.y,
  78641. z = bi.position.z;
  78642. var r = si.radius;
  78643. addBoxToBins(x-r, y-r, z-r, x+r, y+r, z+r, bi);
  78644. break;
  78645. case PLANE:
  78646. if(si.worldNormalNeedsUpdate){
  78647. si.computeWorldNormal(bi.quaternion);
  78648. }
  78649. var planeNormal = si.worldNormal;
  78650. //Relative position from origin of plane object to the first bin
  78651. //Incremented as we iterate through the bins
  78652. var xreset = xmin + binsizeX*0.5 - bi.position.x,
  78653. yreset = ymin + binsizeY*0.5 - bi.position.y,
  78654. zreset = zmin + binsizeZ*0.5 - bi.position.z;
  78655. var d = GridBroadphase_collisionPairs_d;
  78656. d.set(xreset, yreset, zreset);
  78657. for (var xi = 0, xoff = 0; xi !== nx; xi++, xoff += xstep, d.y = yreset, d.x += binsizeX) {
  78658. for (var yi = 0, yoff = 0; yi !== ny; yi++, yoff += ystep, d.z = zreset, d.y += binsizeY) {
  78659. for (var zi = 0, zoff = 0; zi !== nz; zi++, zoff += zstep, d.z += binsizeZ) {
  78660. if (d.dot(planeNormal) < binRadius) {
  78661. var idx = xoff + yoff + zoff;
  78662. bins[idx][binLengths[idx]++] = bi;
  78663. }
  78664. }
  78665. }
  78666. }
  78667. break;
  78668. default:
  78669. if (bi.aabbNeedsUpdate) {
  78670. bi.computeAABB();
  78671. }
  78672. addBoxToBins(
  78673. bi.aabb.lowerBound.x,
  78674. bi.aabb.lowerBound.y,
  78675. bi.aabb.lowerBound.z,
  78676. bi.aabb.upperBound.x,
  78677. bi.aabb.upperBound.y,
  78678. bi.aabb.upperBound.z,
  78679. bi);
  78680. break;
  78681. }
  78682. }
  78683. // Check each bin
  78684. for(var i=0; i!==Nbins; i++){
  78685. var binLength = binLengths[i];
  78686. //Skip bins with no potential collisions
  78687. if (binLength > 1) {
  78688. var bin = bins[i];
  78689. // Do N^2 broadphase inside
  78690. for(var xi=0; xi!==binLength; xi++){
  78691. var bi = bin[xi];
  78692. for(var yi=0; yi!==xi; yi++){
  78693. var bj = bin[yi];
  78694. if(this.needBroadphaseCollision(bi,bj)){
  78695. this.intersectionTest(bi,bj,pairs1,pairs2);
  78696. }
  78697. }
  78698. }
  78699. }
  78700. }
  78701. // for (var zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) {
  78702. // console.log("layer "+zi);
  78703. // for (var yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) {
  78704. // var row = '';
  78705. // for (var xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) {
  78706. // var idx = xoff + yoff + zoff;
  78707. // row += ' ' + binLengths[idx];
  78708. // }
  78709. // console.log(row);
  78710. // }
  78711. // }
  78712. this.makePairsUnique(pairs1,pairs2);
  78713. };
  78714. },{"../math/Vec3":30,"../shapes/Shape":43,"./Broadphase":5}],7:[function(_dereq_,module,exports){
  78715. module.exports = NaiveBroadphase;
  78716. var Broadphase = _dereq_('./Broadphase');
  78717. var AABB = _dereq_('./AABB');
  78718. /**
  78719. * Naive broadphase implementation, used in lack of better ones.
  78720. * @class NaiveBroadphase
  78721. * @constructor
  78722. * @description The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 (which is bad)
  78723. * @extends Broadphase
  78724. */
  78725. function NaiveBroadphase(){
  78726. Broadphase.apply(this);
  78727. }
  78728. NaiveBroadphase.prototype = new Broadphase();
  78729. NaiveBroadphase.prototype.constructor = NaiveBroadphase;
  78730. /**
  78731. * Get all the collision pairs in the physics world
  78732. * @method collisionPairs
  78733. * @param {World} world
  78734. * @param {Array} pairs1
  78735. * @param {Array} pairs2
  78736. */
  78737. NaiveBroadphase.prototype.collisionPairs = function(world,pairs1,pairs2){
  78738. var bodies = world.bodies,
  78739. n = bodies.length,
  78740. i,j,bi,bj;
  78741. // Naive N^2 ftw!
  78742. for(i=0; i!==n; i++){
  78743. for(j=0; j!==i; j++){
  78744. bi = bodies[i];
  78745. bj = bodies[j];
  78746. if(!this.needBroadphaseCollision(bi,bj)){
  78747. continue;
  78748. }
  78749. this.intersectionTest(bi,bj,pairs1,pairs2);
  78750. }
  78751. }
  78752. };
  78753. var tmpAABB = new AABB();
  78754. /**
  78755. * Returns all the bodies within an AABB.
  78756. * @method aabbQuery
  78757. * @param {World} world
  78758. * @param {AABB} aabb
  78759. * @param {array} result An array to store resulting bodies in.
  78760. * @return {array}
  78761. */
  78762. NaiveBroadphase.prototype.aabbQuery = function(world, aabb, result){
  78763. result = result || [];
  78764. for(var i = 0; i < world.bodies.length; i++){
  78765. var b = world.bodies[i];
  78766. if(b.aabbNeedsUpdate){
  78767. b.computeAABB();
  78768. }
  78769. // Ugly hack until Body gets aabb
  78770. if(b.aabb.overlaps(aabb)){
  78771. result.push(b);
  78772. }
  78773. }
  78774. return result;
  78775. };
  78776. },{"./AABB":3,"./Broadphase":5}],8:[function(_dereq_,module,exports){
  78777. module.exports = ObjectCollisionMatrix;
  78778. /**
  78779. * Records what objects are colliding with each other
  78780. * @class ObjectCollisionMatrix
  78781. * @constructor
  78782. */
  78783. function ObjectCollisionMatrix() {
  78784. /**
  78785. * The matrix storage
  78786. * @property matrix
  78787. * @type {Object}
  78788. */
  78789. this.matrix = {};
  78790. }
  78791. /**
  78792. * @method get
  78793. * @param {Number} i
  78794. * @param {Number} j
  78795. * @return {Number}
  78796. */
  78797. ObjectCollisionMatrix.prototype.get = function(i, j) {
  78798. i = i.id;
  78799. j = j.id;
  78800. if (j > i) {
  78801. var temp = j;
  78802. j = i;
  78803. i = temp;
  78804. }
  78805. return i+'-'+j in this.matrix;
  78806. };
  78807. /**
  78808. * @method set
  78809. * @param {Number} i
  78810. * @param {Number} j
  78811. * @param {Number} value
  78812. */
  78813. ObjectCollisionMatrix.prototype.set = function(i, j, value) {
  78814. i = i.id;
  78815. j = j.id;
  78816. if (j > i) {
  78817. var temp = j;
  78818. j = i;
  78819. i = temp;
  78820. }
  78821. if (value) {
  78822. this.matrix[i+'-'+j] = true;
  78823. }
  78824. else {
  78825. delete this.matrix[i+'-'+j];
  78826. }
  78827. };
  78828. /**
  78829. * Empty the matrix
  78830. * @method reset
  78831. */
  78832. ObjectCollisionMatrix.prototype.reset = function() {
  78833. this.matrix = {};
  78834. };
  78835. /**
  78836. * Set max number of objects
  78837. * @method setNumObjects
  78838. * @param {Number} n
  78839. */
  78840. ObjectCollisionMatrix.prototype.setNumObjects = function(n) {
  78841. };
  78842. },{}],9:[function(_dereq_,module,exports){
  78843. module.exports = Ray;
  78844. var Vec3 = _dereq_('../math/Vec3');
  78845. var Quaternion = _dereq_('../math/Quaternion');
  78846. var Transform = _dereq_('../math/Transform');
  78847. var ConvexPolyhedron = _dereq_('../shapes/ConvexPolyhedron');
  78848. var Box = _dereq_('../shapes/Box');
  78849. var RaycastResult = _dereq_('../collision/RaycastResult');
  78850. var Shape = _dereq_('../shapes/Shape');
  78851. var AABB = _dereq_('../collision/AABB');
  78852. /**
  78853. * A line in 3D space that intersects bodies and return points.
  78854. * @class Ray
  78855. * @constructor
  78856. * @param {Vec3} from
  78857. * @param {Vec3} to
  78858. */
  78859. function Ray(from, to){
  78860. /**
  78861. * @property {Vec3} from
  78862. */
  78863. this.from = from ? from.clone() : new Vec3();
  78864. /**
  78865. * @property {Vec3} to
  78866. */
  78867. this.to = to ? to.clone() : new Vec3();
  78868. /**
  78869. * @private
  78870. * @property {Vec3} _direction
  78871. */
  78872. this._direction = new Vec3();
  78873. /**
  78874. * The precision of the ray. Used when checking parallelity etc.
  78875. * @property {Number} precision
  78876. */
  78877. this.precision = 0.0001;
  78878. /**
  78879. * Set to true if you want the Ray to take .collisionResponse flags into account on bodies and shapes.
  78880. * @property {Boolean} checkCollisionResponse
  78881. */
  78882. this.checkCollisionResponse = true;
  78883. /**
  78884. * If set to true, the ray skips any hits with normal.dot(rayDirection) < 0.
  78885. * @property {Boolean} skipBackfaces
  78886. */
  78887. this.skipBackfaces = false;
  78888. /**
  78889. * @property {number} collisionFilterMask
  78890. * @default -1
  78891. */
  78892. this.collisionFilterMask = -1;
  78893. /**
  78894. * @property {number} collisionFilterGroup
  78895. * @default -1
  78896. */
  78897. this.collisionFilterGroup = -1;
  78898. /**
  78899. * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST.
  78900. * @property {number} mode
  78901. */
  78902. this.mode = Ray.ANY;
  78903. /**
  78904. * Current result object.
  78905. * @property {RaycastResult} result
  78906. */
  78907. this.result = new RaycastResult();
  78908. /**
  78909. * Will be set to true during intersectWorld() if the ray hit anything.
  78910. * @property {Boolean} hasHit
  78911. */
  78912. this.hasHit = false;
  78913. /**
  78914. * Current, user-provided result callback. Will be used if mode is Ray.ALL.
  78915. * @property {Function} callback
  78916. */
  78917. this.callback = function(result){};
  78918. }
  78919. Ray.prototype.constructor = Ray;
  78920. Ray.CLOSEST = 1;
  78921. Ray.ANY = 2;
  78922. Ray.ALL = 4;
  78923. var tmpAABB = new AABB();
  78924. var tmpArray = [];
  78925. /**
  78926. * Do itersection against all bodies in the given World.
  78927. * @method intersectWorld
  78928. * @param {World} world
  78929. * @param {object} options
  78930. * @return {Boolean} True if the ray hit anything, otherwise false.
  78931. */
  78932. Ray.prototype.intersectWorld = function (world, options) {
  78933. this.mode = options.mode || Ray.ANY;
  78934. this.result = options.result || new RaycastResult();
  78935. this.skipBackfaces = !!options.skipBackfaces;
  78936. this.collisionFilterMask = typeof(options.collisionFilterMask) !== 'undefined' ? options.collisionFilterMask : -1;
  78937. this.collisionFilterGroup = typeof(options.collisionFilterGroup) !== 'undefined' ? options.collisionFilterGroup : -1;
  78938. if(options.from){
  78939. this.from.copy(options.from);
  78940. }
  78941. if(options.to){
  78942. this.to.copy(options.to);
  78943. }
  78944. this.callback = options.callback || function(){};
  78945. this.hasHit = false;
  78946. this.result.reset();
  78947. this._updateDirection();
  78948. this.getAABB(tmpAABB);
  78949. tmpArray.length = 0;
  78950. world.broadphase.aabbQuery(world, tmpAABB, tmpArray);
  78951. this.intersectBodies(tmpArray);
  78952. return this.hasHit;
  78953. };
  78954. var v1 = new Vec3(),
  78955. v2 = new Vec3();
  78956. /*
  78957. * As per "Barycentric Technique" as named here http://www.blackpawn.com/texts/pointinpoly/default.html But without the division
  78958. */
  78959. Ray.pointInTriangle = pointInTriangle;
  78960. function pointInTriangle(p, a, b, c) {
  78961. c.vsub(a,v0);
  78962. b.vsub(a,v1);
  78963. p.vsub(a,v2);
  78964. var dot00 = v0.dot( v0 );
  78965. var dot01 = v0.dot( v1 );
  78966. var dot02 = v0.dot( v2 );
  78967. var dot11 = v1.dot( v1 );
  78968. var dot12 = v1.dot( v2 );
  78969. var u,v;
  78970. return ( (u = dot11 * dot02 - dot01 * dot12) >= 0 ) &&
  78971. ( (v = dot00 * dot12 - dot01 * dot02) >= 0 ) &&
  78972. ( u + v < ( dot00 * dot11 - dot01 * dot01 ) );
  78973. }
  78974. /**
  78975. * Shoot a ray at a body, get back information about the hit.
  78976. * @method intersectBody
  78977. * @private
  78978. * @param {Body} body
  78979. * @param {RaycastResult} [result] Deprecated - set the result property of the Ray instead.
  78980. */
  78981. var intersectBody_xi = new Vec3();
  78982. var intersectBody_qi = new Quaternion();
  78983. Ray.prototype.intersectBody = function (body, result) {
  78984. if(result){
  78985. this.result = result;
  78986. this._updateDirection();
  78987. }
  78988. var checkCollisionResponse = this.checkCollisionResponse;
  78989. if(checkCollisionResponse && !body.collisionResponse){
  78990. return;
  78991. }
  78992. if((this.collisionFilterGroup & body.collisionFilterMask)===0 || (body.collisionFilterGroup & this.collisionFilterMask)===0){
  78993. return;
  78994. }
  78995. var xi = intersectBody_xi;
  78996. var qi = intersectBody_qi;
  78997. for (var i = 0, N = body.shapes.length; i < N; i++) {
  78998. var shape = body.shapes[i];
  78999. if(checkCollisionResponse && !shape.collisionResponse){
  79000. continue; // Skip
  79001. }
  79002. body.quaternion.mult(body.shapeOrientations[i], qi);
  79003. body.quaternion.vmult(body.shapeOffsets[i], xi);
  79004. xi.vadd(body.position, xi);
  79005. this.intersectShape(
  79006. shape,
  79007. qi,
  79008. xi,
  79009. body
  79010. );
  79011. if(this.result._shouldStop){
  79012. break;
  79013. }
  79014. }
  79015. };
  79016. /**
  79017. * @method intersectBodies
  79018. * @param {Array} bodies An array of Body objects.
  79019. * @param {RaycastResult} [result] Deprecated
  79020. */
  79021. Ray.prototype.intersectBodies = function (bodies, result) {
  79022. if(result){
  79023. this.result = result;
  79024. this._updateDirection();
  79025. }
  79026. for ( var i = 0, l = bodies.length; !this.result._shouldStop && i < l; i ++ ) {
  79027. this.intersectBody(bodies[i]);
  79028. }
  79029. };
  79030. /**
  79031. * Updates the _direction vector.
  79032. * @private
  79033. * @method _updateDirection
  79034. */
  79035. Ray.prototype._updateDirection = function(){
  79036. this.to.vsub(this.from, this._direction);
  79037. this._direction.normalize();
  79038. };
  79039. /**
  79040. * @method intersectShape
  79041. * @private
  79042. * @param {Shape} shape
  79043. * @param {Quaternion} quat
  79044. * @param {Vec3} position
  79045. * @param {Body} body
  79046. */
  79047. Ray.prototype.intersectShape = function(shape, quat, position, body){
  79048. var from = this.from;
  79049. // Checking boundingSphere
  79050. var distance = distanceFromIntersection(from, this._direction, position);
  79051. if ( distance > shape.boundingSphereRadius ) {
  79052. return;
  79053. }
  79054. var intersectMethod = this[shape.type];
  79055. if(intersectMethod){
  79056. intersectMethod.call(this, shape, quat, position, body);
  79057. }
  79058. };
  79059. var vector = new Vec3();
  79060. var normal = new Vec3();
  79061. var intersectPoint = new Vec3();
  79062. var a = new Vec3();
  79063. var b = new Vec3();
  79064. var c = new Vec3();
  79065. var d = new Vec3();
  79066. var tmpRaycastResult = new RaycastResult();
  79067. /**
  79068. * @method intersectBox
  79069. * @private
  79070. * @param {Shape} shape
  79071. * @param {Quaternion} quat
  79072. * @param {Vec3} position
  79073. * @param {Body} body
  79074. */
  79075. Ray.prototype.intersectBox = function(shape, quat, position, body){
  79076. return this.intersectConvex(shape.convexPolyhedronRepresentation, quat, position, body);
  79077. };
  79078. Ray.prototype[Shape.types.BOX] = Ray.prototype.intersectBox;
  79079. /**
  79080. * @method intersectPlane
  79081. * @private
  79082. * @param {Shape} shape
  79083. * @param {Quaternion} quat
  79084. * @param {Vec3} position
  79085. * @param {Body} body
  79086. */
  79087. Ray.prototype.intersectPlane = function(shape, quat, position, body){
  79088. var from = this.from;
  79089. var to = this.to;
  79090. var direction = this._direction;
  79091. // Get plane normal
  79092. var worldNormal = new Vec3(0, 0, 1);
  79093. quat.vmult(worldNormal, worldNormal);
  79094. var len = new Vec3();
  79095. from.vsub(position, len);
  79096. var planeToFrom = len.dot(worldNormal);
  79097. to.vsub(position, len);
  79098. var planeToTo = len.dot(worldNormal);
  79099. if(planeToFrom * planeToTo > 0){
  79100. // "from" and "to" are on the same side of the plane... bail out
  79101. return;
  79102. }
  79103. if(from.distanceTo(to) < planeToFrom){
  79104. return;
  79105. }
  79106. var n_dot_dir = worldNormal.dot(direction);
  79107. if (Math.abs(n_dot_dir) < this.precision) {
  79108. // No intersection
  79109. return;
  79110. }
  79111. var planePointToFrom = new Vec3();
  79112. var dir_scaled_with_t = new Vec3();
  79113. var hitPointWorld = new Vec3();
  79114. from.vsub(position, planePointToFrom);
  79115. var t = -worldNormal.dot(planePointToFrom) / n_dot_dir;
  79116. direction.scale(t, dir_scaled_with_t);
  79117. from.vadd(dir_scaled_with_t, hitPointWorld);
  79118. this.reportIntersection(worldNormal, hitPointWorld, shape, body, -1);
  79119. };
  79120. Ray.prototype[Shape.types.PLANE] = Ray.prototype.intersectPlane;
  79121. /**
  79122. * Get the world AABB of the ray.
  79123. * @method getAABB
  79124. * @param {AABB} aabb
  79125. */
  79126. Ray.prototype.getAABB = function(result){
  79127. var to = this.to;
  79128. var from = this.from;
  79129. result.lowerBound.x = Math.min(to.x, from.x);
  79130. result.lowerBound.y = Math.min(to.y, from.y);
  79131. result.lowerBound.z = Math.min(to.z, from.z);
  79132. result.upperBound.x = Math.max(to.x, from.x);
  79133. result.upperBound.y = Math.max(to.y, from.y);
  79134. result.upperBound.z = Math.max(to.z, from.z);
  79135. };
  79136. var intersectConvexOptions = {
  79137. faceList: [0]
  79138. };
  79139. /**
  79140. * @method intersectHeightfield
  79141. * @private
  79142. * @param {Shape} shape
  79143. * @param {Quaternion} quat
  79144. * @param {Vec3} position
  79145. * @param {Body} body
  79146. */
  79147. Ray.prototype.intersectHeightfield = function(shape, quat, position, body){
  79148. var data = shape.data,
  79149. w = shape.elementSize,
  79150. worldPillarOffset = new Vec3();
  79151. // Convert the ray to local heightfield coordinates
  79152. var localRay = new Ray(this.from, this.to);
  79153. Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from);
  79154. Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to);
  79155. // Get the index of the data points to test against
  79156. var index = [];
  79157. var iMinX = null;
  79158. var iMinY = null;
  79159. var iMaxX = null;
  79160. var iMaxY = null;
  79161. var inside = shape.getIndexOfPosition(localRay.from.x, localRay.from.y, index, false);
  79162. if(inside){
  79163. iMinX = index[0];
  79164. iMinY = index[1];
  79165. iMaxX = index[0];
  79166. iMaxY = index[1];
  79167. }
  79168. inside = shape.getIndexOfPosition(localRay.to.x, localRay.to.y, index, false);
  79169. if(inside){
  79170. if (iMinX === null || index[0] < iMinX) { iMinX = index[0]; }
  79171. if (iMaxX === null || index[0] > iMaxX) { iMaxX = index[0]; }
  79172. if (iMinY === null || index[1] < iMinY) { iMinY = index[1]; }
  79173. if (iMaxY === null || index[1] > iMaxY) { iMaxY = index[1]; }
  79174. }
  79175. if(iMinX === null){
  79176. return;
  79177. }
  79178. var minMax = [];
  79179. shape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  79180. var min = minMax[0];
  79181. var max = minMax[1];
  79182. // // Bail out if the ray can't touch the bounding box
  79183. // // TODO
  79184. // var aabb = new AABB();
  79185. // this.getAABB(aabb);
  79186. // if(aabb.intersects()){
  79187. // return;
  79188. // }
  79189. for(var i = iMinX; i <= iMaxX; i++){
  79190. for(var j = iMinY; j <= iMaxY; j++){
  79191. if(this.result._shouldStop){
  79192. return;
  79193. }
  79194. // Lower triangle
  79195. shape.getConvexTrianglePillar(i, j, false);
  79196. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  79197. this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, intersectConvexOptions);
  79198. if(this.result._shouldStop){
  79199. return;
  79200. }
  79201. // Upper triangle
  79202. shape.getConvexTrianglePillar(i, j, true);
  79203. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  79204. this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, intersectConvexOptions);
  79205. }
  79206. }
  79207. };
  79208. Ray.prototype[Shape.types.HEIGHTFIELD] = Ray.prototype.intersectHeightfield;
  79209. var Ray_intersectSphere_intersectionPoint = new Vec3();
  79210. var Ray_intersectSphere_normal = new Vec3();
  79211. /**
  79212. * @method intersectSphere
  79213. * @private
  79214. * @param {Shape} shape
  79215. * @param {Quaternion} quat
  79216. * @param {Vec3} position
  79217. * @param {Body} body
  79218. */
  79219. Ray.prototype.intersectSphere = function(shape, quat, position, body){
  79220. var from = this.from,
  79221. to = this.to,
  79222. r = shape.radius;
  79223. var a = Math.pow(to.x - from.x, 2) + Math.pow(to.y - from.y, 2) + Math.pow(to.z - from.z, 2);
  79224. var b = 2 * ((to.x - from.x) * (from.x - position.x) + (to.y - from.y) * (from.y - position.y) + (to.z - from.z) * (from.z - position.z));
  79225. var c = Math.pow(from.x - position.x, 2) + Math.pow(from.y - position.y, 2) + Math.pow(from.z - position.z, 2) - Math.pow(r, 2);
  79226. var delta = Math.pow(b, 2) - 4 * a * c;
  79227. var intersectionPoint = Ray_intersectSphere_intersectionPoint;
  79228. var normal = Ray_intersectSphere_normal;
  79229. if(delta < 0){
  79230. // No intersection
  79231. return;
  79232. } else if(delta === 0){
  79233. // single intersection point
  79234. from.lerp(to, delta, intersectionPoint);
  79235. intersectionPoint.vsub(position, normal);
  79236. normal.normalize();
  79237. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  79238. } else {
  79239. var d1 = (- b - Math.sqrt(delta)) / (2 * a);
  79240. var d2 = (- b + Math.sqrt(delta)) / (2 * a);
  79241. if(d1 >= 0 && d1 <= 1){
  79242. from.lerp(to, d1, intersectionPoint);
  79243. intersectionPoint.vsub(position, normal);
  79244. normal.normalize();
  79245. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  79246. }
  79247. if(this.result._shouldStop){
  79248. return;
  79249. }
  79250. if(d2 >= 0 && d2 <= 1){
  79251. from.lerp(to, d2, intersectionPoint);
  79252. intersectionPoint.vsub(position, normal);
  79253. normal.normalize();
  79254. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  79255. }
  79256. }
  79257. };
  79258. Ray.prototype[Shape.types.SPHERE] = Ray.prototype.intersectSphere;
  79259. var intersectConvex_normal = new Vec3();
  79260. var intersectConvex_minDistNormal = new Vec3();
  79261. var intersectConvex_minDistIntersect = new Vec3();
  79262. var intersectConvex_vector = new Vec3();
  79263. /**
  79264. * @method intersectConvex
  79265. * @private
  79266. * @param {Shape} shape
  79267. * @param {Quaternion} quat
  79268. * @param {Vec3} position
  79269. * @param {Body} body
  79270. * @param {object} [options]
  79271. * @param {array} [options.faceList]
  79272. */
  79273. Ray.prototype.intersectConvex = function intersectConvex(
  79274. shape,
  79275. quat,
  79276. position,
  79277. body,
  79278. options
  79279. ){
  79280. var minDistNormal = intersectConvex_minDistNormal;
  79281. var normal = intersectConvex_normal;
  79282. var vector = intersectConvex_vector;
  79283. var minDistIntersect = intersectConvex_minDistIntersect;
  79284. var faceList = (options && options.faceList) || null;
  79285. // Checking faces
  79286. var faces = shape.faces,
  79287. vertices = shape.vertices,
  79288. normals = shape.faceNormals;
  79289. var direction = this._direction;
  79290. var from = this.from;
  79291. var to = this.to;
  79292. var fromToDistance = from.distanceTo(to);
  79293. var minDist = -1;
  79294. var Nfaces = faceList ? faceList.length : faces.length;
  79295. var result = this.result;
  79296. for (var j = 0; !result._shouldStop && j < Nfaces; j++) {
  79297. var fi = faceList ? faceList[j] : j;
  79298. var face = faces[fi];
  79299. var faceNormal = normals[fi];
  79300. var q = quat;
  79301. var x = position;
  79302. // determine if ray intersects the plane of the face
  79303. // note: this works regardless of the direction of the face normal
  79304. // Get plane point in world coordinates...
  79305. vector.copy(vertices[face[0]]);
  79306. q.vmult(vector,vector);
  79307. vector.vadd(x,vector);
  79308. // ...but make it relative to the ray from. We'll fix this later.
  79309. vector.vsub(from,vector);
  79310. // Get plane normal
  79311. q.vmult(faceNormal,normal);
  79312. // If this dot product is negative, we have something interesting
  79313. var dot = direction.dot(normal);
  79314. // Bail out if ray and plane are parallel
  79315. if ( Math.abs( dot ) < this.precision ){
  79316. continue;
  79317. }
  79318. // calc distance to plane
  79319. var scalar = normal.dot(vector) / dot;
  79320. // if negative distance, then plane is behind ray
  79321. if (scalar < 0){
  79322. continue;
  79323. }
  79324. // if (dot < 0) {
  79325. // Intersection point is from + direction * scalar
  79326. direction.mult(scalar,intersectPoint);
  79327. intersectPoint.vadd(from,intersectPoint);
  79328. // a is the point we compare points b and c with.
  79329. a.copy(vertices[face[0]]);
  79330. q.vmult(a,a);
  79331. x.vadd(a,a);
  79332. for(var i = 1; !result._shouldStop && i < face.length - 1; i++){
  79333. // Transform 3 vertices to world coords
  79334. b.copy(vertices[face[i]]);
  79335. c.copy(vertices[face[i+1]]);
  79336. q.vmult(b,b);
  79337. q.vmult(c,c);
  79338. x.vadd(b,b);
  79339. x.vadd(c,c);
  79340. var distance = intersectPoint.distanceTo(from);
  79341. if(!(pointInTriangle(intersectPoint, a, b, c) || pointInTriangle(intersectPoint, b, a, c)) || distance > fromToDistance){
  79342. continue;
  79343. }
  79344. this.reportIntersection(normal, intersectPoint, shape, body, fi);
  79345. }
  79346. // }
  79347. }
  79348. };
  79349. Ray.prototype[Shape.types.CONVEXPOLYHEDRON] = Ray.prototype.intersectConvex;
  79350. var intersectTrimesh_normal = new Vec3();
  79351. var intersectTrimesh_localDirection = new Vec3();
  79352. var intersectTrimesh_localFrom = new Vec3();
  79353. var intersectTrimesh_localTo = new Vec3();
  79354. var intersectTrimesh_worldNormal = new Vec3();
  79355. var intersectTrimesh_worldIntersectPoint = new Vec3();
  79356. var intersectTrimesh_localAABB = new AABB();
  79357. var intersectTrimesh_triangles = [];
  79358. var intersectTrimesh_treeTransform = new Transform();
  79359. /**
  79360. * @method intersectTrimesh
  79361. * @private
  79362. * @param {Shape} shape
  79363. * @param {Quaternion} quat
  79364. * @param {Vec3} position
  79365. * @param {Body} body
  79366. * @param {object} [options]
  79367. * @todo Optimize by transforming the world to local space first.
  79368. * @todo Use Octree lookup
  79369. */
  79370. Ray.prototype.intersectTrimesh = function intersectTrimesh(
  79371. mesh,
  79372. quat,
  79373. position,
  79374. body,
  79375. options
  79376. ){
  79377. var normal = intersectTrimesh_normal;
  79378. var triangles = intersectTrimesh_triangles;
  79379. var treeTransform = intersectTrimesh_treeTransform;
  79380. var minDistNormal = intersectConvex_minDistNormal;
  79381. var vector = intersectConvex_vector;
  79382. var minDistIntersect = intersectConvex_minDistIntersect;
  79383. var localAABB = intersectTrimesh_localAABB;
  79384. var localDirection = intersectTrimesh_localDirection;
  79385. var localFrom = intersectTrimesh_localFrom;
  79386. var localTo = intersectTrimesh_localTo;
  79387. var worldIntersectPoint = intersectTrimesh_worldIntersectPoint;
  79388. var worldNormal = intersectTrimesh_worldNormal;
  79389. var faceList = (options && options.faceList) || null;
  79390. // Checking faces
  79391. var indices = mesh.indices,
  79392. vertices = mesh.vertices,
  79393. normals = mesh.faceNormals;
  79394. var from = this.from;
  79395. var to = this.to;
  79396. var direction = this._direction;
  79397. var minDist = -1;
  79398. treeTransform.position.copy(position);
  79399. treeTransform.quaternion.copy(quat);
  79400. // Transform ray to local space!
  79401. Transform.vectorToLocalFrame(position, quat, direction, localDirection);
  79402. //body.vectorToLocalFrame(direction, localDirection);
  79403. Transform.pointToLocalFrame(position, quat, from, localFrom);
  79404. //body.pointToLocalFrame(from, localFrom);
  79405. Transform.pointToLocalFrame(position, quat, to, localTo);
  79406. //body.pointToLocalFrame(to, localTo);
  79407. var fromToDistanceSquared = localFrom.distanceSquared(localTo);
  79408. mesh.tree.rayQuery(this, treeTransform, triangles);
  79409. for (var i = 0, N = triangles.length; !this.result._shouldStop && i !== N; i++) {
  79410. var trianglesIndex = triangles[i];
  79411. mesh.getNormal(trianglesIndex, normal);
  79412. // determine if ray intersects the plane of the face
  79413. // note: this works regardless of the direction of the face normal
  79414. // Get plane point in world coordinates...
  79415. mesh.getVertex(indices[trianglesIndex * 3], a);
  79416. // ...but make it relative to the ray from. We'll fix this later.
  79417. a.vsub(localFrom,vector);
  79418. // Get plane normal
  79419. // quat.vmult(normal, normal);
  79420. // If this dot product is negative, we have something interesting
  79421. var dot = localDirection.dot(normal);
  79422. // Bail out if ray and plane are parallel
  79423. // if (Math.abs( dot ) < this.precision){
  79424. // continue;
  79425. // }
  79426. // calc distance to plane
  79427. var scalar = normal.dot(vector) / dot;
  79428. // if negative distance, then plane is behind ray
  79429. if (scalar < 0){
  79430. continue;
  79431. }
  79432. // Intersection point is from + direction * scalar
  79433. localDirection.scale(scalar,intersectPoint);
  79434. intersectPoint.vadd(localFrom,intersectPoint);
  79435. // Get triangle vertices
  79436. mesh.getVertex(indices[trianglesIndex * 3 + 1], b);
  79437. mesh.getVertex(indices[trianglesIndex * 3 + 2], c);
  79438. var squaredDistance = intersectPoint.distanceSquared(localFrom);
  79439. if(!(pointInTriangle(intersectPoint, b, a, c) || pointInTriangle(intersectPoint, a, b, c)) || squaredDistance > fromToDistanceSquared){
  79440. continue;
  79441. }
  79442. // transform intersectpoint and normal to world
  79443. Transform.vectorToWorldFrame(quat, normal, worldNormal);
  79444. //body.vectorToWorldFrame(normal, worldNormal);
  79445. Transform.pointToWorldFrame(position, quat, intersectPoint, worldIntersectPoint);
  79446. //body.pointToWorldFrame(intersectPoint, worldIntersectPoint);
  79447. this.reportIntersection(worldNormal, worldIntersectPoint, mesh, body, trianglesIndex);
  79448. }
  79449. triangles.length = 0;
  79450. };
  79451. Ray.prototype[Shape.types.TRIMESH] = Ray.prototype.intersectTrimesh;
  79452. /**
  79453. * @method reportIntersection
  79454. * @private
  79455. * @param {Vec3} normal
  79456. * @param {Vec3} hitPointWorld
  79457. * @param {Shape} shape
  79458. * @param {Body} body
  79459. * @return {boolean} True if the intersections should continue
  79460. */
  79461. Ray.prototype.reportIntersection = function(normal, hitPointWorld, shape, body, hitFaceIndex){
  79462. var from = this.from;
  79463. var to = this.to;
  79464. var distance = from.distanceTo(hitPointWorld);
  79465. var result = this.result;
  79466. // Skip back faces?
  79467. if(this.skipBackfaces && normal.dot(this._direction) > 0){
  79468. return;
  79469. }
  79470. result.hitFaceIndex = typeof(hitFaceIndex) !== 'undefined' ? hitFaceIndex : -1;
  79471. switch(this.mode){
  79472. case Ray.ALL:
  79473. this.hasHit = true;
  79474. result.set(
  79475. from,
  79476. to,
  79477. normal,
  79478. hitPointWorld,
  79479. shape,
  79480. body,
  79481. distance
  79482. );
  79483. result.hasHit = true;
  79484. this.callback(result);
  79485. break;
  79486. case Ray.CLOSEST:
  79487. // Store if closer than current closest
  79488. if(distance < result.distance || !result.hasHit){
  79489. this.hasHit = true;
  79490. result.hasHit = true;
  79491. result.set(
  79492. from,
  79493. to,
  79494. normal,
  79495. hitPointWorld,
  79496. shape,
  79497. body,
  79498. distance
  79499. );
  79500. }
  79501. break;
  79502. case Ray.ANY:
  79503. // Report and stop.
  79504. this.hasHit = true;
  79505. result.hasHit = true;
  79506. result.set(
  79507. from,
  79508. to,
  79509. normal,
  79510. hitPointWorld,
  79511. shape,
  79512. body,
  79513. distance
  79514. );
  79515. result._shouldStop = true;
  79516. break;
  79517. }
  79518. };
  79519. var v0 = new Vec3(),
  79520. intersect = new Vec3();
  79521. function distanceFromIntersection(from, direction, position) {
  79522. // v0 is vector from from to position
  79523. position.vsub(from,v0);
  79524. var dot = v0.dot(direction);
  79525. // intersect = direction*dot + from
  79526. direction.mult(dot,intersect);
  79527. intersect.vadd(from,intersect);
  79528. var distance = position.distanceTo(intersect);
  79529. return distance;
  79530. }
  79531. },{"../collision/AABB":3,"../collision/RaycastResult":10,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../shapes/Box":37,"../shapes/ConvexPolyhedron":38,"../shapes/Shape":43}],10:[function(_dereq_,module,exports){
  79532. var Vec3 = _dereq_('../math/Vec3');
  79533. module.exports = RaycastResult;
  79534. /**
  79535. * Storage for Ray casting data.
  79536. * @class RaycastResult
  79537. * @constructor
  79538. */
  79539. function RaycastResult(){
  79540. /**
  79541. * @property {Vec3} rayFromWorld
  79542. */
  79543. this.rayFromWorld = new Vec3();
  79544. /**
  79545. * @property {Vec3} rayToWorld
  79546. */
  79547. this.rayToWorld = new Vec3();
  79548. /**
  79549. * @property {Vec3} hitNormalWorld
  79550. */
  79551. this.hitNormalWorld = new Vec3();
  79552. /**
  79553. * @property {Vec3} hitPointWorld
  79554. */
  79555. this.hitPointWorld = new Vec3();
  79556. /**
  79557. * @property {boolean} hasHit
  79558. */
  79559. this.hasHit = false;
  79560. /**
  79561. * The hit shape, or null.
  79562. * @property {Shape} shape
  79563. */
  79564. this.shape = null;
  79565. /**
  79566. * The hit body, or null.
  79567. * @property {Body} body
  79568. */
  79569. this.body = null;
  79570. /**
  79571. * The index of the hit triangle, if the hit shape was a trimesh.
  79572. * @property {number} hitFaceIndex
  79573. * @default -1
  79574. */
  79575. this.hitFaceIndex = -1;
  79576. /**
  79577. * Distance to the hit. Will be set to -1 if there was no hit.
  79578. * @property {number} distance
  79579. * @default -1
  79580. */
  79581. this.distance = -1;
  79582. /**
  79583. * If the ray should stop traversing the bodies.
  79584. * @private
  79585. * @property {Boolean} _shouldStop
  79586. * @default false
  79587. */
  79588. this._shouldStop = false;
  79589. }
  79590. /**
  79591. * Reset all result data.
  79592. * @method reset
  79593. */
  79594. RaycastResult.prototype.reset = function () {
  79595. this.rayFromWorld.setZero();
  79596. this.rayToWorld.setZero();
  79597. this.hitNormalWorld.setZero();
  79598. this.hitPointWorld.setZero();
  79599. this.hasHit = false;
  79600. this.shape = null;
  79601. this.body = null;
  79602. this.hitFaceIndex = -1;
  79603. this.distance = -1;
  79604. this._shouldStop = false;
  79605. };
  79606. /**
  79607. * @method abort
  79608. */
  79609. RaycastResult.prototype.abort = function(){
  79610. this._shouldStop = true;
  79611. };
  79612. /**
  79613. * @method set
  79614. * @param {Vec3} rayFromWorld
  79615. * @param {Vec3} rayToWorld
  79616. * @param {Vec3} hitNormalWorld
  79617. * @param {Vec3} hitPointWorld
  79618. * @param {Shape} shape
  79619. * @param {Body} body
  79620. * @param {number} distance
  79621. */
  79622. RaycastResult.prototype.set = function(
  79623. rayFromWorld,
  79624. rayToWorld,
  79625. hitNormalWorld,
  79626. hitPointWorld,
  79627. shape,
  79628. body,
  79629. distance
  79630. ){
  79631. this.rayFromWorld.copy(rayFromWorld);
  79632. this.rayToWorld.copy(rayToWorld);
  79633. this.hitNormalWorld.copy(hitNormalWorld);
  79634. this.hitPointWorld.copy(hitPointWorld);
  79635. this.shape = shape;
  79636. this.body = body;
  79637. this.distance = distance;
  79638. };
  79639. },{"../math/Vec3":30}],11:[function(_dereq_,module,exports){
  79640. var Shape = _dereq_('../shapes/Shape');
  79641. var Broadphase = _dereq_('../collision/Broadphase');
  79642. module.exports = SAPBroadphase;
  79643. /**
  79644. * Sweep and prune broadphase along one axis.
  79645. *
  79646. * @class SAPBroadphase
  79647. * @constructor
  79648. * @param {World} [world]
  79649. * @extends Broadphase
  79650. */
  79651. function SAPBroadphase(world){
  79652. Broadphase.apply(this);
  79653. /**
  79654. * List of bodies currently in the broadphase.
  79655. * @property axisList
  79656. * @type {Array}
  79657. */
  79658. this.axisList = [];
  79659. /**
  79660. * The world to search in.
  79661. * @property world
  79662. * @type {World}
  79663. */
  79664. this.world = null;
  79665. /**
  79666. * Axis to sort the bodies along. Set to 0 for x axis, and 1 for y axis. For best performance, choose an axis that the bodies are spread out more on.
  79667. * @property axisIndex
  79668. * @type {Number}
  79669. */
  79670. this.axisIndex = 0;
  79671. var axisList = this.axisList;
  79672. this._addBodyHandler = function(e){
  79673. axisList.push(e.body);
  79674. };
  79675. this._removeBodyHandler = function(e){
  79676. var idx = axisList.indexOf(e.body);
  79677. if(idx !== -1){
  79678. axisList.splice(idx,1);
  79679. }
  79680. };
  79681. if(world){
  79682. this.setWorld(world);
  79683. }
  79684. }
  79685. SAPBroadphase.prototype = new Broadphase();
  79686. /**
  79687. * Change the world
  79688. * @method setWorld
  79689. * @param {World} world
  79690. */
  79691. SAPBroadphase.prototype.setWorld = function(world){
  79692. // Clear the old axis array
  79693. this.axisList.length = 0;
  79694. // Add all bodies from the new world
  79695. for(var i=0; i<world.bodies.length; i++){
  79696. this.axisList.push(world.bodies[i]);
  79697. }
  79698. // Remove old handlers, if any
  79699. world.removeEventListener("addBody", this._addBodyHandler);
  79700. world.removeEventListener("removeBody", this._removeBodyHandler);
  79701. // Add handlers to update the list of bodies.
  79702. world.addEventListener("addBody", this._addBodyHandler);
  79703. world.addEventListener("removeBody", this._removeBodyHandler);
  79704. this.world = world;
  79705. this.dirty = true;
  79706. };
  79707. /**
  79708. * @static
  79709. * @method insertionSortX
  79710. * @param {Array} a
  79711. * @return {Array}
  79712. */
  79713. SAPBroadphase.insertionSortX = function(a) {
  79714. for(var i=1,l=a.length;i<l;i++) {
  79715. var v = a[i];
  79716. for(var j=i - 1;j>=0;j--) {
  79717. if(a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x){
  79718. break;
  79719. }
  79720. a[j+1] = a[j];
  79721. }
  79722. a[j+1] = v;
  79723. }
  79724. return a;
  79725. };
  79726. /**
  79727. * @static
  79728. * @method insertionSortY
  79729. * @param {Array} a
  79730. * @return {Array}
  79731. */
  79732. SAPBroadphase.insertionSortY = function(a) {
  79733. for(var i=1,l=a.length;i<l;i++) {
  79734. var v = a[i];
  79735. for(var j=i - 1;j>=0;j--) {
  79736. if(a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y){
  79737. break;
  79738. }
  79739. a[j+1] = a[j];
  79740. }
  79741. a[j+1] = v;
  79742. }
  79743. return a;
  79744. };
  79745. /**
  79746. * @static
  79747. * @method insertionSortZ
  79748. * @param {Array} a
  79749. * @return {Array}
  79750. */
  79751. SAPBroadphase.insertionSortZ = function(a) {
  79752. for(var i=1,l=a.length;i<l;i++) {
  79753. var v = a[i];
  79754. for(var j=i - 1;j>=0;j--) {
  79755. if(a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z){
  79756. break;
  79757. }
  79758. a[j+1] = a[j];
  79759. }
  79760. a[j+1] = v;
  79761. }
  79762. return a;
  79763. };
  79764. /**
  79765. * Collect all collision pairs
  79766. * @method collisionPairs
  79767. * @param {World} world
  79768. * @param {Array} p1
  79769. * @param {Array} p2
  79770. */
  79771. SAPBroadphase.prototype.collisionPairs = function(world,p1,p2){
  79772. var bodies = this.axisList,
  79773. N = bodies.length,
  79774. axisIndex = this.axisIndex,
  79775. i, j;
  79776. if(this.dirty){
  79777. this.sortList();
  79778. this.dirty = false;
  79779. }
  79780. // Look through the list
  79781. for(i=0; i !== N; i++){
  79782. var bi = bodies[i];
  79783. for(j=i+1; j < N; j++){
  79784. var bj = bodies[j];
  79785. if(!this.needBroadphaseCollision(bi,bj)){
  79786. continue;
  79787. }
  79788. if(!SAPBroadphase.checkBounds(bi,bj,axisIndex)){
  79789. break;
  79790. }
  79791. this.intersectionTest(bi,bj,p1,p2);
  79792. }
  79793. }
  79794. };
  79795. SAPBroadphase.prototype.sortList = function(){
  79796. var axisList = this.axisList;
  79797. var axisIndex = this.axisIndex;
  79798. var N = axisList.length;
  79799. // Update AABBs
  79800. for(var i = 0; i!==N; i++){
  79801. var bi = axisList[i];
  79802. if(bi.aabbNeedsUpdate){
  79803. bi.computeAABB();
  79804. }
  79805. }
  79806. // Sort the list
  79807. if(axisIndex === 0){
  79808. SAPBroadphase.insertionSortX(axisList);
  79809. } else if(axisIndex === 1){
  79810. SAPBroadphase.insertionSortY(axisList);
  79811. } else if(axisIndex === 2){
  79812. SAPBroadphase.insertionSortZ(axisList);
  79813. }
  79814. };
  79815. /**
  79816. * Check if the bounds of two bodies overlap, along the given SAP axis.
  79817. * @static
  79818. * @method checkBounds
  79819. * @param {Body} bi
  79820. * @param {Body} bj
  79821. * @param {Number} axisIndex
  79822. * @return {Boolean}
  79823. */
  79824. SAPBroadphase.checkBounds = function(bi, bj, axisIndex){
  79825. var biPos;
  79826. var bjPos;
  79827. if(axisIndex === 0){
  79828. biPos = bi.position.x;
  79829. bjPos = bj.position.x;
  79830. } else if(axisIndex === 1){
  79831. biPos = bi.position.y;
  79832. bjPos = bj.position.y;
  79833. } else if(axisIndex === 2){
  79834. biPos = bi.position.z;
  79835. bjPos = bj.position.z;
  79836. }
  79837. var ri = bi.boundingRadius,
  79838. rj = bj.boundingRadius,
  79839. boundA1 = biPos - ri,
  79840. boundA2 = biPos + ri,
  79841. boundB1 = bjPos - rj,
  79842. boundB2 = bjPos + rj;
  79843. return boundB1 < boundA2;
  79844. };
  79845. /**
  79846. * Computes the variance of the body positions and estimates the best
  79847. * axis to use. Will automatically set property .axisIndex.
  79848. * @method autoDetectAxis
  79849. */
  79850. SAPBroadphase.prototype.autoDetectAxis = function(){
  79851. var sumX=0,
  79852. sumX2=0,
  79853. sumY=0,
  79854. sumY2=0,
  79855. sumZ=0,
  79856. sumZ2=0,
  79857. bodies = this.axisList,
  79858. N = bodies.length,
  79859. invN=1/N;
  79860. for(var i=0; i!==N; i++){
  79861. var b = bodies[i];
  79862. var centerX = b.position.x;
  79863. sumX += centerX;
  79864. sumX2 += centerX*centerX;
  79865. var centerY = b.position.y;
  79866. sumY += centerY;
  79867. sumY2 += centerY*centerY;
  79868. var centerZ = b.position.z;
  79869. sumZ += centerZ;
  79870. sumZ2 += centerZ*centerZ;
  79871. }
  79872. var varianceX = sumX2 - sumX*sumX*invN,
  79873. varianceY = sumY2 - sumY*sumY*invN,
  79874. varianceZ = sumZ2 - sumZ*sumZ*invN;
  79875. if(varianceX > varianceY){
  79876. if(varianceX > varianceZ){
  79877. this.axisIndex = 0;
  79878. } else{
  79879. this.axisIndex = 2;
  79880. }
  79881. } else if(varianceY > varianceZ){
  79882. this.axisIndex = 1;
  79883. } else{
  79884. this.axisIndex = 2;
  79885. }
  79886. };
  79887. /**
  79888. * Returns all the bodies within an AABB.
  79889. * @method aabbQuery
  79890. * @param {World} world
  79891. * @param {AABB} aabb
  79892. * @param {array} result An array to store resulting bodies in.
  79893. * @return {array}
  79894. */
  79895. SAPBroadphase.prototype.aabbQuery = function(world, aabb, result){
  79896. result = result || [];
  79897. if(this.dirty){
  79898. this.sortList();
  79899. this.dirty = false;
  79900. }
  79901. var axisIndex = this.axisIndex, axis = 'x';
  79902. if(axisIndex === 1){ axis = 'y'; }
  79903. if(axisIndex === 2){ axis = 'z'; }
  79904. var axisList = this.axisList;
  79905. var lower = aabb.lowerBound[axis];
  79906. var upper = aabb.upperBound[axis];
  79907. for(var i = 0; i < axisList.length; i++){
  79908. var b = axisList[i];
  79909. if(b.aabbNeedsUpdate){
  79910. b.computeAABB();
  79911. }
  79912. if(b.aabb.overlaps(aabb)){
  79913. result.push(b);
  79914. }
  79915. }
  79916. return result;
  79917. };
  79918. },{"../collision/Broadphase":5,"../shapes/Shape":43}],12:[function(_dereq_,module,exports){
  79919. module.exports = ConeTwistConstraint;
  79920. var Constraint = _dereq_('./Constraint');
  79921. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  79922. var ConeEquation = _dereq_('../equations/ConeEquation');
  79923. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  79924. var ContactEquation = _dereq_('../equations/ContactEquation');
  79925. var Vec3 = _dereq_('../math/Vec3');
  79926. /**
  79927. * @class ConeTwistConstraint
  79928. * @constructor
  79929. * @author schteppe
  79930. * @param {Body} bodyA
  79931. * @param {Body} bodyB
  79932. * @param {object} [options]
  79933. * @param {Vec3} [options.pivotA]
  79934. * @param {Vec3} [options.pivotB]
  79935. * @param {Vec3} [options.axisA]
  79936. * @param {Vec3} [options.axisB]
  79937. * @param {Number} [options.maxForce=1e6]
  79938. * @extends PointToPointConstraint
  79939. */
  79940. function ConeTwistConstraint(bodyA, bodyB, options){
  79941. options = options || {};
  79942. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  79943. // Set pivot point in between
  79944. var pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  79945. var pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  79946. this.axisA = options.axisA ? options.axisA.clone() : new Vec3();
  79947. this.axisB = options.axisB ? options.axisB.clone() : new Vec3();
  79948. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  79949. this.collideConnected = !!options.collideConnected;
  79950. this.angle = typeof(options.angle) !== 'undefined' ? options.angle : 0;
  79951. /**
  79952. * @property {ConeEquation} coneEquation
  79953. */
  79954. var c = this.coneEquation = new ConeEquation(bodyA,bodyB,options);
  79955. /**
  79956. * @property {RotationalEquation} twistEquation
  79957. */
  79958. var t = this.twistEquation = new RotationalEquation(bodyA,bodyB,options);
  79959. this.twistAngle = typeof(options.twistAngle) !== 'undefined' ? options.twistAngle : 0;
  79960. // Make the cone equation push the bodies toward the cone axis, not outward
  79961. c.maxForce = 0;
  79962. c.minForce = -maxForce;
  79963. // Make the twist equation add torque toward the initial position
  79964. t.maxForce = 0;
  79965. t.minForce = -maxForce;
  79966. this.equations.push(c, t);
  79967. }
  79968. ConeTwistConstraint.prototype = new PointToPointConstraint();
  79969. ConeTwistConstraint.constructor = ConeTwistConstraint;
  79970. var ConeTwistConstraint_update_tmpVec1 = new Vec3();
  79971. var ConeTwistConstraint_update_tmpVec2 = new Vec3();
  79972. ConeTwistConstraint.prototype.update = function(){
  79973. var bodyA = this.bodyA,
  79974. bodyB = this.bodyB,
  79975. cone = this.coneEquation,
  79976. twist = this.twistEquation;
  79977. PointToPointConstraint.prototype.update.call(this);
  79978. // Update the axes to the cone constraint
  79979. bodyA.vectorToWorldFrame(this.axisA, cone.axisA);
  79980. bodyB.vectorToWorldFrame(this.axisB, cone.axisB);
  79981. // Update the world axes in the twist constraint
  79982. this.axisA.tangents(twist.axisA, twist.axisA);
  79983. bodyA.vectorToWorldFrame(twist.axisA, twist.axisA);
  79984. this.axisB.tangents(twist.axisB, twist.axisB);
  79985. bodyB.vectorToWorldFrame(twist.axisB, twist.axisB);
  79986. cone.angle = this.angle;
  79987. twist.maxAngle = this.twistAngle;
  79988. };
  79989. },{"../equations/ConeEquation":18,"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],13:[function(_dereq_,module,exports){
  79990. module.exports = Constraint;
  79991. var Utils = _dereq_('../utils/Utils');
  79992. /**
  79993. * Constraint base class
  79994. * @class Constraint
  79995. * @author schteppe
  79996. * @constructor
  79997. * @param {Body} bodyA
  79998. * @param {Body} bodyB
  79999. * @param {object} [options]
  80000. * @param {boolean} [options.collideConnected=true]
  80001. * @param {boolean} [options.wakeUpBodies=true]
  80002. */
  80003. function Constraint(bodyA, bodyB, options){
  80004. options = Utils.defaults(options,{
  80005. collideConnected : true,
  80006. wakeUpBodies : true,
  80007. });
  80008. /**
  80009. * Equations to be solved in this constraint
  80010. * @property equations
  80011. * @type {Array}
  80012. */
  80013. this.equations = [];
  80014. /**
  80015. * @property {Body} bodyA
  80016. */
  80017. this.bodyA = bodyA;
  80018. /**
  80019. * @property {Body} bodyB
  80020. */
  80021. this.bodyB = bodyB;
  80022. /**
  80023. * @property {Number} id
  80024. */
  80025. this.id = Constraint.idCounter++;
  80026. /**
  80027. * Set to true if you want the bodies to collide when they are connected.
  80028. * @property collideConnected
  80029. * @type {boolean}
  80030. */
  80031. this.collideConnected = options.collideConnected;
  80032. if(options.wakeUpBodies){
  80033. if(bodyA){
  80034. bodyA.wakeUp();
  80035. }
  80036. if(bodyB){
  80037. bodyB.wakeUp();
  80038. }
  80039. }
  80040. }
  80041. /**
  80042. * Update all the equations with data.
  80043. * @method update
  80044. */
  80045. Constraint.prototype.update = function(){
  80046. throw new Error("method update() not implmemented in this Constraint subclass!");
  80047. };
  80048. /**
  80049. * Enables all equations in the constraint.
  80050. * @method enable
  80051. */
  80052. Constraint.prototype.enable = function(){
  80053. var eqs = this.equations;
  80054. for(var i=0; i<eqs.length; i++){
  80055. eqs[i].enabled = true;
  80056. }
  80057. };
  80058. /**
  80059. * Disables all equations in the constraint.
  80060. * @method disable
  80061. */
  80062. Constraint.prototype.disable = function(){
  80063. var eqs = this.equations;
  80064. for(var i=0; i<eqs.length; i++){
  80065. eqs[i].enabled = false;
  80066. }
  80067. };
  80068. Constraint.idCounter = 0;
  80069. },{"../utils/Utils":53}],14:[function(_dereq_,module,exports){
  80070. module.exports = DistanceConstraint;
  80071. var Constraint = _dereq_('./Constraint');
  80072. var ContactEquation = _dereq_('../equations/ContactEquation');
  80073. /**
  80074. * Constrains two bodies to be at a constant distance from each others center of mass.
  80075. * @class DistanceConstraint
  80076. * @constructor
  80077. * @author schteppe
  80078. * @param {Body} bodyA
  80079. * @param {Body} bodyB
  80080. * @param {Number} [distance] The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB
  80081. * @param {Number} [maxForce=1e6]
  80082. * @extends Constraint
  80083. */
  80084. function DistanceConstraint(bodyA,bodyB,distance,maxForce){
  80085. Constraint.call(this,bodyA,bodyB);
  80086. if(typeof(distance)==="undefined") {
  80087. distance = bodyA.position.distanceTo(bodyB.position);
  80088. }
  80089. if(typeof(maxForce)==="undefined") {
  80090. maxForce = 1e6;
  80091. }
  80092. /**
  80093. * @property {number} distance
  80094. */
  80095. this.distance = distance;
  80096. /**
  80097. * @property {ContactEquation} distanceEquation
  80098. */
  80099. var eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);
  80100. this.equations.push(eq);
  80101. // Make it bidirectional
  80102. eq.minForce = -maxForce;
  80103. eq.maxForce = maxForce;
  80104. }
  80105. DistanceConstraint.prototype = new Constraint();
  80106. DistanceConstraint.prototype.update = function(){
  80107. var bodyA = this.bodyA;
  80108. var bodyB = this.bodyB;
  80109. var eq = this.distanceEquation;
  80110. var halfDist = this.distance * 0.5;
  80111. var normal = eq.ni;
  80112. bodyB.position.vsub(bodyA.position, normal);
  80113. normal.normalize();
  80114. normal.mult(halfDist, eq.ri);
  80115. normal.mult(-halfDist, eq.rj);
  80116. };
  80117. },{"../equations/ContactEquation":19,"./Constraint":13}],15:[function(_dereq_,module,exports){
  80118. module.exports = HingeConstraint;
  80119. var Constraint = _dereq_('./Constraint');
  80120. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  80121. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  80122. var RotationalMotorEquation = _dereq_('../equations/RotationalMotorEquation');
  80123. var ContactEquation = _dereq_('../equations/ContactEquation');
  80124. var Vec3 = _dereq_('../math/Vec3');
  80125. /**
  80126. * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation.
  80127. * @class HingeConstraint
  80128. * @constructor
  80129. * @author schteppe
  80130. * @param {Body} bodyA
  80131. * @param {Body} bodyB
  80132. * @param {object} [options]
  80133. * @param {Vec3} [options.pivotA] A point defined locally in bodyA. This defines the offset of axisA.
  80134. * @param {Vec3} [options.axisA] An axis that bodyA can rotate around, defined locally in bodyA.
  80135. * @param {Vec3} [options.pivotB]
  80136. * @param {Vec3} [options.axisB]
  80137. * @param {Number} [options.maxForce=1e6]
  80138. * @extends PointToPointConstraint
  80139. */
  80140. function HingeConstraint(bodyA, bodyB, options){
  80141. options = options || {};
  80142. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  80143. var pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  80144. var pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  80145. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  80146. /**
  80147. * Rotation axis, defined locally in bodyA.
  80148. * @property {Vec3} axisA
  80149. */
  80150. var axisA = this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1,0,0);
  80151. axisA.normalize();
  80152. /**
  80153. * Rotation axis, defined locally in bodyB.
  80154. * @property {Vec3} axisB
  80155. */
  80156. var axisB = this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1,0,0);
  80157. axisB.normalize();
  80158. /**
  80159. * @property {RotationalEquation} rotationalEquation1
  80160. */
  80161. var r1 = this.rotationalEquation1 = new RotationalEquation(bodyA,bodyB,options);
  80162. /**
  80163. * @property {RotationalEquation} rotationalEquation2
  80164. */
  80165. var r2 = this.rotationalEquation2 = new RotationalEquation(bodyA,bodyB,options);
  80166. /**
  80167. * @property {RotationalMotorEquation} motorEquation
  80168. */
  80169. var motor = this.motorEquation = new RotationalMotorEquation(bodyA,bodyB,maxForce);
  80170. motor.enabled = false; // Not enabled by default
  80171. // Equations to be fed to the solver
  80172. this.equations.push(
  80173. r1, // rotational1
  80174. r2, // rotational2
  80175. motor
  80176. );
  80177. }
  80178. HingeConstraint.prototype = new PointToPointConstraint();
  80179. HingeConstraint.constructor = HingeConstraint;
  80180. /**
  80181. * @method enableMotor
  80182. */
  80183. HingeConstraint.prototype.enableMotor = function(){
  80184. this.motorEquation.enabled = true;
  80185. };
  80186. /**
  80187. * @method disableMotor
  80188. */
  80189. HingeConstraint.prototype.disableMotor = function(){
  80190. this.motorEquation.enabled = false;
  80191. };
  80192. /**
  80193. * @method setMotorSpeed
  80194. * @param {number} speed
  80195. */
  80196. HingeConstraint.prototype.setMotorSpeed = function(speed){
  80197. this.motorEquation.targetVelocity = speed;
  80198. };
  80199. /**
  80200. * @method setMotorMaxForce
  80201. * @param {number} maxForce
  80202. */
  80203. HingeConstraint.prototype.setMotorMaxForce = function(maxForce){
  80204. this.motorEquation.maxForce = maxForce;
  80205. this.motorEquation.minForce = -maxForce;
  80206. };
  80207. var HingeConstraint_update_tmpVec1 = new Vec3();
  80208. var HingeConstraint_update_tmpVec2 = new Vec3();
  80209. HingeConstraint.prototype.update = function(){
  80210. var bodyA = this.bodyA,
  80211. bodyB = this.bodyB,
  80212. motor = this.motorEquation,
  80213. r1 = this.rotationalEquation1,
  80214. r2 = this.rotationalEquation2,
  80215. worldAxisA = HingeConstraint_update_tmpVec1,
  80216. worldAxisB = HingeConstraint_update_tmpVec2;
  80217. var axisA = this.axisA;
  80218. var axisB = this.axisB;
  80219. PointToPointConstraint.prototype.update.call(this);
  80220. // Get world axes
  80221. bodyA.quaternion.vmult(axisA, worldAxisA);
  80222. bodyB.quaternion.vmult(axisB, worldAxisB);
  80223. worldAxisA.tangents(r1.axisA, r2.axisA);
  80224. r1.axisB.copy(worldAxisB);
  80225. r2.axisB.copy(worldAxisB);
  80226. if(this.motorEquation.enabled){
  80227. bodyA.quaternion.vmult(this.axisA, motor.axisA);
  80228. bodyB.quaternion.vmult(this.axisB, motor.axisB);
  80229. }
  80230. };
  80231. },{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],16:[function(_dereq_,module,exports){
  80232. module.exports = LockConstraint;
  80233. var Constraint = _dereq_('./Constraint');
  80234. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  80235. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  80236. var RotationalMotorEquation = _dereq_('../equations/RotationalMotorEquation');
  80237. var ContactEquation = _dereq_('../equations/ContactEquation');
  80238. var Vec3 = _dereq_('../math/Vec3');
  80239. /**
  80240. * Lock constraint. Will remove all degrees of freedom between the bodies.
  80241. * @class LockConstraint
  80242. * @constructor
  80243. * @author schteppe
  80244. * @param {Body} bodyA
  80245. * @param {Body} bodyB
  80246. * @param {object} [options]
  80247. * @param {Number} [options.maxForce=1e6]
  80248. * @extends PointToPointConstraint
  80249. */
  80250. function LockConstraint(bodyA, bodyB, options){
  80251. options = options || {};
  80252. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  80253. // Set pivot point in between
  80254. var pivotA = new Vec3();
  80255. var pivotB = new Vec3();
  80256. var halfWay = new Vec3();
  80257. bodyA.position.vadd(bodyB.position, halfWay);
  80258. halfWay.scale(0.5, halfWay);
  80259. bodyB.pointToLocalFrame(halfWay, pivotB);
  80260. bodyA.pointToLocalFrame(halfWay, pivotA);
  80261. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  80262. /**
  80263. * @property {RotationalEquation} rotationalEquation1
  80264. */
  80265. var r1 = this.rotationalEquation1 = new RotationalEquation(bodyA,bodyB,options);
  80266. /**
  80267. * @property {RotationalEquation} rotationalEquation2
  80268. */
  80269. var r2 = this.rotationalEquation2 = new RotationalEquation(bodyA,bodyB,options);
  80270. /**
  80271. * @property {RotationalEquation} rotationalEquation3
  80272. */
  80273. var r3 = this.rotationalEquation3 = new RotationalEquation(bodyA,bodyB,options);
  80274. this.equations.push(r1, r2, r3);
  80275. }
  80276. LockConstraint.prototype = new PointToPointConstraint();
  80277. LockConstraint.constructor = LockConstraint;
  80278. var LockConstraint_update_tmpVec1 = new Vec3();
  80279. var LockConstraint_update_tmpVec2 = new Vec3();
  80280. LockConstraint.prototype.update = function(){
  80281. var bodyA = this.bodyA,
  80282. bodyB = this.bodyB,
  80283. motor = this.motorEquation,
  80284. r1 = this.rotationalEquation1,
  80285. r2 = this.rotationalEquation2,
  80286. r3 = this.rotationalEquation3,
  80287. worldAxisA = LockConstraint_update_tmpVec1,
  80288. worldAxisB = LockConstraint_update_tmpVec2;
  80289. PointToPointConstraint.prototype.update.call(this);
  80290. bodyA.vectorToWorldFrame(Vec3.UNIT_X, r1.axisA);
  80291. bodyB.vectorToWorldFrame(Vec3.UNIT_Y, r1.axisB);
  80292. bodyA.vectorToWorldFrame(Vec3.UNIT_Y, r2.axisA);
  80293. bodyB.vectorToWorldFrame(Vec3.UNIT_Z, r2.axisB);
  80294. bodyA.vectorToWorldFrame(Vec3.UNIT_Z, r3.axisA);
  80295. bodyB.vectorToWorldFrame(Vec3.UNIT_X, r3.axisB);
  80296. };
  80297. },{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],17:[function(_dereq_,module,exports){
  80298. module.exports = PointToPointConstraint;
  80299. var Constraint = _dereq_('./Constraint');
  80300. var ContactEquation = _dereq_('../equations/ContactEquation');
  80301. var Vec3 = _dereq_('../math/Vec3');
  80302. /**
  80303. * Connects two bodies at given offset points.
  80304. * @class PointToPointConstraint
  80305. * @extends Constraint
  80306. * @constructor
  80307. * @param {Body} bodyA
  80308. * @param {Vec3} pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.
  80309. * @param {Body} bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point.
  80310. * @param {Vec3} pivotB See pivotA.
  80311. * @param {Number} maxForce The maximum force that should be applied to constrain the bodies.
  80312. *
  80313. * @example
  80314. * var bodyA = new Body({ mass: 1 });
  80315. * var bodyB = new Body({ mass: 1 });
  80316. * bodyA.position.set(-1, 0, 0);
  80317. * bodyB.position.set(1, 0, 0);
  80318. * bodyA.addShape(shapeA);
  80319. * bodyB.addShape(shapeB);
  80320. * world.addBody(bodyA);
  80321. * world.addBody(bodyB);
  80322. * var localPivotA = new Vec3(1, 0, 0);
  80323. * var localPivotB = new Vec3(-1, 0, 0);
  80324. * var constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB);
  80325. * world.addConstraint(constraint);
  80326. */
  80327. function PointToPointConstraint(bodyA,pivotA,bodyB,pivotB,maxForce){
  80328. Constraint.call(this,bodyA,bodyB);
  80329. maxForce = typeof(maxForce) !== 'undefined' ? maxForce : 1e6;
  80330. /**
  80331. * Pivot, defined locally in bodyA.
  80332. * @property {Vec3} pivotA
  80333. */
  80334. this.pivotA = pivotA ? pivotA.clone() : new Vec3();
  80335. /**
  80336. * Pivot, defined locally in bodyB.
  80337. * @property {Vec3} pivotB
  80338. */
  80339. this.pivotB = pivotB ? pivotB.clone() : new Vec3();
  80340. /**
  80341. * @property {ContactEquation} equationX
  80342. */
  80343. var x = this.equationX = new ContactEquation(bodyA,bodyB);
  80344. /**
  80345. * @property {ContactEquation} equationY
  80346. */
  80347. var y = this.equationY = new ContactEquation(bodyA,bodyB);
  80348. /**
  80349. * @property {ContactEquation} equationZ
  80350. */
  80351. var z = this.equationZ = new ContactEquation(bodyA,bodyB);
  80352. // Equations to be fed to the solver
  80353. this.equations.push(x, y, z);
  80354. // Make the equations bidirectional
  80355. x.minForce = y.minForce = z.minForce = -maxForce;
  80356. x.maxForce = y.maxForce = z.maxForce = maxForce;
  80357. x.ni.set(1, 0, 0);
  80358. y.ni.set(0, 1, 0);
  80359. z.ni.set(0, 0, 1);
  80360. }
  80361. PointToPointConstraint.prototype = new Constraint();
  80362. PointToPointConstraint.prototype.update = function(){
  80363. var bodyA = this.bodyA;
  80364. var bodyB = this.bodyB;
  80365. var x = this.equationX;
  80366. var y = this.equationY;
  80367. var z = this.equationZ;
  80368. // Rotate the pivots to world space
  80369. bodyA.quaternion.vmult(this.pivotA,x.ri);
  80370. bodyB.quaternion.vmult(this.pivotB,x.rj);
  80371. y.ri.copy(x.ri);
  80372. y.rj.copy(x.rj);
  80373. z.ri.copy(x.ri);
  80374. z.rj.copy(x.rj);
  80375. };
  80376. },{"../equations/ContactEquation":19,"../math/Vec3":30,"./Constraint":13}],18:[function(_dereq_,module,exports){
  80377. module.exports = ConeEquation;
  80378. var Vec3 = _dereq_('../math/Vec3');
  80379. var Mat3 = _dereq_('../math/Mat3');
  80380. var Equation = _dereq_('./Equation');
  80381. /**
  80382. * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other.
  80383. * @class ConeEquation
  80384. * @constructor
  80385. * @author schteppe
  80386. * @param {Body} bodyA
  80387. * @param {Body} bodyB
  80388. * @param {Vec3} [options.axisA] Local axis in A
  80389. * @param {Vec3} [options.axisB] Local axis in B
  80390. * @param {Vec3} [options.angle] The "cone angle" to keep
  80391. * @param {number} [options.maxForce=1e6]
  80392. * @extends Equation
  80393. */
  80394. function ConeEquation(bodyA, bodyB, options){
  80395. options = options || {};
  80396. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  80397. Equation.call(this,bodyA,bodyB,-maxForce, maxForce);
  80398. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  80399. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  80400. /**
  80401. * The cone angle to keep
  80402. * @property {number} angle
  80403. */
  80404. this.angle = typeof(options.angle) !== 'undefined' ? options.angle : 0;
  80405. }
  80406. ConeEquation.prototype = new Equation();
  80407. ConeEquation.prototype.constructor = ConeEquation;
  80408. var tmpVec1 = new Vec3();
  80409. var tmpVec2 = new Vec3();
  80410. ConeEquation.prototype.computeB = function(h){
  80411. var a = this.a,
  80412. b = this.b,
  80413. ni = this.axisA,
  80414. nj = this.axisB,
  80415. nixnj = tmpVec1,
  80416. njxni = tmpVec2,
  80417. GA = this.jacobianElementA,
  80418. GB = this.jacobianElementB;
  80419. // Caluclate cross products
  80420. ni.cross(nj, nixnj);
  80421. nj.cross(ni, njxni);
  80422. // The angle between two vector is:
  80423. // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b
  80424. // g = a * b
  80425. // gdot = (b x a) * wi + (a x b) * wj
  80426. // G = [0 bxa 0 axb]
  80427. // W = [vi wi vj wj]
  80428. GA.rotational.copy(njxni);
  80429. GB.rotational.copy(nixnj);
  80430. var g = Math.cos(this.angle) - ni.dot(nj),
  80431. GW = this.computeGW(),
  80432. GiMf = this.computeGiMf();
  80433. var B = - g * a - GW * b - h * GiMf;
  80434. return B;
  80435. };
  80436. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],19:[function(_dereq_,module,exports){
  80437. module.exports = ContactEquation;
  80438. var Equation = _dereq_('./Equation');
  80439. var Vec3 = _dereq_('../math/Vec3');
  80440. var Mat3 = _dereq_('../math/Mat3');
  80441. /**
  80442. * Contact/non-penetration constraint equation
  80443. * @class ContactEquation
  80444. * @constructor
  80445. * @author schteppe
  80446. * @param {Body} bodyA
  80447. * @param {Body} bodyB
  80448. * @extends Equation
  80449. */
  80450. function ContactEquation(bodyA, bodyB, maxForce){
  80451. maxForce = typeof(maxForce) !== 'undefined' ? maxForce : 1e6;
  80452. Equation.call(this, bodyA, bodyB, 0, maxForce);
  80453. /**
  80454. * @property restitution
  80455. * @type {Number}
  80456. */
  80457. this.restitution = 0.0; // "bounciness": u1 = -e*u0
  80458. /**
  80459. * World-oriented vector that goes from the center of bi to the contact point.
  80460. * @property {Vec3} ri
  80461. */
  80462. this.ri = new Vec3();
  80463. /**
  80464. * World-oriented vector that starts in body j position and goes to the contact point.
  80465. * @property {Vec3} rj
  80466. */
  80467. this.rj = new Vec3();
  80468. /**
  80469. * Contact normal, pointing out of body i.
  80470. * @property {Vec3} ni
  80471. */
  80472. this.ni = new Vec3();
  80473. }
  80474. ContactEquation.prototype = new Equation();
  80475. ContactEquation.prototype.constructor = ContactEquation;
  80476. var ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors
  80477. var ContactEquation_computeB_temp2 = new Vec3();
  80478. var ContactEquation_computeB_temp3 = new Vec3();
  80479. ContactEquation.prototype.computeB = function(h){
  80480. var a = this.a,
  80481. b = this.b,
  80482. bi = this.bi,
  80483. bj = this.bj,
  80484. ri = this.ri,
  80485. rj = this.rj,
  80486. rixn = ContactEquation_computeB_temp1,
  80487. rjxn = ContactEquation_computeB_temp2,
  80488. vi = bi.velocity,
  80489. wi = bi.angularVelocity,
  80490. fi = bi.force,
  80491. taui = bi.torque,
  80492. vj = bj.velocity,
  80493. wj = bj.angularVelocity,
  80494. fj = bj.force,
  80495. tauj = bj.torque,
  80496. penetrationVec = ContactEquation_computeB_temp3,
  80497. GA = this.jacobianElementA,
  80498. GB = this.jacobianElementB,
  80499. n = this.ni;
  80500. // Caluclate cross products
  80501. ri.cross(n,rixn);
  80502. rj.cross(n,rjxn);
  80503. // g = xj+rj -(xi+ri)
  80504. // G = [ -ni -rixn ni rjxn ]
  80505. n.negate(GA.spatial);
  80506. rixn.negate(GA.rotational);
  80507. GB.spatial.copy(n);
  80508. GB.rotational.copy(rjxn);
  80509. // Calculate the penetration vector
  80510. penetrationVec.copy(bj.position);
  80511. penetrationVec.vadd(rj,penetrationVec);
  80512. penetrationVec.vsub(bi.position,penetrationVec);
  80513. penetrationVec.vsub(ri,penetrationVec);
  80514. var g = n.dot(penetrationVec);
  80515. // Compute iteration
  80516. var ePlusOne = this.restitution + 1;
  80517. var GW = ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn);
  80518. var GiMf = this.computeGiMf();
  80519. var B = - g * a - GW * b - h*GiMf;
  80520. return B;
  80521. };
  80522. var ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3();
  80523. var ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3();
  80524. var ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3();
  80525. var ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3();
  80526. var ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3();
  80527. /**
  80528. * Get the current relative velocity in the contact point.
  80529. * @method getImpactVelocityAlongNormal
  80530. * @return {number}
  80531. */
  80532. ContactEquation.prototype.getImpactVelocityAlongNormal = function(){
  80533. var vi = ContactEquation_getImpactVelocityAlongNormal_vi;
  80534. var vj = ContactEquation_getImpactVelocityAlongNormal_vj;
  80535. var xi = ContactEquation_getImpactVelocityAlongNormal_xi;
  80536. var xj = ContactEquation_getImpactVelocityAlongNormal_xj;
  80537. var relVel = ContactEquation_getImpactVelocityAlongNormal_relVel;
  80538. this.bi.position.vadd(this.ri, xi);
  80539. this.bj.position.vadd(this.rj, xj);
  80540. this.bi.getVelocityAtWorldPoint(xi, vi);
  80541. this.bj.getVelocityAtWorldPoint(xj, vj);
  80542. vi.vsub(vj, relVel);
  80543. return this.ni.dot(relVel);
  80544. };
  80545. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],20:[function(_dereq_,module,exports){
  80546. module.exports = Equation;
  80547. var JacobianElement = _dereq_('../math/JacobianElement'),
  80548. Vec3 = _dereq_('../math/Vec3');
  80549. /**
  80550. * Equation base class
  80551. * @class Equation
  80552. * @constructor
  80553. * @author schteppe
  80554. * @param {Body} bi
  80555. * @param {Body} bj
  80556. * @param {Number} minForce Minimum (read: negative max) force to be applied by the constraint.
  80557. * @param {Number} maxForce Maximum (read: positive max) force to be applied by the constraint.
  80558. */
  80559. function Equation(bi,bj,minForce,maxForce){
  80560. this.id = Equation.id++;
  80561. /**
  80562. * @property {number} minForce
  80563. */
  80564. this.minForce = typeof(minForce)==="undefined" ? -1e6 : minForce;
  80565. /**
  80566. * @property {number} maxForce
  80567. */
  80568. this.maxForce = typeof(maxForce)==="undefined" ? 1e6 : maxForce;
  80569. /**
  80570. * @property bi
  80571. * @type {Body}
  80572. */
  80573. this.bi = bi;
  80574. /**
  80575. * @property bj
  80576. * @type {Body}
  80577. */
  80578. this.bj = bj;
  80579. /**
  80580. * SPOOK parameter
  80581. * @property {number} a
  80582. */
  80583. this.a = 0.0;
  80584. /**
  80585. * SPOOK parameter
  80586. * @property {number} b
  80587. */
  80588. this.b = 0.0;
  80589. /**
  80590. * SPOOK parameter
  80591. * @property {number} eps
  80592. */
  80593. this.eps = 0.0;
  80594. /**
  80595. * @property {JacobianElement} jacobianElementA
  80596. */
  80597. this.jacobianElementA = new JacobianElement();
  80598. /**
  80599. * @property {JacobianElement} jacobianElementB
  80600. */
  80601. this.jacobianElementB = new JacobianElement();
  80602. /**
  80603. * @property {boolean} enabled
  80604. * @default true
  80605. */
  80606. this.enabled = true;
  80607. // Set typical spook params
  80608. this.setSpookParams(1e7,4,1/60);
  80609. }
  80610. Equation.prototype.constructor = Equation;
  80611. Equation.id = 0;
  80612. /**
  80613. * Recalculates a,b,eps.
  80614. * @method setSpookParams
  80615. */
  80616. Equation.prototype.setSpookParams = function(stiffness,relaxation,timeStep){
  80617. var d = relaxation,
  80618. k = stiffness,
  80619. h = timeStep;
  80620. this.a = 4.0 / (h * (1 + 4 * d));
  80621. this.b = (4.0 * d) / (1 + 4 * d);
  80622. this.eps = 4.0 / (h * h * k * (1 + 4 * d));
  80623. };
  80624. /**
  80625. * Computes the RHS of the SPOOK equation
  80626. * @method computeB
  80627. * @return {Number}
  80628. */
  80629. Equation.prototype.computeB = function(a,b,h){
  80630. var GW = this.computeGW(),
  80631. Gq = this.computeGq(),
  80632. GiMf = this.computeGiMf();
  80633. return - Gq * a - GW * b - GiMf*h;
  80634. };
  80635. /**
  80636. * Computes G*q, where q are the generalized body coordinates
  80637. * @method computeGq
  80638. * @return {Number}
  80639. */
  80640. Equation.prototype.computeGq = function(){
  80641. var GA = this.jacobianElementA,
  80642. GB = this.jacobianElementB,
  80643. bi = this.bi,
  80644. bj = this.bj,
  80645. xi = bi.position,
  80646. xj = bj.position;
  80647. return GA.spatial.dot(xi) + GB.spatial.dot(xj);
  80648. };
  80649. var zero = new Vec3();
  80650. /**
  80651. * Computes G*W, where W are the body velocities
  80652. * @method computeGW
  80653. * @return {Number}
  80654. */
  80655. Equation.prototype.computeGW = function(){
  80656. var GA = this.jacobianElementA,
  80657. GB = this.jacobianElementB,
  80658. bi = this.bi,
  80659. bj = this.bj,
  80660. vi = bi.velocity,
  80661. vj = bj.velocity,
  80662. wi = bi.angularVelocity || zero,
  80663. wj = bj.angularVelocity || zero;
  80664. return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj);
  80665. };
  80666. /**
  80667. * Computes G*Wlambda, where W are the body velocities
  80668. * @method computeGWlambda
  80669. * @return {Number}
  80670. */
  80671. Equation.prototype.computeGWlambda = function(){
  80672. var GA = this.jacobianElementA,
  80673. GB = this.jacobianElementB,
  80674. bi = this.bi,
  80675. bj = this.bj,
  80676. vi = bi.vlambda,
  80677. vj = bj.vlambda,
  80678. wi = bi.wlambda || zero,
  80679. wj = bj.wlambda || zero;
  80680. return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj);
  80681. };
  80682. /**
  80683. * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.
  80684. * @method computeGiMf
  80685. * @return {Number}
  80686. */
  80687. var iMfi = new Vec3(),
  80688. iMfj = new Vec3(),
  80689. invIi_vmult_taui = new Vec3(),
  80690. invIj_vmult_tauj = new Vec3();
  80691. Equation.prototype.computeGiMf = function(){
  80692. var GA = this.jacobianElementA,
  80693. GB = this.jacobianElementB,
  80694. bi = this.bi,
  80695. bj = this.bj,
  80696. fi = bi.force,
  80697. ti = bi.torque,
  80698. fj = bj.force,
  80699. tj = bj.torque,
  80700. invMassi = bi.invMassSolve,
  80701. invMassj = bj.invMassSolve;
  80702. if(bi.invInertiaWorldSolve){ bi.invInertiaWorldSolve.vmult(ti,invIi_vmult_taui); }
  80703. else { invIi_vmult_taui.set(0,0,0); }
  80704. if(bj.invInertiaWorldSolve){ bj.invInertiaWorldSolve.vmult(tj,invIj_vmult_tauj); }
  80705. else { invIj_vmult_tauj.set(0,0,0); }
  80706. fi.mult(invMassi,iMfi);
  80707. fj.mult(invMassj,iMfj);
  80708. return GA.multiplyVectors(iMfi,invIi_vmult_taui) + GB.multiplyVectors(iMfj,invIj_vmult_tauj);
  80709. };
  80710. /**
  80711. * Computes G*inv(M)*G'
  80712. * @method computeGiMGt
  80713. * @return {Number}
  80714. */
  80715. var tmp = new Vec3();
  80716. Equation.prototype.computeGiMGt = function(){
  80717. var GA = this.jacobianElementA,
  80718. GB = this.jacobianElementB,
  80719. bi = this.bi,
  80720. bj = this.bj,
  80721. invMassi = bi.invMassSolve,
  80722. invMassj = bj.invMassSolve,
  80723. invIi = bi.invInertiaWorldSolve,
  80724. invIj = bj.invInertiaWorldSolve,
  80725. result = invMassi + invMassj;
  80726. if(invIi){
  80727. invIi.vmult(GA.rotational,tmp);
  80728. result += tmp.dot(GA.rotational);
  80729. }
  80730. if(invIj){
  80731. invIj.vmult(GB.rotational,tmp);
  80732. result += tmp.dot(GB.rotational);
  80733. }
  80734. return result;
  80735. };
  80736. var addToWlambda_temp = new Vec3(),
  80737. addToWlambda_Gi = new Vec3(),
  80738. addToWlambda_Gj = new Vec3(),
  80739. addToWlambda_ri = new Vec3(),
  80740. addToWlambda_rj = new Vec3(),
  80741. addToWlambda_Mdiag = new Vec3();
  80742. /**
  80743. * Add constraint velocity to the bodies.
  80744. * @method addToWlambda
  80745. * @param {Number} deltalambda
  80746. */
  80747. Equation.prototype.addToWlambda = function(deltalambda){
  80748. var GA = this.jacobianElementA,
  80749. GB = this.jacobianElementB,
  80750. bi = this.bi,
  80751. bj = this.bj,
  80752. temp = addToWlambda_temp;
  80753. // Add to linear velocity
  80754. // v_lambda += inv(M) * delta_lamba * G
  80755. GA.spatial.mult(bi.invMassSolve * deltalambda,temp);
  80756. bi.vlambda.vadd(temp, bi.vlambda);
  80757. GB.spatial.mult(bj.invMassSolve * deltalambda,temp);
  80758. bj.vlambda.vadd(temp, bj.vlambda);
  80759. // Add to angular velocity
  80760. if(bi.invInertiaWorldSolve){
  80761. bi.invInertiaWorldSolve.vmult(GA.rotational,temp);
  80762. temp.mult(deltalambda,temp);
  80763. bi.wlambda.vadd(temp,bi.wlambda);
  80764. }
  80765. if(bj.invInertiaWorldSolve){
  80766. bj.invInertiaWorldSolve.vmult(GB.rotational,temp);
  80767. temp.mult(deltalambda,temp);
  80768. bj.wlambda.vadd(temp,bj.wlambda);
  80769. }
  80770. };
  80771. /**
  80772. * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps
  80773. * @method computeInvC
  80774. * @param {Number} eps
  80775. * @return {Number}
  80776. */
  80777. Equation.prototype.computeC = function(){
  80778. return this.computeGiMGt() + this.eps;
  80779. };
  80780. },{"../math/JacobianElement":26,"../math/Vec3":30}],21:[function(_dereq_,module,exports){
  80781. module.exports = FrictionEquation;
  80782. var Equation = _dereq_('./Equation');
  80783. var Vec3 = _dereq_('../math/Vec3');
  80784. var Mat3 = _dereq_('../math/Mat3');
  80785. /**
  80786. * Constrains the slipping in a contact along a tangent
  80787. * @class FrictionEquation
  80788. * @constructor
  80789. * @author schteppe
  80790. * @param {Body} bodyA
  80791. * @param {Body} bodyB
  80792. * @param {Number} slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g
  80793. * @extends Equation
  80794. */
  80795. function FrictionEquation(bodyA, bodyB, slipForce){
  80796. Equation.call(this,bodyA, bodyB, -slipForce, slipForce);
  80797. this.ri = new Vec3();
  80798. this.rj = new Vec3();
  80799. this.t = new Vec3(); // tangent
  80800. }
  80801. FrictionEquation.prototype = new Equation();
  80802. FrictionEquation.prototype.constructor = FrictionEquation;
  80803. var FrictionEquation_computeB_temp1 = new Vec3();
  80804. var FrictionEquation_computeB_temp2 = new Vec3();
  80805. FrictionEquation.prototype.computeB = function(h){
  80806. var a = this.a,
  80807. b = this.b,
  80808. bi = this.bi,
  80809. bj = this.bj,
  80810. ri = this.ri,
  80811. rj = this.rj,
  80812. rixt = FrictionEquation_computeB_temp1,
  80813. rjxt = FrictionEquation_computeB_temp2,
  80814. t = this.t;
  80815. // Caluclate cross products
  80816. ri.cross(t,rixt);
  80817. rj.cross(t,rjxt);
  80818. // G = [-t -rixt t rjxt]
  80819. // And remember, this is a pure velocity constraint, g is always zero!
  80820. var GA = this.jacobianElementA,
  80821. GB = this.jacobianElementB;
  80822. t.negate(GA.spatial);
  80823. rixt.negate(GA.rotational);
  80824. GB.spatial.copy(t);
  80825. GB.rotational.copy(rjxt);
  80826. var GW = this.computeGW();
  80827. var GiMf = this.computeGiMf();
  80828. var B = - GW * b - h * GiMf;
  80829. return B;
  80830. };
  80831. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],22:[function(_dereq_,module,exports){
  80832. module.exports = RotationalEquation;
  80833. var Vec3 = _dereq_('../math/Vec3');
  80834. var Mat3 = _dereq_('../math/Mat3');
  80835. var Equation = _dereq_('./Equation');
  80836. /**
  80837. * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space.
  80838. * @class RotationalEquation
  80839. * @constructor
  80840. * @author schteppe
  80841. * @param {Body} bodyA
  80842. * @param {Body} bodyB
  80843. * @param {Vec3} [options.axisA]
  80844. * @param {Vec3} [options.axisB]
  80845. * @param {number} [options.maxForce]
  80846. * @extends Equation
  80847. */
  80848. function RotationalEquation(bodyA, bodyB, options){
  80849. options = options || {};
  80850. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  80851. Equation.call(this,bodyA,bodyB,-maxForce, maxForce);
  80852. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  80853. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  80854. this.maxAngle = Math.PI / 2;
  80855. }
  80856. RotationalEquation.prototype = new Equation();
  80857. RotationalEquation.prototype.constructor = RotationalEquation;
  80858. var tmpVec1 = new Vec3();
  80859. var tmpVec2 = new Vec3();
  80860. RotationalEquation.prototype.computeB = function(h){
  80861. var a = this.a,
  80862. b = this.b,
  80863. ni = this.axisA,
  80864. nj = this.axisB,
  80865. nixnj = tmpVec1,
  80866. njxni = tmpVec2,
  80867. GA = this.jacobianElementA,
  80868. GB = this.jacobianElementB;
  80869. // Caluclate cross products
  80870. ni.cross(nj, nixnj);
  80871. nj.cross(ni, njxni);
  80872. // g = ni * nj
  80873. // gdot = (nj x ni) * wi + (ni x nj) * wj
  80874. // G = [0 njxni 0 nixnj]
  80875. // W = [vi wi vj wj]
  80876. GA.rotational.copy(njxni);
  80877. GB.rotational.copy(nixnj);
  80878. var g = Math.cos(this.maxAngle) - ni.dot(nj),
  80879. GW = this.computeGW(),
  80880. GiMf = this.computeGiMf();
  80881. var B = - g * a - GW * b - h * GiMf;
  80882. return B;
  80883. };
  80884. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],23:[function(_dereq_,module,exports){
  80885. module.exports = RotationalMotorEquation;
  80886. var Vec3 = _dereq_('../math/Vec3');
  80887. var Mat3 = _dereq_('../math/Mat3');
  80888. var Equation = _dereq_('./Equation');
  80889. /**
  80890. * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value.
  80891. * @class RotationalMotorEquation
  80892. * @constructor
  80893. * @author schteppe
  80894. * @param {Body} bodyA
  80895. * @param {Body} bodyB
  80896. * @param {Number} maxForce
  80897. * @extends Equation
  80898. */
  80899. function RotationalMotorEquation(bodyA, bodyB, maxForce){
  80900. maxForce = typeof(maxForce)!=='undefined' ? maxForce : 1e6;
  80901. Equation.call(this,bodyA,bodyB,-maxForce,maxForce);
  80902. /**
  80903. * World oriented rotational axis
  80904. * @property {Vec3} axisA
  80905. */
  80906. this.axisA = new Vec3();
  80907. /**
  80908. * World oriented rotational axis
  80909. * @property {Vec3} axisB
  80910. */
  80911. this.axisB = new Vec3(); // World oriented rotational axis
  80912. /**
  80913. * Motor velocity
  80914. * @property {Number} targetVelocity
  80915. */
  80916. this.targetVelocity = 0;
  80917. }
  80918. RotationalMotorEquation.prototype = new Equation();
  80919. RotationalMotorEquation.prototype.constructor = RotationalMotorEquation;
  80920. RotationalMotorEquation.prototype.computeB = function(h){
  80921. var a = this.a,
  80922. b = this.b,
  80923. bi = this.bi,
  80924. bj = this.bj,
  80925. axisA = this.axisA,
  80926. axisB = this.axisB,
  80927. GA = this.jacobianElementA,
  80928. GB = this.jacobianElementB;
  80929. // g = 0
  80930. // gdot = axisA * wi - axisB * wj
  80931. // gdot = G * W = G * [vi wi vj wj]
  80932. // =>
  80933. // G = [0 axisA 0 -axisB]
  80934. GA.rotational.copy(axisA);
  80935. axisB.negate(GB.rotational);
  80936. var GW = this.computeGW() - this.targetVelocity,
  80937. GiMf = this.computeGiMf();
  80938. var B = - GW * b - h * GiMf;
  80939. return B;
  80940. };
  80941. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],24:[function(_dereq_,module,exports){
  80942. var Utils = _dereq_('../utils/Utils');
  80943. module.exports = ContactMaterial;
  80944. /**
  80945. * Defines what happens when two materials meet.
  80946. * @class ContactMaterial
  80947. * @constructor
  80948. * @param {Material} m1
  80949. * @param {Material} m2
  80950. * @param {object} [options]
  80951. * @param {Number} [options.friction=0.3]
  80952. * @param {Number} [options.restitution=0.3]
  80953. * @param {number} [options.contactEquationStiffness=1e7]
  80954. * @param {number} [options.contactEquationRelaxation=3]
  80955. * @param {number} [options.frictionEquationStiffness=1e7]
  80956. * @param {Number} [options.frictionEquationRelaxation=3]
  80957. */
  80958. function ContactMaterial(m1, m2, options){
  80959. options = Utils.defaults(options, {
  80960. friction: 0.3,
  80961. restitution: 0.3,
  80962. contactEquationStiffness: 1e7,
  80963. contactEquationRelaxation: 3,
  80964. frictionEquationStiffness: 1e7,
  80965. frictionEquationRelaxation: 3
  80966. });
  80967. /**
  80968. * Identifier of this material
  80969. * @property {Number} id
  80970. */
  80971. this.id = ContactMaterial.idCounter++;
  80972. /**
  80973. * Participating materials
  80974. * @property {Array} materials
  80975. * @todo Should be .materialA and .materialB instead
  80976. */
  80977. this.materials = [m1, m2];
  80978. /**
  80979. * Friction coefficient
  80980. * @property {Number} friction
  80981. */
  80982. this.friction = options.friction;
  80983. /**
  80984. * Restitution coefficient
  80985. * @property {Number} restitution
  80986. */
  80987. this.restitution = options.restitution;
  80988. /**
  80989. * Stiffness of the produced contact equations
  80990. * @property {Number} contactEquationStiffness
  80991. */
  80992. this.contactEquationStiffness = options.contactEquationStiffness;
  80993. /**
  80994. * Relaxation time of the produced contact equations
  80995. * @property {Number} contactEquationRelaxation
  80996. */
  80997. this.contactEquationRelaxation = options.contactEquationRelaxation;
  80998. /**
  80999. * Stiffness of the produced friction equations
  81000. * @property {Number} frictionEquationStiffness
  81001. */
  81002. this.frictionEquationStiffness = options.frictionEquationStiffness;
  81003. /**
  81004. * Relaxation time of the produced friction equations
  81005. * @property {Number} frictionEquationRelaxation
  81006. */
  81007. this.frictionEquationRelaxation = options.frictionEquationRelaxation;
  81008. }
  81009. ContactMaterial.idCounter = 0;
  81010. },{"../utils/Utils":53}],25:[function(_dereq_,module,exports){
  81011. module.exports = Material;
  81012. /**
  81013. * Defines a physics material.
  81014. * @class Material
  81015. * @constructor
  81016. * @param {object} [options]
  81017. * @author schteppe
  81018. */
  81019. function Material(options){
  81020. var name = '';
  81021. options = options || {};
  81022. // Backwards compatibility fix
  81023. if(typeof(options) === 'string'){
  81024. name = options;
  81025. options = {};
  81026. } else if(typeof(options) === 'object') {
  81027. name = '';
  81028. }
  81029. /**
  81030. * @property name
  81031. * @type {String}
  81032. */
  81033. this.name = name;
  81034. /**
  81035. * material id.
  81036. * @property id
  81037. * @type {number}
  81038. */
  81039. this.id = Material.idCounter++;
  81040. /**
  81041. * Friction for this material. If non-negative, it will be used instead of the friction given by ContactMaterials. If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used.
  81042. * @property {number} friction
  81043. */
  81044. this.friction = typeof(options.friction) !== 'undefined' ? options.friction : -1;
  81045. /**
  81046. * Restitution for this material. If non-negative, it will be used instead of the restitution given by ContactMaterials. If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used.
  81047. * @property {number} restitution
  81048. */
  81049. this.restitution = typeof(options.restitution) !== 'undefined' ? options.restitution : -1;
  81050. }
  81051. Material.idCounter = 0;
  81052. },{}],26:[function(_dereq_,module,exports){
  81053. module.exports = JacobianElement;
  81054. var Vec3 = _dereq_('./Vec3');
  81055. /**
  81056. * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom.
  81057. * @class JacobianElement
  81058. * @constructor
  81059. */
  81060. function JacobianElement(){
  81061. /**
  81062. * @property {Vec3} spatial
  81063. */
  81064. this.spatial = new Vec3();
  81065. /**
  81066. * @property {Vec3} rotational
  81067. */
  81068. this.rotational = new Vec3();
  81069. }
  81070. /**
  81071. * Multiply with other JacobianElement
  81072. * @method multiplyElement
  81073. * @param {JacobianElement} element
  81074. * @return {Number}
  81075. */
  81076. JacobianElement.prototype.multiplyElement = function(element){
  81077. return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational);
  81078. };
  81079. /**
  81080. * Multiply with two vectors
  81081. * @method multiplyVectors
  81082. * @param {Vec3} spatial
  81083. * @param {Vec3} rotational
  81084. * @return {Number}
  81085. */
  81086. JacobianElement.prototype.multiplyVectors = function(spatial,rotational){
  81087. return spatial.dot(this.spatial) + rotational.dot(this.rotational);
  81088. };
  81089. },{"./Vec3":30}],27:[function(_dereq_,module,exports){
  81090. module.exports = Mat3;
  81091. var Vec3 = _dereq_('./Vec3');
  81092. /**
  81093. * A 3x3 matrix.
  81094. * @class Mat3
  81095. * @constructor
  81096. * @param array elements Array of nine elements. Optional.
  81097. * @author schteppe / http://github.com/schteppe
  81098. */
  81099. function Mat3(elements){
  81100. /**
  81101. * A vector of length 9, containing all matrix elements
  81102. * @property {Array} elements
  81103. */
  81104. if(elements){
  81105. this.elements = elements;
  81106. } else {
  81107. this.elements = [0,0,0,0,0,0,0,0,0];
  81108. }
  81109. }
  81110. /**
  81111. * Sets the matrix to identity
  81112. * @method identity
  81113. * @todo Should perhaps be renamed to setIdentity() to be more clear.
  81114. * @todo Create another function that immediately creates an identity matrix eg. eye()
  81115. */
  81116. Mat3.prototype.identity = function(){
  81117. var e = this.elements;
  81118. e[0] = 1;
  81119. e[1] = 0;
  81120. e[2] = 0;
  81121. e[3] = 0;
  81122. e[4] = 1;
  81123. e[5] = 0;
  81124. e[6] = 0;
  81125. e[7] = 0;
  81126. e[8] = 1;
  81127. };
  81128. /**
  81129. * Set all elements to zero
  81130. * @method setZero
  81131. */
  81132. Mat3.prototype.setZero = function(){
  81133. var e = this.elements;
  81134. e[0] = 0;
  81135. e[1] = 0;
  81136. e[2] = 0;
  81137. e[3] = 0;
  81138. e[4] = 0;
  81139. e[5] = 0;
  81140. e[6] = 0;
  81141. e[7] = 0;
  81142. e[8] = 0;
  81143. };
  81144. /**
  81145. * Sets the matrix diagonal elements from a Vec3
  81146. * @method setTrace
  81147. * @param {Vec3} vec3
  81148. */
  81149. Mat3.prototype.setTrace = function(vec3){
  81150. var e = this.elements;
  81151. e[0] = vec3.x;
  81152. e[4] = vec3.y;
  81153. e[8] = vec3.z;
  81154. };
  81155. /**
  81156. * Gets the matrix diagonal elements
  81157. * @method getTrace
  81158. * @return {Vec3}
  81159. */
  81160. Mat3.prototype.getTrace = function(target){
  81161. var target = target || new Vec3();
  81162. var e = this.elements;
  81163. target.x = e[0];
  81164. target.y = e[4];
  81165. target.z = e[8];
  81166. };
  81167. /**
  81168. * Matrix-Vector multiplication
  81169. * @method vmult
  81170. * @param {Vec3} v The vector to multiply with
  81171. * @param {Vec3} target Optional, target to save the result in.
  81172. */
  81173. Mat3.prototype.vmult = function(v,target){
  81174. target = target || new Vec3();
  81175. var e = this.elements,
  81176. x = v.x,
  81177. y = v.y,
  81178. z = v.z;
  81179. target.x = e[0]*x + e[1]*y + e[2]*z;
  81180. target.y = e[3]*x + e[4]*y + e[5]*z;
  81181. target.z = e[6]*x + e[7]*y + e[8]*z;
  81182. return target;
  81183. };
  81184. /**
  81185. * Matrix-scalar multiplication
  81186. * @method smult
  81187. * @param {Number} s
  81188. */
  81189. Mat3.prototype.smult = function(s){
  81190. for(var i=0; i<this.elements.length; i++){
  81191. this.elements[i] *= s;
  81192. }
  81193. };
  81194. /**
  81195. * Matrix multiplication
  81196. * @method mmult
  81197. * @param {Mat3} m Matrix to multiply with from left side.
  81198. * @return {Mat3} The result.
  81199. */
  81200. Mat3.prototype.mmult = function(m,target){
  81201. var r = target || new Mat3();
  81202. for(var i=0; i<3; i++){
  81203. for(var j=0; j<3; j++){
  81204. var sum = 0.0;
  81205. for(var k=0; k<3; k++){
  81206. sum += m.elements[i+k*3] * this.elements[k+j*3];
  81207. }
  81208. r.elements[i+j*3] = sum;
  81209. }
  81210. }
  81211. return r;
  81212. };
  81213. /**
  81214. * Scale each column of the matrix
  81215. * @method scale
  81216. * @param {Vec3} v
  81217. * @return {Mat3} The result.
  81218. */
  81219. Mat3.prototype.scale = function(v,target){
  81220. target = target || new Mat3();
  81221. var e = this.elements,
  81222. t = target.elements;
  81223. for(var i=0; i!==3; i++){
  81224. t[3*i + 0] = v.x * e[3*i + 0];
  81225. t[3*i + 1] = v.y * e[3*i + 1];
  81226. t[3*i + 2] = v.z * e[3*i + 2];
  81227. }
  81228. return target;
  81229. };
  81230. /**
  81231. * Solve Ax=b
  81232. * @method solve
  81233. * @param {Vec3} b The right hand side
  81234. * @param {Vec3} target Optional. Target vector to save in.
  81235. * @return {Vec3} The solution x
  81236. * @todo should reuse arrays
  81237. */
  81238. Mat3.prototype.solve = function(b,target){
  81239. target = target || new Vec3();
  81240. // Construct equations
  81241. var nr = 3; // num rows
  81242. var nc = 4; // num cols
  81243. var eqns = [];
  81244. for(var i=0; i<nr*nc; i++){
  81245. eqns.push(0);
  81246. }
  81247. var i,j;
  81248. for(i=0; i<3; i++){
  81249. for(j=0; j<3; j++){
  81250. eqns[i+nc*j] = this.elements[i+3*j];
  81251. }
  81252. }
  81253. eqns[3+4*0] = b.x;
  81254. eqns[3+4*1] = b.y;
  81255. eqns[3+4*2] = b.z;
  81256. // Compute right upper triangular version of the matrix - Gauss elimination
  81257. var n = 3, k = n, np;
  81258. var kp = 4; // num rows
  81259. var p, els;
  81260. do {
  81261. i = k - n;
  81262. if (eqns[i+nc*i] === 0) {
  81263. // the pivot is null, swap lines
  81264. for (j = i + 1; j < k; j++) {
  81265. if (eqns[i+nc*j] !== 0) {
  81266. np = kp;
  81267. do { // do ligne( i ) = ligne( i ) + ligne( k )
  81268. p = kp - np;
  81269. eqns[p+nc*i] += eqns[p+nc*j];
  81270. } while (--np);
  81271. break;
  81272. }
  81273. }
  81274. }
  81275. if (eqns[i+nc*i] !== 0) {
  81276. for (j = i + 1; j < k; j++) {
  81277. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  81278. np = kp;
  81279. do { // do ligne( k ) = ligne( k ) - multiplier * ligne( i )
  81280. p = kp - np;
  81281. eqns[p+nc*j] = p <= i ? 0 : eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  81282. } while (--np);
  81283. }
  81284. }
  81285. } while (--n);
  81286. // Get the solution
  81287. target.z = eqns[2*nc+3] / eqns[2*nc+2];
  81288. target.y = (eqns[1*nc+3] - eqns[1*nc+2]*target.z) / eqns[1*nc+1];
  81289. target.x = (eqns[0*nc+3] - eqns[0*nc+2]*target.z - eqns[0*nc+1]*target.y) / eqns[0*nc+0];
  81290. if(isNaN(target.x) || isNaN(target.y) || isNaN(target.z) || target.x===Infinity || target.y===Infinity || target.z===Infinity){
  81291. throw "Could not solve equation! Got x=["+target.toString()+"], b=["+b.toString()+"], A=["+this.toString()+"]";
  81292. }
  81293. return target;
  81294. };
  81295. /**
  81296. * Get an element in the matrix by index. Index starts at 0, not 1!!!
  81297. * @method e
  81298. * @param {Number} row
  81299. * @param {Number} column
  81300. * @param {Number} value Optional. If provided, the matrix element will be set to this value.
  81301. * @return {Number}
  81302. */
  81303. Mat3.prototype.e = function( row , column ,value){
  81304. if(value===undefined){
  81305. return this.elements[column+3*row];
  81306. } else {
  81307. // Set value
  81308. this.elements[column+3*row] = value;
  81309. }
  81310. };
  81311. /**
  81312. * Copy another matrix into this matrix object.
  81313. * @method copy
  81314. * @param {Mat3} source
  81315. * @return {Mat3} this
  81316. */
  81317. Mat3.prototype.copy = function(source){
  81318. for(var i=0; i < source.elements.length; i++){
  81319. this.elements[i] = source.elements[i];
  81320. }
  81321. return this;
  81322. };
  81323. /**
  81324. * Returns a string representation of the matrix.
  81325. * @method toString
  81326. * @return string
  81327. */
  81328. Mat3.prototype.toString = function(){
  81329. var r = "";
  81330. var sep = ",";
  81331. for(var i=0; i<9; i++){
  81332. r += this.elements[i] + sep;
  81333. }
  81334. return r;
  81335. };
  81336. /**
  81337. * reverse the matrix
  81338. * @method reverse
  81339. * @param {Mat3} target Optional. Target matrix to save in.
  81340. * @return {Mat3} The solution x
  81341. */
  81342. Mat3.prototype.reverse = function(target){
  81343. target = target || new Mat3();
  81344. // Construct equations
  81345. var nr = 3; // num rows
  81346. var nc = 6; // num cols
  81347. var eqns = [];
  81348. for(var i=0; i<nr*nc; i++){
  81349. eqns.push(0);
  81350. }
  81351. var i,j;
  81352. for(i=0; i<3; i++){
  81353. for(j=0; j<3; j++){
  81354. eqns[i+nc*j] = this.elements[i+3*j];
  81355. }
  81356. }
  81357. eqns[3+6*0] = 1;
  81358. eqns[3+6*1] = 0;
  81359. eqns[3+6*2] = 0;
  81360. eqns[4+6*0] = 0;
  81361. eqns[4+6*1] = 1;
  81362. eqns[4+6*2] = 0;
  81363. eqns[5+6*0] = 0;
  81364. eqns[5+6*1] = 0;
  81365. eqns[5+6*2] = 1;
  81366. // Compute right upper triangular version of the matrix - Gauss elimination
  81367. var n = 3, k = n, np;
  81368. var kp = nc; // num rows
  81369. var p;
  81370. do {
  81371. i = k - n;
  81372. if (eqns[i+nc*i] === 0) {
  81373. // the pivot is null, swap lines
  81374. for (j = i + 1; j < k; j++) {
  81375. if (eqns[i+nc*j] !== 0) {
  81376. np = kp;
  81377. do { // do line( i ) = line( i ) + line( k )
  81378. p = kp - np;
  81379. eqns[p+nc*i] += eqns[p+nc*j];
  81380. } while (--np);
  81381. break;
  81382. }
  81383. }
  81384. }
  81385. if (eqns[i+nc*i] !== 0) {
  81386. for (j = i + 1; j < k; j++) {
  81387. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  81388. np = kp;
  81389. do { // do line( k ) = line( k ) - multiplier * line( i )
  81390. p = kp - np;
  81391. eqns[p+nc*j] = p <= i ? 0 : eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  81392. } while (--np);
  81393. }
  81394. }
  81395. } while (--n);
  81396. // eliminate the upper left triangle of the matrix
  81397. i = 2;
  81398. do {
  81399. j = i-1;
  81400. do {
  81401. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  81402. np = nc;
  81403. do {
  81404. p = nc - np;
  81405. eqns[p+nc*j] = eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  81406. } while (--np);
  81407. } while (j--);
  81408. } while (--i);
  81409. // operations on the diagonal
  81410. i = 2;
  81411. do {
  81412. var multiplier = 1 / eqns[i+nc*i];
  81413. np = nc;
  81414. do {
  81415. p = nc - np;
  81416. eqns[p+nc*i] = eqns[p+nc*i] * multiplier ;
  81417. } while (--np);
  81418. } while (i--);
  81419. i = 2;
  81420. do {
  81421. j = 2;
  81422. do {
  81423. p = eqns[nr+j+nc*i];
  81424. if( isNaN( p ) || p ===Infinity ){
  81425. throw "Could not reverse! A=["+this.toString()+"]";
  81426. }
  81427. target.e( i , j , p );
  81428. } while (j--);
  81429. } while (i--);
  81430. return target;
  81431. };
  81432. /**
  81433. * Set the matrix from a quaterion
  81434. * @method setRotationFromQuaternion
  81435. * @param {Quaternion} q
  81436. */
  81437. Mat3.prototype.setRotationFromQuaternion = function( q ) {
  81438. var x = q.x, y = q.y, z = q.z, w = q.w,
  81439. x2 = x + x, y2 = y + y, z2 = z + z,
  81440. xx = x * x2, xy = x * y2, xz = x * z2,
  81441. yy = y * y2, yz = y * z2, zz = z * z2,
  81442. wx = w * x2, wy = w * y2, wz = w * z2,
  81443. e = this.elements;
  81444. e[3*0 + 0] = 1 - ( yy + zz );
  81445. e[3*0 + 1] = xy - wz;
  81446. e[3*0 + 2] = xz + wy;
  81447. e[3*1 + 0] = xy + wz;
  81448. e[3*1 + 1] = 1 - ( xx + zz );
  81449. e[3*1 + 2] = yz - wx;
  81450. e[3*2 + 0] = xz - wy;
  81451. e[3*2 + 1] = yz + wx;
  81452. e[3*2 + 2] = 1 - ( xx + yy );
  81453. return this;
  81454. };
  81455. /**
  81456. * Transpose the matrix
  81457. * @method transpose
  81458. * @param {Mat3} target Where to store the result.
  81459. * @return {Mat3} The target Mat3, or a new Mat3 if target was omitted.
  81460. */
  81461. Mat3.prototype.transpose = function( target ) {
  81462. target = target || new Mat3();
  81463. var Mt = target.elements,
  81464. M = this.elements;
  81465. for(var i=0; i!==3; i++){
  81466. for(var j=0; j!==3; j++){
  81467. Mt[3*i + j] = M[3*j + i];
  81468. }
  81469. }
  81470. return target;
  81471. };
  81472. },{"./Vec3":30}],28:[function(_dereq_,module,exports){
  81473. module.exports = Quaternion;
  81474. var Vec3 = _dereq_('./Vec3');
  81475. /**
  81476. * A Quaternion describes a rotation in 3D space. The Quaternion is mathematically defined as Q = x*i + y*j + z*k + w, where (i,j,k) are imaginary basis vectors. (x,y,z) can be seen as a vector related to the axis of rotation, while the real multiplier, w, is related to the amount of rotation.
  81477. * @class Quaternion
  81478. * @constructor
  81479. * @param {Number} x Multiplier of the imaginary basis vector i.
  81480. * @param {Number} y Multiplier of the imaginary basis vector j.
  81481. * @param {Number} z Multiplier of the imaginary basis vector k.
  81482. * @param {Number} w Multiplier of the real part.
  81483. * @see http://en.wikipedia.org/wiki/Quaternion
  81484. */
  81485. function Quaternion(x,y,z,w){
  81486. /**
  81487. * @property {Number} x
  81488. */
  81489. this.x = x!==undefined ? x : 0;
  81490. /**
  81491. * @property {Number} y
  81492. */
  81493. this.y = y!==undefined ? y : 0;
  81494. /**
  81495. * @property {Number} z
  81496. */
  81497. this.z = z!==undefined ? z : 0;
  81498. /**
  81499. * The multiplier of the real quaternion basis vector.
  81500. * @property {Number} w
  81501. */
  81502. this.w = w!==undefined ? w : 1;
  81503. }
  81504. /**
  81505. * Set the value of the quaternion.
  81506. * @method set
  81507. * @param {Number} x
  81508. * @param {Number} y
  81509. * @param {Number} z
  81510. * @param {Number} w
  81511. */
  81512. Quaternion.prototype.set = function(x,y,z,w){
  81513. this.x = x;
  81514. this.y = y;
  81515. this.z = z;
  81516. this.w = w;
  81517. };
  81518. /**
  81519. * Convert to a readable format
  81520. * @method toString
  81521. * @return string
  81522. */
  81523. Quaternion.prototype.toString = function(){
  81524. return this.x+","+this.y+","+this.z+","+this.w;
  81525. };
  81526. /**
  81527. * Convert to an Array
  81528. * @method toArray
  81529. * @return Array
  81530. */
  81531. Quaternion.prototype.toArray = function(){
  81532. return [this.x, this.y, this.z, this.w];
  81533. };
  81534. /**
  81535. * Set the quaternion components given an axis and an angle.
  81536. * @method setFromAxisAngle
  81537. * @param {Vec3} axis
  81538. * @param {Number} angle in radians
  81539. */
  81540. Quaternion.prototype.setFromAxisAngle = function(axis,angle){
  81541. var s = Math.sin(angle*0.5);
  81542. this.x = axis.x * s;
  81543. this.y = axis.y * s;
  81544. this.z = axis.z * s;
  81545. this.w = Math.cos(angle*0.5);
  81546. };
  81547. /**
  81548. * Converts the quaternion to axis/angle representation.
  81549. * @method toAxisAngle
  81550. * @param {Vec3} targetAxis Optional. A vector object to reuse for storing the axis.
  81551. * @return Array An array, first elemnt is the axis and the second is the angle in radians.
  81552. */
  81553. Quaternion.prototype.toAxisAngle = function(targetAxis){
  81554. targetAxis = targetAxis || new Vec3();
  81555. this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised
  81556. var angle = 2 * Math.acos(this.w);
  81557. var s = Math.sqrt(1-this.w*this.w); // assuming quaternion normalised then w is less than 1, so term always positive.
  81558. if (s < 0.001) { // test to avoid divide by zero, s is always positive due to sqrt
  81559. // if s close to zero then direction of axis not important
  81560. targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0;
  81561. targetAxis.y = this.y;
  81562. targetAxis.z = this.z;
  81563. } else {
  81564. targetAxis.x = this.x / s; // normalise axis
  81565. targetAxis.y = this.y / s;
  81566. targetAxis.z = this.z / s;
  81567. }
  81568. return [targetAxis,angle];
  81569. };
  81570. var sfv_t1 = new Vec3(),
  81571. sfv_t2 = new Vec3();
  81572. /**
  81573. * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v.
  81574. * @method setFromVectors
  81575. * @param {Vec3} u
  81576. * @param {Vec3} v
  81577. */
  81578. Quaternion.prototype.setFromVectors = function(u,v){
  81579. if(u.isAntiparallelTo(v)){
  81580. var t1 = sfv_t1;
  81581. var t2 = sfv_t2;
  81582. u.tangents(t1,t2);
  81583. this.setFromAxisAngle(t1,Math.PI);
  81584. } else {
  81585. var a = u.cross(v);
  81586. this.x = a.x;
  81587. this.y = a.y;
  81588. this.z = a.z;
  81589. this.w = Math.sqrt(Math.pow(u.norm(),2) * Math.pow(v.norm(),2)) + u.dot(v);
  81590. this.normalize();
  81591. }
  81592. };
  81593. /**
  81594. * Quaternion multiplication
  81595. * @method mult
  81596. * @param {Quaternion} q
  81597. * @param {Quaternion} target Optional.
  81598. * @return {Quaternion}
  81599. */
  81600. var Quaternion_mult_va = new Vec3();
  81601. var Quaternion_mult_vb = new Vec3();
  81602. var Quaternion_mult_vaxvb = new Vec3();
  81603. Quaternion.prototype.mult = function(q,target){
  81604. target = target || new Quaternion();
  81605. var w = this.w,
  81606. va = Quaternion_mult_va,
  81607. vb = Quaternion_mult_vb,
  81608. vaxvb = Quaternion_mult_vaxvb;
  81609. va.set(this.x,this.y,this.z);
  81610. vb.set(q.x,q.y,q.z);
  81611. target.w = w*q.w - va.dot(vb);
  81612. va.cross(vb,vaxvb);
  81613. target.x = w * vb.x + q.w*va.x + vaxvb.x;
  81614. target.y = w * vb.y + q.w*va.y + vaxvb.y;
  81615. target.z = w * vb.z + q.w*va.z + vaxvb.z;
  81616. return target;
  81617. };
  81618. /**
  81619. * Get the inverse quaternion rotation.
  81620. * @method inverse
  81621. * @param {Quaternion} target
  81622. * @return {Quaternion}
  81623. */
  81624. Quaternion.prototype.inverse = function(target){
  81625. var x = this.x, y = this.y, z = this.z, w = this.w;
  81626. target = target || new Quaternion();
  81627. this.conjugate(target);
  81628. var inorm2 = 1/(x*x + y*y + z*z + w*w);
  81629. target.x *= inorm2;
  81630. target.y *= inorm2;
  81631. target.z *= inorm2;
  81632. target.w *= inorm2;
  81633. return target;
  81634. };
  81635. /**
  81636. * Get the quaternion conjugate
  81637. * @method conjugate
  81638. * @param {Quaternion} target
  81639. * @return {Quaternion}
  81640. */
  81641. Quaternion.prototype.conjugate = function(target){
  81642. target = target || new Quaternion();
  81643. target.x = -this.x;
  81644. target.y = -this.y;
  81645. target.z = -this.z;
  81646. target.w = this.w;
  81647. return target;
  81648. };
  81649. /**
  81650. * Normalize the quaternion. Note that this changes the values of the quaternion.
  81651. * @method normalize
  81652. */
  81653. Quaternion.prototype.normalize = function(){
  81654. var l = Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);
  81655. if ( l === 0 ) {
  81656. this.x = 0;
  81657. this.y = 0;
  81658. this.z = 0;
  81659. this.w = 0;
  81660. } else {
  81661. l = 1 / l;
  81662. this.x *= l;
  81663. this.y *= l;
  81664. this.z *= l;
  81665. this.w *= l;
  81666. }
  81667. };
  81668. /**
  81669. * Approximation of quaternion normalization. Works best when quat is already almost-normalized.
  81670. * @method normalizeFast
  81671. * @see http://jsperf.com/fast-quaternion-normalization
  81672. * @author unphased, https://github.com/unphased
  81673. */
  81674. Quaternion.prototype.normalizeFast = function () {
  81675. var f = (3.0-(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w))/2.0;
  81676. if ( f === 0 ) {
  81677. this.x = 0;
  81678. this.y = 0;
  81679. this.z = 0;
  81680. this.w = 0;
  81681. } else {
  81682. this.x *= f;
  81683. this.y *= f;
  81684. this.z *= f;
  81685. this.w *= f;
  81686. }
  81687. };
  81688. /**
  81689. * Multiply the quaternion by a vector
  81690. * @method vmult
  81691. * @param {Vec3} v
  81692. * @param {Vec3} target Optional
  81693. * @return {Vec3}
  81694. */
  81695. Quaternion.prototype.vmult = function(v,target){
  81696. target = target || new Vec3();
  81697. var x = v.x,
  81698. y = v.y,
  81699. z = v.z;
  81700. var qx = this.x,
  81701. qy = this.y,
  81702. qz = this.z,
  81703. qw = this.w;
  81704. // q*v
  81705. var ix = qw * x + qy * z - qz * y,
  81706. iy = qw * y + qz * x - qx * z,
  81707. iz = qw * z + qx * y - qy * x,
  81708. iw = -qx * x - qy * y - qz * z;
  81709. target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  81710. target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  81711. target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  81712. return target;
  81713. };
  81714. /**
  81715. * Copies value of source to this quaternion.
  81716. * @method copy
  81717. * @param {Quaternion} source
  81718. * @return {Quaternion} this
  81719. */
  81720. Quaternion.prototype.copy = function(source){
  81721. this.x = source.x;
  81722. this.y = source.y;
  81723. this.z = source.z;
  81724. this.w = source.w;
  81725. return this;
  81726. };
  81727. /**
  81728. * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: http://www.euclideanspace.com/maths/standards/index.htm
  81729. * @method toEuler
  81730. * @param {Vec3} target
  81731. * @param string order Three-character string e.g. "YZX", which also is default.
  81732. */
  81733. Quaternion.prototype.toEuler = function(target,order){
  81734. order = order || "YZX";
  81735. var heading, attitude, bank;
  81736. var x = this.x, y = this.y, z = this.z, w = this.w;
  81737. switch(order){
  81738. case "YZX":
  81739. var test = x*y + z*w;
  81740. if (test > 0.499) { // singularity at north pole
  81741. heading = 2 * Math.atan2(x,w);
  81742. attitude = Math.PI/2;
  81743. bank = 0;
  81744. }
  81745. if (test < -0.499) { // singularity at south pole
  81746. heading = -2 * Math.atan2(x,w);
  81747. attitude = - Math.PI/2;
  81748. bank = 0;
  81749. }
  81750. if(isNaN(heading)){
  81751. var sqx = x*x;
  81752. var sqy = y*y;
  81753. var sqz = z*z;
  81754. heading = Math.atan2(2*y*w - 2*x*z , 1 - 2*sqy - 2*sqz); // Heading
  81755. attitude = Math.asin(2*test); // attitude
  81756. bank = Math.atan2(2*x*w - 2*y*z , 1 - 2*sqx - 2*sqz); // bank
  81757. }
  81758. break;
  81759. default:
  81760. throw new Error("Euler order "+order+" not supported yet.");
  81761. }
  81762. target.y = heading;
  81763. target.z = attitude;
  81764. target.x = bank;
  81765. };
  81766. /**
  81767. * See http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  81768. * @method setFromEuler
  81769. * @param {Number} x
  81770. * @param {Number} y
  81771. * @param {Number} z
  81772. * @param {String} order The order to apply angles: 'XYZ' or 'YXZ' or any other combination
  81773. */
  81774. Quaternion.prototype.setFromEuler = function ( x, y, z, order ) {
  81775. order = order || "XYZ";
  81776. var c1 = Math.cos( x / 2 );
  81777. var c2 = Math.cos( y / 2 );
  81778. var c3 = Math.cos( z / 2 );
  81779. var s1 = Math.sin( x / 2 );
  81780. var s2 = Math.sin( y / 2 );
  81781. var s3 = Math.sin( z / 2 );
  81782. if ( order === 'XYZ' ) {
  81783. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  81784. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  81785. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  81786. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  81787. } else if ( order === 'YXZ' ) {
  81788. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  81789. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  81790. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  81791. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  81792. } else if ( order === 'ZXY' ) {
  81793. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  81794. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  81795. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  81796. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  81797. } else if ( order === 'ZYX' ) {
  81798. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  81799. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  81800. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  81801. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  81802. } else if ( order === 'YZX' ) {
  81803. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  81804. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  81805. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  81806. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  81807. } else if ( order === 'XZY' ) {
  81808. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  81809. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  81810. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  81811. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  81812. }
  81813. return this;
  81814. };
  81815. Quaternion.prototype.clone = function(){
  81816. return new Quaternion(this.x, this.y, this.z, this.w);
  81817. };
  81818. },{"./Vec3":30}],29:[function(_dereq_,module,exports){
  81819. var Vec3 = _dereq_('./Vec3');
  81820. var Quaternion = _dereq_('./Quaternion');
  81821. module.exports = Transform;
  81822. /**
  81823. * @class Transform
  81824. * @constructor
  81825. */
  81826. function Transform(options) {
  81827. options = options || {};
  81828. /**
  81829. * @property {Vec3} position
  81830. */
  81831. this.position = new Vec3();
  81832. if(options.position){
  81833. this.position.copy(options.position);
  81834. }
  81835. /**
  81836. * @property {Quaternion} quaternion
  81837. */
  81838. this.quaternion = new Quaternion();
  81839. if(options.quaternion){
  81840. this.quaternion.copy(options.quaternion);
  81841. }
  81842. }
  81843. var tmpQuat = new Quaternion();
  81844. /**
  81845. * @static
  81846. * @method pointToLocaFrame
  81847. * @param {Vec3} position
  81848. * @param {Quaternion} quaternion
  81849. * @param {Vec3} worldPoint
  81850. * @param {Vec3} result
  81851. */
  81852. Transform.pointToLocalFrame = function(position, quaternion, worldPoint, result){
  81853. var result = result || new Vec3();
  81854. worldPoint.vsub(position, result);
  81855. quaternion.conjugate(tmpQuat);
  81856. tmpQuat.vmult(result, result);
  81857. return result;
  81858. };
  81859. /**
  81860. * Get a global point in local transform coordinates.
  81861. * @method pointToLocal
  81862. * @param {Vec3} point
  81863. * @param {Vec3} result
  81864. * @return {Vec3} The "result" vector object
  81865. */
  81866. Transform.prototype.pointToLocal = function(worldPoint, result){
  81867. return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);
  81868. };
  81869. /**
  81870. * @static
  81871. * @method pointToWorldFrame
  81872. * @param {Vec3} position
  81873. * @param {Vec3} quaternion
  81874. * @param {Vec3} localPoint
  81875. * @param {Vec3} result
  81876. */
  81877. Transform.pointToWorldFrame = function(position, quaternion, localPoint, result){
  81878. var result = result || new Vec3();
  81879. quaternion.vmult(localPoint, result);
  81880. result.vadd(position, result);
  81881. return result;
  81882. };
  81883. /**
  81884. * Get a local point in global transform coordinates.
  81885. * @method pointToWorld
  81886. * @param {Vec3} point
  81887. * @param {Vec3} result
  81888. * @return {Vec3} The "result" vector object
  81889. */
  81890. Transform.prototype.pointToWorld = function(localPoint, result){
  81891. return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);
  81892. };
  81893. Transform.prototype.vectorToWorldFrame = function(localVector, result){
  81894. var result = result || new Vec3();
  81895. this.quaternion.vmult(localVector, result);
  81896. return result;
  81897. };
  81898. Transform.vectorToWorldFrame = function(quaternion, localVector, result){
  81899. quaternion.vmult(localVector, result);
  81900. return result;
  81901. };
  81902. Transform.vectorToLocalFrame = function(position, quaternion, worldVector, result){
  81903. var result = result || new Vec3();
  81904. quaternion.w *= -1;
  81905. quaternion.vmult(worldVector, result);
  81906. quaternion.w *= -1;
  81907. return result;
  81908. };
  81909. },{"./Quaternion":28,"./Vec3":30}],30:[function(_dereq_,module,exports){
  81910. module.exports = Vec3;
  81911. var Mat3 = _dereq_('./Mat3');
  81912. /**
  81913. * 3-dimensional vector
  81914. * @class Vec3
  81915. * @constructor
  81916. * @param {Number} x
  81917. * @param {Number} y
  81918. * @param {Number} z
  81919. * @author schteppe
  81920. * @example
  81921. * var v = new Vec3(1, 2, 3);
  81922. * console.log('x=' + v.x); // x=1
  81923. */
  81924. function Vec3(x,y,z){
  81925. /**
  81926. * @property x
  81927. * @type {Number}
  81928. */
  81929. this.x = x||0.0;
  81930. /**
  81931. * @property y
  81932. * @type {Number}
  81933. */
  81934. this.y = y||0.0;
  81935. /**
  81936. * @property z
  81937. * @type {Number}
  81938. */
  81939. this.z = z||0.0;
  81940. }
  81941. /**
  81942. * @static
  81943. * @property {Vec3} ZERO
  81944. */
  81945. Vec3.ZERO = new Vec3(0, 0, 0);
  81946. /**
  81947. * @static
  81948. * @property {Vec3} UNIT_X
  81949. */
  81950. Vec3.UNIT_X = new Vec3(1, 0, 0);
  81951. /**
  81952. * @static
  81953. * @property {Vec3} UNIT_Y
  81954. */
  81955. Vec3.UNIT_Y = new Vec3(0, 1, 0);
  81956. /**
  81957. * @static
  81958. * @property {Vec3} UNIT_Z
  81959. */
  81960. Vec3.UNIT_Z = new Vec3(0, 0, 1);
  81961. /**
  81962. * Vector cross product
  81963. * @method cross
  81964. * @param {Vec3} v
  81965. * @param {Vec3} target Optional. Target to save in.
  81966. * @return {Vec3}
  81967. */
  81968. Vec3.prototype.cross = function(v,target){
  81969. var vx=v.x, vy=v.y, vz=v.z, x=this.x, y=this.y, z=this.z;
  81970. target = target || new Vec3();
  81971. target.x = (y * vz) - (z * vy);
  81972. target.y = (z * vx) - (x * vz);
  81973. target.z = (x * vy) - (y * vx);
  81974. return target;
  81975. };
  81976. /**
  81977. * Set the vectors' 3 elements
  81978. * @method set
  81979. * @param {Number} x
  81980. * @param {Number} y
  81981. * @param {Number} z
  81982. * @return Vec3
  81983. */
  81984. Vec3.prototype.set = function(x,y,z){
  81985. this.x = x;
  81986. this.y = y;
  81987. this.z = z;
  81988. return this;
  81989. };
  81990. /**
  81991. * Set all components of the vector to zero.
  81992. * @method setZero
  81993. */
  81994. Vec3.prototype.setZero = function(){
  81995. this.x = this.y = this.z = 0;
  81996. };
  81997. /**
  81998. * Vector addition
  81999. * @method vadd
  82000. * @param {Vec3} v
  82001. * @param {Vec3} target Optional.
  82002. * @return {Vec3}
  82003. */
  82004. Vec3.prototype.vadd = function(v,target){
  82005. if(target){
  82006. target.x = v.x + this.x;
  82007. target.y = v.y + this.y;
  82008. target.z = v.z + this.z;
  82009. } else {
  82010. return new Vec3(this.x + v.x,
  82011. this.y + v.y,
  82012. this.z + v.z);
  82013. }
  82014. };
  82015. /**
  82016. * Vector subtraction
  82017. * @method vsub
  82018. * @param {Vec3} v
  82019. * @param {Vec3} target Optional. Target to save in.
  82020. * @return {Vec3}
  82021. */
  82022. Vec3.prototype.vsub = function(v,target){
  82023. if(target){
  82024. target.x = this.x - v.x;
  82025. target.y = this.y - v.y;
  82026. target.z = this.z - v.z;
  82027. } else {
  82028. return new Vec3(this.x-v.x,
  82029. this.y-v.y,
  82030. this.z-v.z);
  82031. }
  82032. };
  82033. /**
  82034. * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c
  82035. * @method crossmat
  82036. * @see http://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf
  82037. * @return {Mat3}
  82038. */
  82039. Vec3.prototype.crossmat = function(){
  82040. return new Mat3([ 0, -this.z, this.y,
  82041. this.z, 0, -this.x,
  82042. -this.y, this.x, 0]);
  82043. };
  82044. /**
  82045. * Normalize the vector. Note that this changes the values in the vector.
  82046. * @method normalize
  82047. * @return {Number} Returns the norm of the vector
  82048. */
  82049. Vec3.prototype.normalize = function(){
  82050. var x=this.x, y=this.y, z=this.z;
  82051. var n = Math.sqrt(x*x + y*y + z*z);
  82052. if(n>0.0){
  82053. var invN = 1/n;
  82054. this.x *= invN;
  82055. this.y *= invN;
  82056. this.z *= invN;
  82057. } else {
  82058. // Make something up
  82059. this.x = 0;
  82060. this.y = 0;
  82061. this.z = 0;
  82062. }
  82063. return n;
  82064. };
  82065. /**
  82066. * Get the version of this vector that is of length 1.
  82067. * @method unit
  82068. * @param {Vec3} target Optional target to save in
  82069. * @return {Vec3} Returns the unit vector
  82070. */
  82071. Vec3.prototype.unit = function(target){
  82072. target = target || new Vec3();
  82073. var x=this.x, y=this.y, z=this.z;
  82074. var ninv = Math.sqrt(x*x + y*y + z*z);
  82075. if(ninv>0.0){
  82076. ninv = 1.0/ninv;
  82077. target.x = x * ninv;
  82078. target.y = y * ninv;
  82079. target.z = z * ninv;
  82080. } else {
  82081. target.x = 1;
  82082. target.y = 0;
  82083. target.z = 0;
  82084. }
  82085. return target;
  82086. };
  82087. /**
  82088. * Get the length of the vector
  82089. * @method norm
  82090. * @return {Number}
  82091. * @deprecated Use .length() instead
  82092. */
  82093. Vec3.prototype.norm = function(){
  82094. var x=this.x, y=this.y, z=this.z;
  82095. return Math.sqrt(x*x + y*y + z*z);
  82096. };
  82097. /**
  82098. * Get the length of the vector
  82099. * @method length
  82100. * @return {Number}
  82101. */
  82102. Vec3.prototype.length = Vec3.prototype.norm;
  82103. /**
  82104. * Get the squared length of the vector
  82105. * @method norm2
  82106. * @return {Number}
  82107. * @deprecated Use .lengthSquared() instead.
  82108. */
  82109. Vec3.prototype.norm2 = function(){
  82110. return this.dot(this);
  82111. };
  82112. /**
  82113. * Get the squared length of the vector.
  82114. * @method lengthSquared
  82115. * @return {Number}
  82116. */
  82117. Vec3.prototype.lengthSquared = Vec3.prototype.norm2;
  82118. /**
  82119. * Get distance from this point to another point
  82120. * @method distanceTo
  82121. * @param {Vec3} p
  82122. * @return {Number}
  82123. */
  82124. Vec3.prototype.distanceTo = function(p){
  82125. var x=this.x, y=this.y, z=this.z;
  82126. var px=p.x, py=p.y, pz=p.z;
  82127. return Math.sqrt((px-x)*(px-x)+
  82128. (py-y)*(py-y)+
  82129. (pz-z)*(pz-z));
  82130. };
  82131. /**
  82132. * Get squared distance from this point to another point
  82133. * @method distanceSquared
  82134. * @param {Vec3} p
  82135. * @return {Number}
  82136. */
  82137. Vec3.prototype.distanceSquared = function(p){
  82138. var x=this.x, y=this.y, z=this.z;
  82139. var px=p.x, py=p.y, pz=p.z;
  82140. return (px-x)*(px-x) + (py-y)*(py-y) + (pz-z)*(pz-z);
  82141. };
  82142. /**
  82143. * Multiply all the components of the vector with a scalar.
  82144. * @deprecated Use .scale instead
  82145. * @method mult
  82146. * @param {Number} scalar
  82147. * @param {Vec3} target The vector to save the result in.
  82148. * @return {Vec3}
  82149. * @deprecated Use .scale() instead
  82150. */
  82151. Vec3.prototype.mult = function(scalar,target){
  82152. target = target || new Vec3();
  82153. var x = this.x,
  82154. y = this.y,
  82155. z = this.z;
  82156. target.x = scalar * x;
  82157. target.y = scalar * y;
  82158. target.z = scalar * z;
  82159. return target;
  82160. };
  82161. /**
  82162. * Multiply the vector with a scalar.
  82163. * @method scale
  82164. * @param {Number} scalar
  82165. * @param {Vec3} target
  82166. * @return {Vec3}
  82167. */
  82168. Vec3.prototype.scale = Vec3.prototype.mult;
  82169. /**
  82170. * Calculate dot product
  82171. * @method dot
  82172. * @param {Vec3} v
  82173. * @return {Number}
  82174. */
  82175. Vec3.prototype.dot = function(v){
  82176. return this.x * v.x + this.y * v.y + this.z * v.z;
  82177. };
  82178. /**
  82179. * @method isZero
  82180. * @return bool
  82181. */
  82182. Vec3.prototype.isZero = function(){
  82183. return this.x===0 && this.y===0 && this.z===0;
  82184. };
  82185. /**
  82186. * Make the vector point in the opposite direction.
  82187. * @method negate
  82188. * @param {Vec3} target Optional target to save in
  82189. * @return {Vec3}
  82190. */
  82191. Vec3.prototype.negate = function(target){
  82192. target = target || new Vec3();
  82193. target.x = -this.x;
  82194. target.y = -this.y;
  82195. target.z = -this.z;
  82196. return target;
  82197. };
  82198. /**
  82199. * Compute two artificial tangents to the vector
  82200. * @method tangents
  82201. * @param {Vec3} t1 Vector object to save the first tangent in
  82202. * @param {Vec3} t2 Vector object to save the second tangent in
  82203. */
  82204. var Vec3_tangents_n = new Vec3();
  82205. var Vec3_tangents_randVec = new Vec3();
  82206. Vec3.prototype.tangents = function(t1,t2){
  82207. var norm = this.norm();
  82208. if(norm>0.0){
  82209. var n = Vec3_tangents_n;
  82210. var inorm = 1/norm;
  82211. n.set(this.x*inorm,this.y*inorm,this.z*inorm);
  82212. var randVec = Vec3_tangents_randVec;
  82213. if(Math.abs(n.x) < 0.9){
  82214. randVec.set(1,0,0);
  82215. n.cross(randVec,t1);
  82216. } else {
  82217. randVec.set(0,1,0);
  82218. n.cross(randVec,t1);
  82219. }
  82220. n.cross(t1,t2);
  82221. } else {
  82222. // The normal length is zero, make something up
  82223. t1.set(1, 0, 0);
  82224. t2.set(0, 1, 0);
  82225. }
  82226. };
  82227. /**
  82228. * Converts to a more readable format
  82229. * @method toString
  82230. * @return string
  82231. */
  82232. Vec3.prototype.toString = function(){
  82233. return this.x+","+this.y+","+this.z;
  82234. };
  82235. /**
  82236. * Converts to an array
  82237. * @method toArray
  82238. * @return Array
  82239. */
  82240. Vec3.prototype.toArray = function(){
  82241. return [this.x, this.y, this.z];
  82242. };
  82243. /**
  82244. * Copies value of source to this vector.
  82245. * @method copy
  82246. * @param {Vec3} source
  82247. * @return {Vec3} this
  82248. */
  82249. Vec3.prototype.copy = function(source){
  82250. this.x = source.x;
  82251. this.y = source.y;
  82252. this.z = source.z;
  82253. return this;
  82254. };
  82255. /**
  82256. * Do a linear interpolation between two vectors
  82257. * @method lerp
  82258. * @param {Vec3} v
  82259. * @param {Number} t A number between 0 and 1. 0 will make this function return u, and 1 will make it return v. Numbers in between will generate a vector in between them.
  82260. * @param {Vec3} target
  82261. */
  82262. Vec3.prototype.lerp = function(v,t,target){
  82263. var x=this.x, y=this.y, z=this.z;
  82264. target.x = x + (v.x-x)*t;
  82265. target.y = y + (v.y-y)*t;
  82266. target.z = z + (v.z-z)*t;
  82267. };
  82268. /**
  82269. * Check if a vector equals is almost equal to another one.
  82270. * @method almostEquals
  82271. * @param {Vec3} v
  82272. * @param {Number} precision
  82273. * @return bool
  82274. */
  82275. Vec3.prototype.almostEquals = function(v,precision){
  82276. if(precision===undefined){
  82277. precision = 1e-6;
  82278. }
  82279. if( Math.abs(this.x-v.x)>precision ||
  82280. Math.abs(this.y-v.y)>precision ||
  82281. Math.abs(this.z-v.z)>precision){
  82282. return false;
  82283. }
  82284. return true;
  82285. };
  82286. /**
  82287. * Check if a vector is almost zero
  82288. * @method almostZero
  82289. * @param {Number} precision
  82290. */
  82291. Vec3.prototype.almostZero = function(precision){
  82292. if(precision===undefined){
  82293. precision = 1e-6;
  82294. }
  82295. if( Math.abs(this.x)>precision ||
  82296. Math.abs(this.y)>precision ||
  82297. Math.abs(this.z)>precision){
  82298. return false;
  82299. }
  82300. return true;
  82301. };
  82302. var antip_neg = new Vec3();
  82303. /**
  82304. * Check if the vector is anti-parallel to another vector.
  82305. * @method isAntiparallelTo
  82306. * @param {Vec3} v
  82307. * @param {Number} precision Set to zero for exact comparisons
  82308. * @return {Boolean}
  82309. */
  82310. Vec3.prototype.isAntiparallelTo = function(v,precision){
  82311. this.negate(antip_neg);
  82312. return antip_neg.almostEquals(v,precision);
  82313. };
  82314. /**
  82315. * Clone the vector
  82316. * @method clone
  82317. * @return {Vec3}
  82318. */
  82319. Vec3.prototype.clone = function(){
  82320. return new Vec3(this.x, this.y, this.z);
  82321. };
  82322. },{"./Mat3":27}],31:[function(_dereq_,module,exports){
  82323. module.exports = Body;
  82324. var EventTarget = _dereq_('../utils/EventTarget');
  82325. var Shape = _dereq_('../shapes/Shape');
  82326. var Vec3 = _dereq_('../math/Vec3');
  82327. var Mat3 = _dereq_('../math/Mat3');
  82328. var Quaternion = _dereq_('../math/Quaternion');
  82329. var Material = _dereq_('../material/Material');
  82330. var AABB = _dereq_('../collision/AABB');
  82331. var Box = _dereq_('../shapes/Box');
  82332. /**
  82333. * Base class for all body types.
  82334. * @class Body
  82335. * @constructor
  82336. * @extends EventTarget
  82337. * @param {object} [options]
  82338. * @param {Vec3} [options.position]
  82339. * @param {Vec3} [options.velocity]
  82340. * @param {Vec3} [options.angularVelocity]
  82341. * @param {Quaternion} [options.quaternion]
  82342. * @param {number} [options.mass]
  82343. * @param {Material} [options.material]
  82344. * @param {number} [options.type]
  82345. * @param {number} [options.linearDamping=0.01]
  82346. * @param {number} [options.angularDamping=0.01]
  82347. * @param {boolean} [options.allowSleep=true]
  82348. * @param {number} [options.sleepSpeedLimit=0.1]
  82349. * @param {number} [options.sleepTimeLimit=1]
  82350. * @param {number} [options.collisionFilterGroup=1]
  82351. * @param {number} [options.collisionFilterMask=1]
  82352. * @param {boolean} [options.fixedRotation=false]
  82353. * @param {Body} [options.shape]
  82354. * @example
  82355. * var body = new Body({
  82356. * mass: 1
  82357. * });
  82358. * var shape = new Sphere(1);
  82359. * body.addShape(shape);
  82360. * world.add(body);
  82361. */
  82362. function Body(options){
  82363. options = options || {};
  82364. EventTarget.apply(this);
  82365. this.id = Body.idCounter++;
  82366. /**
  82367. * Reference to the world the body is living in
  82368. * @property world
  82369. * @type {World}
  82370. */
  82371. this.world = null;
  82372. /**
  82373. * Callback function that is used BEFORE stepping the system. Use it to apply forces, for example. Inside the function, "this" will refer to this Body object.
  82374. * @property preStep
  82375. * @type {Function}
  82376. * @deprecated Use World events instead
  82377. */
  82378. this.preStep = null;
  82379. /**
  82380. * Callback function that is used AFTER stepping the system. Inside the function, "this" will refer to this Body object.
  82381. * @property postStep
  82382. * @type {Function}
  82383. * @deprecated Use World events instead
  82384. */
  82385. this.postStep = null;
  82386. this.vlambda = new Vec3();
  82387. /**
  82388. * @property {Number} collisionFilterGroup
  82389. */
  82390. this.collisionFilterGroup = typeof(options.collisionFilterGroup) === 'number' ? options.collisionFilterGroup : 1;
  82391. /**
  82392. * @property {Number} collisionFilterMask
  82393. */
  82394. this.collisionFilterMask = typeof(options.collisionFilterMask) === 'number' ? options.collisionFilterMask : 1;
  82395. /**
  82396. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  82397. * @property {Number} collisionResponse
  82398. */
  82399. this.collisionResponse = true;
  82400. /**
  82401. * @property position
  82402. * @type {Vec3}
  82403. */
  82404. this.position = new Vec3();
  82405. if(options.position){
  82406. this.position.copy(options.position);
  82407. }
  82408. /**
  82409. * @property {Vec3} previousPosition
  82410. */
  82411. this.previousPosition = new Vec3();
  82412. /**
  82413. * Initial position of the body
  82414. * @property initPosition
  82415. * @type {Vec3}
  82416. */
  82417. this.initPosition = new Vec3();
  82418. /**
  82419. * @property velocity
  82420. * @type {Vec3}
  82421. */
  82422. this.velocity = new Vec3();
  82423. if(options.velocity){
  82424. this.velocity.copy(options.velocity);
  82425. }
  82426. /**
  82427. * @property initVelocity
  82428. * @type {Vec3}
  82429. */
  82430. this.initVelocity = new Vec3();
  82431. /**
  82432. * Linear force on the body
  82433. * @property force
  82434. * @type {Vec3}
  82435. */
  82436. this.force = new Vec3();
  82437. var mass = typeof(options.mass) === 'number' ? options.mass : 0;
  82438. /**
  82439. * @property mass
  82440. * @type {Number}
  82441. * @default 0
  82442. */
  82443. this.mass = mass;
  82444. /**
  82445. * @property invMass
  82446. * @type {Number}
  82447. */
  82448. this.invMass = mass > 0 ? 1.0 / mass : 0;
  82449. /**
  82450. * @property material
  82451. * @type {Material}
  82452. */
  82453. this.material = options.material || null;
  82454. /**
  82455. * @property linearDamping
  82456. * @type {Number}
  82457. */
  82458. this.linearDamping = typeof(options.linearDamping) === 'number' ? options.linearDamping : 0.01;
  82459. /**
  82460. * One of: Body.DYNAMIC, Body.STATIC and Body.KINEMATIC.
  82461. * @property type
  82462. * @type {Number}
  82463. */
  82464. this.type = (mass <= 0.0 ? Body.STATIC : Body.DYNAMIC);
  82465. if(typeof(options.type) === typeof(Body.STATIC)){
  82466. this.type = options.type;
  82467. }
  82468. /**
  82469. * If true, the body will automatically fall to sleep.
  82470. * @property allowSleep
  82471. * @type {Boolean}
  82472. * @default true
  82473. */
  82474. this.allowSleep = typeof(options.allowSleep) !== 'undefined' ? options.allowSleep : true;
  82475. /**
  82476. * Current sleep state.
  82477. * @property sleepState
  82478. * @type {Number}
  82479. */
  82480. this.sleepState = 0;
  82481. /**
  82482. * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
  82483. * @property sleepSpeedLimit
  82484. * @type {Number}
  82485. * @default 0.1
  82486. */
  82487. this.sleepSpeedLimit = typeof(options.sleepSpeedLimit) !== 'undefined' ? options.sleepSpeedLimit : 0.1;
  82488. /**
  82489. * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
  82490. * @property sleepTimeLimit
  82491. * @type {Number}
  82492. * @default 1
  82493. */
  82494. this.sleepTimeLimit = typeof(options.sleepTimeLimit) !== 'undefined' ? options.sleepTimeLimit : 1;
  82495. this.timeLastSleepy = 0;
  82496. this._wakeUpAfterNarrowphase = false;
  82497. /**
  82498. * Rotational force on the body, around center of mass
  82499. * @property {Vec3} torque
  82500. */
  82501. this.torque = new Vec3();
  82502. /**
  82503. * Orientation of the body
  82504. * @property quaternion
  82505. * @type {Quaternion}
  82506. */
  82507. this.quaternion = new Quaternion();
  82508. if(options.quaternion){
  82509. this.quaternion.copy(options.quaternion);
  82510. }
  82511. /**
  82512. * @property initQuaternion
  82513. * @type {Quaternion}
  82514. */
  82515. this.initQuaternion = new Quaternion();
  82516. /**
  82517. * @property angularVelocity
  82518. * @type {Vec3}
  82519. */
  82520. this.angularVelocity = new Vec3();
  82521. if(options.angularVelocity){
  82522. this.angularVelocity.copy(options.angularVelocity);
  82523. }
  82524. /**
  82525. * @property initAngularVelocity
  82526. * @type {Vec3}
  82527. */
  82528. this.initAngularVelocity = new Vec3();
  82529. this.interpolatedPosition = new Vec3();
  82530. this.interpolatedQuaternion = new Quaternion();
  82531. /**
  82532. * @property shapes
  82533. * @type {array}
  82534. */
  82535. this.shapes = [];
  82536. /**
  82537. * @property shapeOffsets
  82538. * @type {array}
  82539. */
  82540. this.shapeOffsets = [];
  82541. /**
  82542. * @property shapeOrientations
  82543. * @type {array}
  82544. */
  82545. this.shapeOrientations = [];
  82546. /**
  82547. * @property inertia
  82548. * @type {Vec3}
  82549. */
  82550. this.inertia = new Vec3();
  82551. /**
  82552. * @property {Vec3} invInertia
  82553. */
  82554. this.invInertia = new Vec3();
  82555. /**
  82556. * @property {Mat3} invInertiaWorld
  82557. */
  82558. this.invInertiaWorld = new Mat3();
  82559. this.invMassSolve = 0;
  82560. /**
  82561. * @property {Vec3} invInertiaSolve
  82562. */
  82563. this.invInertiaSolve = new Vec3();
  82564. /**
  82565. * @property {Mat3} invInertiaWorldSolve
  82566. */
  82567. this.invInertiaWorldSolve = new Mat3();
  82568. /**
  82569. * Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() after changing this.
  82570. * @property {Boolean} fixedRotation
  82571. * @default false
  82572. */
  82573. this.fixedRotation = typeof(options.fixedRotation) !== "undefined" ? options.fixedRotation : false;
  82574. /**
  82575. * @property {Number} angularDamping
  82576. */
  82577. this.angularDamping = typeof(options.angularDamping) !== 'undefined' ? options.angularDamping : 0.01;
  82578. /**
  82579. * @property aabb
  82580. * @type {AABB}
  82581. */
  82582. this.aabb = new AABB();
  82583. /**
  82584. * Indicates if the AABB needs to be updated before use.
  82585. * @property aabbNeedsUpdate
  82586. * @type {Boolean}
  82587. */
  82588. this.aabbNeedsUpdate = true;
  82589. this.wlambda = new Vec3();
  82590. if(options.shape){
  82591. this.addShape(options.shape);
  82592. }
  82593. this.updateMassProperties();
  82594. }
  82595. Body.prototype = new EventTarget();
  82596. Body.prototype.constructor = Body;
  82597. /**
  82598. * A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.
  82599. * @static
  82600. * @property DYNAMIC
  82601. * @type {Number}
  82602. */
  82603. Body.DYNAMIC = 1;
  82604. /**
  82605. * A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.
  82606. * @static
  82607. * @property STATIC
  82608. * @type {Number}
  82609. */
  82610. Body.STATIC = 2;
  82611. /**
  82612. * A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.
  82613. * @static
  82614. * @property KINEMATIC
  82615. * @type {Number}
  82616. */
  82617. Body.KINEMATIC = 4;
  82618. /**
  82619. * @static
  82620. * @property AWAKE
  82621. * @type {number}
  82622. */
  82623. Body.AWAKE = 0;
  82624. /**
  82625. * @static
  82626. * @property SLEEPY
  82627. * @type {number}
  82628. */
  82629. Body.SLEEPY = 1;
  82630. /**
  82631. * @static
  82632. * @property SLEEPING
  82633. * @type {number}
  82634. */
  82635. Body.SLEEPING = 2;
  82636. Body.idCounter = 0;
  82637. /**
  82638. * Wake the body up.
  82639. * @method wakeUp
  82640. */
  82641. Body.prototype.wakeUp = function(){
  82642. var s = this.sleepState;
  82643. this.sleepState = 0;
  82644. if(s === Body.SLEEPING){
  82645. this.dispatchEvent({type:"wakeup"});
  82646. }
  82647. };
  82648. /**
  82649. * Force body sleep
  82650. * @method sleep
  82651. */
  82652. Body.prototype.sleep = function(){
  82653. this.sleepState = Body.SLEEPING;
  82654. this.velocity.set(0,0,0);
  82655. this.angularVelocity.set(0,0,0);
  82656. };
  82657. Body.sleepyEvent = {
  82658. type: "sleepy"
  82659. };
  82660. Body.sleepEvent = {
  82661. type: "sleep"
  82662. };
  82663. /**
  82664. * Called every timestep to update internal sleep timer and change sleep state if needed.
  82665. * @method sleepTick
  82666. * @param {Number} time The world time in seconds
  82667. */
  82668. Body.prototype.sleepTick = function(time){
  82669. if(this.allowSleep){
  82670. var sleepState = this.sleepState;
  82671. var speedSquared = this.velocity.norm2() + this.angularVelocity.norm2();
  82672. var speedLimitSquared = Math.pow(this.sleepSpeedLimit,2);
  82673. if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){
  82674. this.sleepState = Body.SLEEPY; // Sleepy
  82675. this.timeLastSleepy = time;
  82676. this.dispatchEvent(Body.sleepyEvent);
  82677. } else if(sleepState===Body.SLEEPY && speedSquared > speedLimitSquared){
  82678. this.wakeUp(); // Wake up
  82679. } else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){
  82680. this.sleep(); // Sleeping
  82681. this.dispatchEvent(Body.sleepEvent);
  82682. }
  82683. }
  82684. };
  82685. /**
  82686. * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass".
  82687. * @method updateSolveMassProperties
  82688. */
  82689. Body.prototype.updateSolveMassProperties = function(){
  82690. if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){
  82691. this.invMassSolve = 0;
  82692. this.invInertiaSolve.setZero();
  82693. this.invInertiaWorldSolve.setZero();
  82694. } else {
  82695. this.invMassSolve = this.invMass;
  82696. this.invInertiaSolve.copy(this.invInertia);
  82697. this.invInertiaWorldSolve.copy(this.invInertiaWorld);
  82698. }
  82699. };
  82700. /**
  82701. * Convert a world point to local body frame.
  82702. * @method pointToLocalFrame
  82703. * @param {Vec3} worldPoint
  82704. * @param {Vec3} result
  82705. * @return {Vec3}
  82706. */
  82707. Body.prototype.pointToLocalFrame = function(worldPoint,result){
  82708. var result = result || new Vec3();
  82709. worldPoint.vsub(this.position,result);
  82710. this.quaternion.conjugate().vmult(result,result);
  82711. return result;
  82712. };
  82713. /**
  82714. * Convert a world vector to local body frame.
  82715. * @method vectorToLocalFrame
  82716. * @param {Vec3} worldPoint
  82717. * @param {Vec3} result
  82718. * @return {Vec3}
  82719. */
  82720. Body.prototype.vectorToLocalFrame = function(worldVector, result){
  82721. var result = result || new Vec3();
  82722. this.quaternion.conjugate().vmult(worldVector,result);
  82723. return result;
  82724. };
  82725. /**
  82726. * Convert a local body point to world frame.
  82727. * @method pointToWorldFrame
  82728. * @param {Vec3} localPoint
  82729. * @param {Vec3} result
  82730. * @return {Vec3}
  82731. */
  82732. Body.prototype.pointToWorldFrame = function(localPoint,result){
  82733. var result = result || new Vec3();
  82734. this.quaternion.vmult(localPoint,result);
  82735. result.vadd(this.position,result);
  82736. return result;
  82737. };
  82738. /**
  82739. * Convert a local body point to world frame.
  82740. * @method vectorToWorldFrame
  82741. * @param {Vec3} localVector
  82742. * @param {Vec3} result
  82743. * @return {Vec3}
  82744. */
  82745. Body.prototype.vectorToWorldFrame = function(localVector, result){
  82746. var result = result || new Vec3();
  82747. this.quaternion.vmult(localVector, result);
  82748. return result;
  82749. };
  82750. var tmpVec = new Vec3();
  82751. var tmpQuat = new Quaternion();
  82752. /**
  82753. * Add a shape to the body with a local offset and orientation.
  82754. * @method addShape
  82755. * @param {Shape} shape
  82756. * @param {Vec3} offset
  82757. * @param {Quaternion} quaternion
  82758. * @return {Body} The body object, for chainability.
  82759. */
  82760. Body.prototype.addShape = function(shape, _offset, _orientation){
  82761. var offset = new Vec3();
  82762. var orientation = new Quaternion();
  82763. if(_offset){
  82764. offset.copy(_offset);
  82765. }
  82766. if(_orientation){
  82767. orientation.copy(_orientation);
  82768. }
  82769. this.shapes.push(shape);
  82770. this.shapeOffsets.push(offset);
  82771. this.shapeOrientations.push(orientation);
  82772. this.updateMassProperties();
  82773. this.updateBoundingRadius();
  82774. this.aabbNeedsUpdate = true;
  82775. return this;
  82776. };
  82777. /**
  82778. * Update the bounding radius of the body. Should be done if any of the shapes are changed.
  82779. * @method updateBoundingRadius
  82780. */
  82781. Body.prototype.updateBoundingRadius = function(){
  82782. var shapes = this.shapes,
  82783. shapeOffsets = this.shapeOffsets,
  82784. N = shapes.length,
  82785. radius = 0;
  82786. for(var i=0; i!==N; i++){
  82787. var shape = shapes[i];
  82788. shape.updateBoundingSphereRadius();
  82789. var offset = shapeOffsets[i].norm(),
  82790. r = shape.boundingSphereRadius;
  82791. if(offset + r > radius){
  82792. radius = offset + r;
  82793. }
  82794. }
  82795. this.boundingRadius = radius;
  82796. };
  82797. var computeAABB_shapeAABB = new AABB();
  82798. /**
  82799. * Updates the .aabb
  82800. * @method computeAABB
  82801. * @todo rename to updateAABB()
  82802. */
  82803. Body.prototype.computeAABB = function(){
  82804. var shapes = this.shapes,
  82805. shapeOffsets = this.shapeOffsets,
  82806. shapeOrientations = this.shapeOrientations,
  82807. N = shapes.length,
  82808. offset = tmpVec,
  82809. orientation = tmpQuat,
  82810. bodyQuat = this.quaternion,
  82811. aabb = this.aabb,
  82812. shapeAABB = computeAABB_shapeAABB;
  82813. for(var i=0; i!==N; i++){
  82814. var shape = shapes[i];
  82815. // Get shape world quaternion
  82816. shapeOrientations[i].mult(bodyQuat, orientation);
  82817. // Get shape world position
  82818. orientation.vmult(shapeOffsets[i], offset);
  82819. offset.vadd(this.position, offset);
  82820. // vec2.rotate(offset, shapeOffsets[i], bodyAngle);
  82821. // vec2.add(offset, offset, this.position);
  82822. // Get shape AABB
  82823. shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);
  82824. if(i === 0){
  82825. aabb.copy(shapeAABB);
  82826. } else {
  82827. aabb.extend(shapeAABB);
  82828. }
  82829. }
  82830. this.aabbNeedsUpdate = false;
  82831. };
  82832. var uiw_m1 = new Mat3(),
  82833. uiw_m2 = new Mat3(),
  82834. uiw_m3 = new Mat3();
  82835. /**
  82836. * Update .inertiaWorld and .invInertiaWorld
  82837. * @method updateInertiaWorld
  82838. */
  82839. Body.prototype.updateInertiaWorld = function(force){
  82840. var I = this.invInertia;
  82841. if (I.x === I.y && I.y === I.z && !force) {
  82842. // If inertia M = s*I, where I is identity and s a scalar, then
  82843. // R*M*R' = R*(s*I)*R' = s*R*I*R' = s*R*R' = s*I = M
  82844. // where R is the rotation matrix.
  82845. // In other words, we don't have to transform the inertia if all
  82846. // inertia diagonal entries are equal.
  82847. } else {
  82848. var m1 = uiw_m1,
  82849. m2 = uiw_m2,
  82850. m3 = uiw_m3;
  82851. m1.setRotationFromQuaternion(this.quaternion);
  82852. m1.transpose(m2);
  82853. m1.scale(I,m1);
  82854. m1.mmult(m2,this.invInertiaWorld);
  82855. //m3.getTrace(this.invInertiaWorld);
  82856. }
  82857. /*
  82858. this.quaternion.vmult(this.inertia,this.inertiaWorld);
  82859. this.quaternion.vmult(this.invInertia,this.invInertiaWorld);
  82860. */
  82861. };
  82862. /**
  82863. * Apply force to a world point. This could for example be a point on the Body surface. Applying force this way will add to Body.force and Body.torque.
  82864. * @method applyForce
  82865. * @param {Vec3} force The amount of force to add.
  82866. * @param {Vec3} worldPoint A world point to apply the force on.
  82867. */
  82868. var Body_applyForce_r = new Vec3();
  82869. var Body_applyForce_rotForce = new Vec3();
  82870. Body.prototype.applyForce = function(force,worldPoint){
  82871. if(this.type !== Body.DYNAMIC){
  82872. return;
  82873. }
  82874. // Compute point position relative to the body center
  82875. var r = Body_applyForce_r;
  82876. worldPoint.vsub(this.position,r);
  82877. // Compute produced rotational force
  82878. var rotForce = Body_applyForce_rotForce;
  82879. r.cross(force,rotForce);
  82880. // Add linear force
  82881. this.force.vadd(force,this.force);
  82882. // Add rotational force
  82883. this.torque.vadd(rotForce,this.torque);
  82884. };
  82885. /**
  82886. * Apply force to a local point in the body.
  82887. * @method applyLocalForce
  82888. * @param {Vec3} force The force vector to apply, defined locally in the body frame.
  82889. * @param {Vec3} localPoint A local point in the body to apply the force on.
  82890. */
  82891. var Body_applyLocalForce_worldForce = new Vec3();
  82892. var Body_applyLocalForce_worldPoint = new Vec3();
  82893. Body.prototype.applyLocalForce = function(localForce, localPoint){
  82894. if(this.type !== Body.DYNAMIC){
  82895. return;
  82896. }
  82897. var worldForce = Body_applyLocalForce_worldForce;
  82898. var worldPoint = Body_applyLocalForce_worldPoint;
  82899. // Transform the force vector to world space
  82900. this.vectorToWorldFrame(localForce, worldForce);
  82901. this.pointToWorldFrame(localPoint, worldPoint);
  82902. this.applyForce(worldForce, worldPoint);
  82903. };
  82904. /**
  82905. * Apply impulse to a world point. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
  82906. * @method applyImpulse
  82907. * @param {Vec3} impulse The amount of impulse to add.
  82908. * @param {Vec3} worldPoint A world point to apply the force on.
  82909. */
  82910. var Body_applyImpulse_r = new Vec3();
  82911. var Body_applyImpulse_velo = new Vec3();
  82912. var Body_applyImpulse_rotVelo = new Vec3();
  82913. Body.prototype.applyImpulse = function(impulse, worldPoint){
  82914. if(this.type !== Body.DYNAMIC){
  82915. return;
  82916. }
  82917. // Compute point position relative to the body center
  82918. var r = Body_applyImpulse_r;
  82919. worldPoint.vsub(this.position,r);
  82920. // Compute produced central impulse velocity
  82921. var velo = Body_applyImpulse_velo;
  82922. velo.copy(impulse);
  82923. velo.mult(this.invMass,velo);
  82924. // Add linear impulse
  82925. this.velocity.vadd(velo, this.velocity);
  82926. // Compute produced rotational impulse velocity
  82927. var rotVelo = Body_applyImpulse_rotVelo;
  82928. r.cross(impulse,rotVelo);
  82929. /*
  82930. rotVelo.x *= this.invInertia.x;
  82931. rotVelo.y *= this.invInertia.y;
  82932. rotVelo.z *= this.invInertia.z;
  82933. */
  82934. this.invInertiaWorld.vmult(rotVelo,rotVelo);
  82935. // Add rotational Impulse
  82936. this.angularVelocity.vadd(rotVelo, this.angularVelocity);
  82937. };
  82938. /**
  82939. * Apply locally-defined impulse to a local point in the body.
  82940. * @method applyLocalImpulse
  82941. * @param {Vec3} force The force vector to apply, defined locally in the body frame.
  82942. * @param {Vec3} localPoint A local point in the body to apply the force on.
  82943. */
  82944. var Body_applyLocalImpulse_worldImpulse = new Vec3();
  82945. var Body_applyLocalImpulse_worldPoint = new Vec3();
  82946. Body.prototype.applyLocalImpulse = function(localImpulse, localPoint){
  82947. if(this.type !== Body.DYNAMIC){
  82948. return;
  82949. }
  82950. var worldImpulse = Body_applyLocalImpulse_worldImpulse;
  82951. var worldPoint = Body_applyLocalImpulse_worldPoint;
  82952. // Transform the force vector to world space
  82953. this.vectorToWorldFrame(localImpulse, worldImpulse);
  82954. this.pointToWorldFrame(localPoint, worldPoint);
  82955. this.applyImpulse(worldImpulse, worldPoint);
  82956. };
  82957. var Body_updateMassProperties_halfExtents = new Vec3();
  82958. /**
  82959. * Should be called whenever you change the body shape or mass.
  82960. * @method updateMassProperties
  82961. */
  82962. Body.prototype.updateMassProperties = function(){
  82963. var halfExtents = Body_updateMassProperties_halfExtents;
  82964. this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;
  82965. var I = this.inertia;
  82966. var fixed = this.fixedRotation;
  82967. // Approximate with AABB box
  82968. this.computeAABB();
  82969. halfExtents.set(
  82970. (this.aabb.upperBound.x-this.aabb.lowerBound.x) / 2,
  82971. (this.aabb.upperBound.y-this.aabb.lowerBound.y) / 2,
  82972. (this.aabb.upperBound.z-this.aabb.lowerBound.z) / 2
  82973. );
  82974. Box.calculateInertia(halfExtents, this.mass, I);
  82975. this.invInertia.set(
  82976. I.x > 0 && !fixed ? 1.0 / I.x : 0,
  82977. I.y > 0 && !fixed ? 1.0 / I.y : 0,
  82978. I.z > 0 && !fixed ? 1.0 / I.z : 0
  82979. );
  82980. this.updateInertiaWorld(true);
  82981. };
  82982. /**
  82983. * Get world velocity of a point in the body.
  82984. * @method getVelocityAtWorldPoint
  82985. * @param {Vec3} worldPoint
  82986. * @param {Vec3} result
  82987. * @return {Vec3} The result vector.
  82988. */
  82989. Body.prototype.getVelocityAtWorldPoint = function(worldPoint, result){
  82990. var r = new Vec3();
  82991. worldPoint.vsub(this.position, r);
  82992. this.angularVelocity.cross(r, result);
  82993. this.velocity.vadd(result, result);
  82994. return result;
  82995. };
  82996. },{"../collision/AABB":3,"../material/Material":25,"../math/Mat3":27,"../math/Quaternion":28,"../math/Vec3":30,"../shapes/Box":37,"../shapes/Shape":43,"../utils/EventTarget":49}],32:[function(_dereq_,module,exports){
  82997. var Body = _dereq_('./Body');
  82998. var Vec3 = _dereq_('../math/Vec3');
  82999. var Quaternion = _dereq_('../math/Quaternion');
  83000. var RaycastResult = _dereq_('../collision/RaycastResult');
  83001. var Ray = _dereq_('../collision/Ray');
  83002. var WheelInfo = _dereq_('../objects/WheelInfo');
  83003. module.exports = RaycastVehicle;
  83004. /**
  83005. * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces.
  83006. * @class RaycastVehicle
  83007. * @constructor
  83008. * @param {object} [options]
  83009. * @param {Body} [options.chassisBody] The car chassis body.
  83010. * @param {integer} [options.indexRightAxis] Axis to use for right. x=0, y=1, z=2
  83011. * @param {integer} [options.indexLeftAxis]
  83012. * @param {integer} [options.indexUpAxis]
  83013. */
  83014. function RaycastVehicle(options){
  83015. /**
  83016. * @property {Body} chassisBody
  83017. */
  83018. this.chassisBody = options.chassisBody;
  83019. /**
  83020. * An array of WheelInfo objects.
  83021. * @property {array} wheelInfos
  83022. */
  83023. this.wheelInfos = [];
  83024. /**
  83025. * Will be set to true if the car is sliding.
  83026. * @property {boolean} sliding
  83027. */
  83028. this.sliding = false;
  83029. /**
  83030. * @property {World} world
  83031. */
  83032. this.world = null;
  83033. /**
  83034. * Index of the right axis, 0=x, 1=y, 2=z
  83035. * @property {integer} indexRightAxis
  83036. * @default 1
  83037. */
  83038. this.indexRightAxis = typeof(options.indexRightAxis) !== 'undefined' ? options.indexRightAxis : 1;
  83039. /**
  83040. * Index of the forward axis, 0=x, 1=y, 2=z
  83041. * @property {integer} indexForwardAxis
  83042. * @default 0
  83043. */
  83044. this.indexForwardAxis = typeof(options.indexForwardAxis) !== 'undefined' ? options.indexForwardAxis : 0;
  83045. /**
  83046. * Index of the up axis, 0=x, 1=y, 2=z
  83047. * @property {integer} indexUpAxis
  83048. * @default 2
  83049. */
  83050. this.indexUpAxis = typeof(options.indexUpAxis) !== 'undefined' ? options.indexUpAxis : 2;
  83051. }
  83052. var tmpVec1 = new Vec3();
  83053. var tmpVec2 = new Vec3();
  83054. var tmpVec3 = new Vec3();
  83055. var tmpVec4 = new Vec3();
  83056. var tmpVec5 = new Vec3();
  83057. var tmpVec6 = new Vec3();
  83058. var tmpRay = new Ray();
  83059. /**
  83060. * Add a wheel. For information about the options, see WheelInfo.
  83061. * @method addWheel
  83062. * @param {object} [options]
  83063. */
  83064. RaycastVehicle.prototype.addWheel = function(options){
  83065. options = options || {};
  83066. var info = new WheelInfo(options);
  83067. var index = this.wheelInfos.length;
  83068. this.wheelInfos.push(info);
  83069. return index;
  83070. };
  83071. /**
  83072. * Set the steering value of a wheel.
  83073. * @method setSteeringValue
  83074. * @param {number} value
  83075. * @param {integer} wheelIndex
  83076. */
  83077. RaycastVehicle.prototype.setSteeringValue = function(value, wheelIndex){
  83078. var wheel = this.wheelInfos[wheelIndex];
  83079. wheel.steering = value;
  83080. };
  83081. var torque = new Vec3();
  83082. /**
  83083. * Set the wheel force to apply on one of the wheels each time step
  83084. * @method applyEngineForce
  83085. * @param {number} value
  83086. * @param {integer} wheelIndex
  83087. */
  83088. RaycastVehicle.prototype.applyEngineForce = function(value, wheelIndex){
  83089. this.wheelInfos[wheelIndex].engineForce = value;
  83090. };
  83091. /**
  83092. * Set the braking force of a wheel
  83093. * @method setBrake
  83094. * @param {number} brake
  83095. * @param {integer} wheelIndex
  83096. */
  83097. RaycastVehicle.prototype.setBrake = function(brake, wheelIndex){
  83098. this.wheelInfos[wheelIndex].brake = brake;
  83099. };
  83100. /**
  83101. * Add the vehicle including its constraints to the world.
  83102. * @method addToWorld
  83103. * @param {World} world
  83104. */
  83105. RaycastVehicle.prototype.addToWorld = function(world){
  83106. var constraints = this.constraints;
  83107. world.add(this.chassisBody);
  83108. var that = this;
  83109. this.preStepCallback = function(){
  83110. that.updateVehicle(world.dt);
  83111. };
  83112. world.addEventListener('preStep', this.preStepCallback);
  83113. this.world = world;
  83114. };
  83115. /**
  83116. * Get one of the wheel axles, world-oriented.
  83117. * @private
  83118. * @method getVehicleAxisWorld
  83119. * @param {integer} axisIndex
  83120. * @param {Vec3} result
  83121. */
  83122. RaycastVehicle.prototype.getVehicleAxisWorld = function(axisIndex, result){
  83123. result.set(
  83124. axisIndex === 0 ? 1 : 0,
  83125. axisIndex === 1 ? 1 : 0,
  83126. axisIndex === 2 ? 1 : 0
  83127. );
  83128. this.chassisBody.vectorToWorldFrame(result, result);
  83129. };
  83130. RaycastVehicle.prototype.updateVehicle = function(timeStep){
  83131. var wheelInfos = this.wheelInfos;
  83132. var numWheels = wheelInfos.length;
  83133. var chassisBody = this.chassisBody;
  83134. for (var i = 0; i < numWheels; i++) {
  83135. this.updateWheelTransform(i);
  83136. }
  83137. this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.norm();
  83138. var forwardWorld = new Vec3();
  83139. this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld);
  83140. if (forwardWorld.dot(chassisBody.velocity) < 0){
  83141. this.currentVehicleSpeedKmHour *= -1;
  83142. }
  83143. // simulate suspension
  83144. for (var i = 0; i < numWheels; i++) {
  83145. this.castRay(wheelInfos[i]);
  83146. }
  83147. this.updateSuspension(timeStep);
  83148. var impulse = new Vec3();
  83149. var relpos = new Vec3();
  83150. for (var i = 0; i < numWheels; i++) {
  83151. //apply suspension force
  83152. var wheel = wheelInfos[i];
  83153. var suspensionForce = wheel.suspensionForce;
  83154. if (suspensionForce > wheel.maxSuspensionForce) {
  83155. suspensionForce = wheel.maxSuspensionForce;
  83156. }
  83157. wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);
  83158. wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);
  83159. chassisBody.applyImpulse(impulse, wheel.raycastResult.hitPointWorld/*relpos*/);
  83160. }
  83161. this.updateFriction(timeStep);
  83162. var hitNormalWorldScaledWithProj = new Vec3();
  83163. var fwd = new Vec3();
  83164. var vel = new Vec3();
  83165. for (i = 0; i < numWheels; i++) {
  83166. var wheel = wheelInfos[i];
  83167. //var relpos = new Vec3();
  83168. //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);
  83169. chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel);
  83170. // Hack to get the rotation in the correct direction
  83171. var m = 1;
  83172. switch(this.indexUpAxis){
  83173. case 1:
  83174. m = -1;
  83175. break;
  83176. }
  83177. if (wheel.isInContact) {
  83178. this.getVehicleAxisWorld(this.indexForwardAxis, fwd);
  83179. var proj = fwd.dot(wheel.raycastResult.hitNormalWorld);
  83180. wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);
  83181. fwd.vsub(hitNormalWorldScaledWithProj, fwd);
  83182. var proj2 = fwd.dot(vel);
  83183. wheel.deltaRotation = m * proj2 * timeStep / wheel.radius;
  83184. }
  83185. if((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed){
  83186. // Apply custom rotation when accelerating and sliding
  83187. wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;
  83188. }
  83189. // Lock wheels
  83190. if(Math.abs(wheel.brake) > Math.abs(wheel.engineForce)){
  83191. wheel.deltaRotation = 0;
  83192. }
  83193. wheel.rotation += wheel.deltaRotation; // Use the old value
  83194. wheel.deltaRotation *= 0.99; // damping of rotation when not in contact
  83195. }
  83196. };
  83197. RaycastVehicle.prototype.updateSuspension = function(deltaTime) {
  83198. var chassisBody = this.chassisBody;
  83199. var chassisMass = chassisBody.mass;
  83200. var wheelInfos = this.wheelInfos;
  83201. var numWheels = wheelInfos.length;
  83202. for (var w_it = 0; w_it < numWheels; w_it++){
  83203. var wheel = wheelInfos[w_it];
  83204. if (wheel.isInContact){
  83205. var force;
  83206. // Spring
  83207. var susp_length = wheel.suspensionRestLength;
  83208. var current_length = wheel.suspensionLength;
  83209. var length_diff = (susp_length - current_length);
  83210. force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension;
  83211. // Damper
  83212. var projected_rel_vel = wheel.suspensionRelativeVelocity;
  83213. var susp_damping;
  83214. if (projected_rel_vel < 0) {
  83215. susp_damping = wheel.dampingCompression;
  83216. } else {
  83217. susp_damping = wheel.dampingRelaxation;
  83218. }
  83219. force -= susp_damping * projected_rel_vel;
  83220. wheel.suspensionForce = force * chassisMass;
  83221. if (wheel.suspensionForce < 0) {
  83222. wheel.suspensionForce = 0;
  83223. }
  83224. } else {
  83225. wheel.suspensionForce = 0;
  83226. }
  83227. }
  83228. };
  83229. /**
  83230. * Remove the vehicle including its constraints from the world.
  83231. * @method removeFromWorld
  83232. * @param {World} world
  83233. */
  83234. RaycastVehicle.prototype.removeFromWorld = function(world){
  83235. var constraints = this.constraints;
  83236. world.remove(this.chassisBody);
  83237. world.removeEventListener('preStep', this.preStepCallback);
  83238. this.world = null;
  83239. };
  83240. var castRay_rayvector = new Vec3();
  83241. var castRay_target = new Vec3();
  83242. RaycastVehicle.prototype.castRay = function(wheel) {
  83243. var rayvector = castRay_rayvector;
  83244. var target = castRay_target;
  83245. this.updateWheelTransformWorld(wheel);
  83246. var chassisBody = this.chassisBody;
  83247. var depth = -1;
  83248. var raylen = wheel.suspensionRestLength + wheel.radius;
  83249. wheel.directionWorld.scale(raylen, rayvector);
  83250. var source = wheel.chassisConnectionPointWorld;
  83251. source.vadd(rayvector, target);
  83252. var raycastResult = wheel.raycastResult;
  83253. var param = 0;
  83254. raycastResult.reset();
  83255. // Turn off ray collision with the chassis temporarily
  83256. var oldState = chassisBody.collisionResponse;
  83257. chassisBody.collisionResponse = false;
  83258. // Cast ray against world
  83259. this.world.rayTest(source, target, raycastResult);
  83260. chassisBody.collisionResponse = oldState;
  83261. var object = raycastResult.body;
  83262. wheel.raycastResult.groundObject = 0;
  83263. if (object) {
  83264. depth = raycastResult.distance;
  83265. wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld;
  83266. wheel.isInContact = true;
  83267. var hitDistance = raycastResult.distance;
  83268. wheel.suspensionLength = hitDistance - wheel.radius;
  83269. // clamp on max suspension travel
  83270. var minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel;
  83271. var maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel;
  83272. if (wheel.suspensionLength < minSuspensionLength) {
  83273. wheel.suspensionLength = minSuspensionLength;
  83274. }
  83275. if (wheel.suspensionLength > maxSuspensionLength) {
  83276. wheel.suspensionLength = maxSuspensionLength;
  83277. wheel.raycastResult.reset();
  83278. }
  83279. var denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld);
  83280. var chassis_velocity_at_contactPoint = new Vec3();
  83281. chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld, chassis_velocity_at_contactPoint);
  83282. var projVel = wheel.raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint );
  83283. if (denominator >= -0.1) {
  83284. wheel.suspensionRelativeVelocity = 0;
  83285. wheel.clippedInvContactDotSuspension = 1 / 0.1;
  83286. } else {
  83287. var inv = -1 / denominator;
  83288. wheel.suspensionRelativeVelocity = projVel * inv;
  83289. wheel.clippedInvContactDotSuspension = inv;
  83290. }
  83291. } else {
  83292. //put wheel info as in rest position
  83293. wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel;
  83294. wheel.suspensionRelativeVelocity = 0.0;
  83295. wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld);
  83296. wheel.clippedInvContactDotSuspension = 1.0;
  83297. }
  83298. return depth;
  83299. };
  83300. RaycastVehicle.prototype.updateWheelTransformWorld = function(wheel){
  83301. wheel.isInContact = false;
  83302. var chassisBody = this.chassisBody;
  83303. chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld);
  83304. chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld);
  83305. chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld);
  83306. };
  83307. /**
  83308. * Update one of the wheel transform.
  83309. * Note when rendering wheels: during each step, wheel transforms are updated BEFORE the chassis; ie. their position becomes invalid after the step. Thus when you render wheels, you must update wheel transforms before rendering them. See raycastVehicle demo for an example.
  83310. * @method updateWheelTransform
  83311. * @param {integer} wheelIndex The wheel index to update.
  83312. */
  83313. RaycastVehicle.prototype.updateWheelTransform = function(wheelIndex){
  83314. var up = tmpVec4;
  83315. var right = tmpVec5;
  83316. var fwd = tmpVec6;
  83317. var wheel = this.wheelInfos[wheelIndex];
  83318. this.updateWheelTransformWorld(wheel);
  83319. wheel.directionLocal.scale(-1, up);
  83320. right.copy(wheel.axleLocal);
  83321. up.cross(right, fwd);
  83322. fwd.normalize();
  83323. right.normalize();
  83324. // Rotate around steering over the wheelAxle
  83325. var steering = wheel.steering;
  83326. var steeringOrn = new Quaternion();
  83327. steeringOrn.setFromAxisAngle(up, steering);
  83328. var rotatingOrn = new Quaternion();
  83329. rotatingOrn.setFromAxisAngle(right, wheel.rotation);
  83330. // World rotation of the wheel
  83331. var q = wheel.worldTransform.quaternion;
  83332. this.chassisBody.quaternion.mult(steeringOrn, q);
  83333. q.mult(rotatingOrn, q);
  83334. q.normalize();
  83335. // world position of the wheel
  83336. var p = wheel.worldTransform.position;
  83337. p.copy(wheel.directionWorld);
  83338. p.scale(wheel.suspensionLength, p);
  83339. p.vadd(wheel.chassisConnectionPointWorld, p);
  83340. };
  83341. var directions = [
  83342. new Vec3(1, 0, 0),
  83343. new Vec3(0, 1, 0),
  83344. new Vec3(0, 0, 1)
  83345. ];
  83346. /**
  83347. * Get the world transform of one of the wheels
  83348. * @method getWheelTransformWorld
  83349. * @param {integer} wheelIndex
  83350. * @return {Transform}
  83351. */
  83352. RaycastVehicle.prototype.getWheelTransformWorld = function(wheelIndex) {
  83353. return this.wheelInfos[wheelIndex].worldTransform;
  83354. };
  83355. var updateFriction_surfNormalWS_scaled_proj = new Vec3();
  83356. var updateFriction_axle = [];
  83357. var updateFriction_forwardWS = [];
  83358. var sideFrictionStiffness2 = 1;
  83359. RaycastVehicle.prototype.updateFriction = function(timeStep) {
  83360. var surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj;
  83361. //calculate the impulse, so that the wheels don't move sidewards
  83362. var wheelInfos = this.wheelInfos;
  83363. var numWheels = wheelInfos.length;
  83364. var chassisBody = this.chassisBody;
  83365. var forwardWS = updateFriction_forwardWS;
  83366. var axle = updateFriction_axle;
  83367. var numWheelsOnGround = 0;
  83368. for (var i = 0; i < numWheels; i++) {
  83369. var wheel = wheelInfos[i];
  83370. var groundObject = wheel.raycastResult.body;
  83371. if (groundObject){
  83372. numWheelsOnGround++;
  83373. }
  83374. wheel.sideImpulse = 0;
  83375. wheel.forwardImpulse = 0;
  83376. if(!forwardWS[i]){
  83377. forwardWS[i] = new Vec3();
  83378. }
  83379. if(!axle[i]){
  83380. axle[i] = new Vec3();
  83381. }
  83382. }
  83383. for (var i = 0; i < numWheels; i++){
  83384. var wheel = wheelInfos[i];
  83385. var groundObject = wheel.raycastResult.body;
  83386. if (groundObject) {
  83387. var axlei = axle[i];
  83388. var wheelTrans = this.getWheelTransformWorld(i);
  83389. // Get world axle
  83390. wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei);
  83391. var surfNormalWS = wheel.raycastResult.hitNormalWorld;
  83392. var proj = axlei.dot(surfNormalWS);
  83393. surfNormalWS.scale(proj, surfNormalWS_scaled_proj);
  83394. axlei.vsub(surfNormalWS_scaled_proj, axlei);
  83395. axlei.normalize();
  83396. surfNormalWS.cross(axlei, forwardWS[i]);
  83397. forwardWS[i].normalize();
  83398. wheel.sideImpulse = resolveSingleBilateral(
  83399. chassisBody,
  83400. wheel.raycastResult.hitPointWorld,
  83401. groundObject,
  83402. wheel.raycastResult.hitPointWorld,
  83403. axlei
  83404. );
  83405. wheel.sideImpulse *= sideFrictionStiffness2;
  83406. }
  83407. }
  83408. var sideFactor = 1;
  83409. var fwdFactor = 0.5;
  83410. this.sliding = false;
  83411. for (var i = 0; i < numWheels; i++) {
  83412. var wheel = wheelInfos[i];
  83413. var groundObject = wheel.raycastResult.body;
  83414. var rollingFriction = 0;
  83415. wheel.slipInfo = 1;
  83416. if (groundObject) {
  83417. var defaultRollingFrictionImpulse = 0;
  83418. var maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse;
  83419. // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse);
  83420. // rollingFriction = calcRollingFriction(contactPt);
  83421. rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse);
  83422. rollingFriction += wheel.engineForce * timeStep;
  83423. // rollingFriction = 0;
  83424. var factor = maxImpulse / rollingFriction;
  83425. wheel.slipInfo *= factor;
  83426. }
  83427. //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break)
  83428. wheel.forwardImpulse = 0;
  83429. wheel.skidInfo = 1;
  83430. if (groundObject) {
  83431. wheel.skidInfo = 1;
  83432. var maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip;
  83433. var maximpSide = maximp;
  83434. var maximpSquared = maximp * maximpSide;
  83435. wheel.forwardImpulse = rollingFriction;//wheelInfo.engineForce* timeStep;
  83436. var x = wheel.forwardImpulse * fwdFactor;
  83437. var y = wheel.sideImpulse * sideFactor;
  83438. var impulseSquared = x * x + y * y;
  83439. wheel.sliding = false;
  83440. if (impulseSquared > maximpSquared) {
  83441. this.sliding = true;
  83442. wheel.sliding = true;
  83443. var factor = maximp / Math.sqrt(impulseSquared);
  83444. wheel.skidInfo *= factor;
  83445. }
  83446. }
  83447. }
  83448. if (this.sliding) {
  83449. for (var i = 0; i < numWheels; i++) {
  83450. var wheel = wheelInfos[i];
  83451. if (wheel.sideImpulse !== 0) {
  83452. if (wheel.skidInfo < 1){
  83453. wheel.forwardImpulse *= wheel.skidInfo;
  83454. wheel.sideImpulse *= wheel.skidInfo;
  83455. }
  83456. }
  83457. }
  83458. }
  83459. // apply the impulses
  83460. for (var i = 0; i < numWheels; i++) {
  83461. var wheel = wheelInfos[i];
  83462. var rel_pos = new Vec3();
  83463. //wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos);
  83464. // cannons applyimpulse is using world coord for the position
  83465. rel_pos.copy(wheel.raycastResult.hitPointWorld);
  83466. if (wheel.forwardImpulse !== 0) {
  83467. var impulse = new Vec3();
  83468. forwardWS[i].scale(wheel.forwardImpulse, impulse);
  83469. chassisBody.applyImpulse(impulse, rel_pos);
  83470. }
  83471. if (wheel.sideImpulse !== 0){
  83472. var groundObject = wheel.raycastResult.body;
  83473. var rel_pos2 = new Vec3();
  83474. //wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2);
  83475. rel_pos2.copy(wheel.raycastResult.hitPointWorld);
  83476. var sideImp = new Vec3();
  83477. axle[i].scale(wheel.sideImpulse, sideImp);
  83478. // Scale the relative position in the up direction with rollInfluence.
  83479. // If rollInfluence is 1, the impulse will be applied on the hitPoint (easy to roll over), if it is zero it will be applied in the same plane as the center of mass (not easy to roll over).
  83480. chassisBody.pointToLocalFrame(rel_pos, rel_pos);
  83481. rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence;
  83482. chassisBody.pointToWorldFrame(rel_pos, rel_pos);
  83483. chassisBody.applyImpulse(sideImp, rel_pos);
  83484. //apply friction impulse on the ground
  83485. sideImp.scale(-1, sideImp);
  83486. groundObject.applyImpulse(sideImp, rel_pos2);
  83487. }
  83488. }
  83489. };
  83490. var calcRollingFriction_vel1 = new Vec3();
  83491. var calcRollingFriction_vel2 = new Vec3();
  83492. var calcRollingFriction_vel = new Vec3();
  83493. function calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) {
  83494. var j1 = 0;
  83495. var contactPosWorld = frictionPosWorld;
  83496. // var rel_pos1 = new Vec3();
  83497. // var rel_pos2 = new Vec3();
  83498. var vel1 = calcRollingFriction_vel1;
  83499. var vel2 = calcRollingFriction_vel2;
  83500. var vel = calcRollingFriction_vel;
  83501. // contactPosWorld.vsub(body0.position, rel_pos1);
  83502. // contactPosWorld.vsub(body1.position, rel_pos2);
  83503. body0.getVelocityAtWorldPoint(contactPosWorld, vel1);
  83504. body1.getVelocityAtWorldPoint(contactPosWorld, vel2);
  83505. vel1.vsub(vel2, vel);
  83506. var vrel = frictionDirectionWorld.dot(vel);
  83507. var denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld);
  83508. var denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld);
  83509. var relaxation = 1;
  83510. var jacDiagABInv = relaxation / (denom0 + denom1);
  83511. // calculate j that moves us to zero relative velocity
  83512. j1 = -vrel * jacDiagABInv;
  83513. if (maxImpulse < j1) {
  83514. j1 = maxImpulse;
  83515. }
  83516. if (j1 < -maxImpulse) {
  83517. j1 = -maxImpulse;
  83518. }
  83519. return j1;
  83520. }
  83521. var computeImpulseDenominator_r0 = new Vec3();
  83522. var computeImpulseDenominator_c0 = new Vec3();
  83523. var computeImpulseDenominator_vec = new Vec3();
  83524. var computeImpulseDenominator_m = new Vec3();
  83525. function computeImpulseDenominator(body, pos, normal) {
  83526. var r0 = computeImpulseDenominator_r0;
  83527. var c0 = computeImpulseDenominator_c0;
  83528. var vec = computeImpulseDenominator_vec;
  83529. var m = computeImpulseDenominator_m;
  83530. pos.vsub(body.position, r0);
  83531. r0.cross(normal, c0);
  83532. body.invInertiaWorld.vmult(c0, m);
  83533. m.cross(r0, vec);
  83534. return body.invMass + normal.dot(vec);
  83535. }
  83536. var resolveSingleBilateral_vel1 = new Vec3();
  83537. var resolveSingleBilateral_vel2 = new Vec3();
  83538. var resolveSingleBilateral_vel = new Vec3();
  83539. //bilateral constraint between two dynamic objects
  83540. function resolveSingleBilateral(body1, pos1, body2, pos2, normal, impulse){
  83541. var normalLenSqr = normal.norm2();
  83542. if (normalLenSqr > 1.1){
  83543. return 0; // no impulse
  83544. }
  83545. // var rel_pos1 = new Vec3();
  83546. // var rel_pos2 = new Vec3();
  83547. // pos1.vsub(body1.position, rel_pos1);
  83548. // pos2.vsub(body2.position, rel_pos2);
  83549. var vel1 = resolveSingleBilateral_vel1;
  83550. var vel2 = resolveSingleBilateral_vel2;
  83551. var vel = resolveSingleBilateral_vel;
  83552. body1.getVelocityAtWorldPoint(pos1, vel1);
  83553. body2.getVelocityAtWorldPoint(pos2, vel2);
  83554. vel1.vsub(vel2, vel);
  83555. var rel_vel = normal.dot(vel);
  83556. var contactDamping = 0.2;
  83557. var massTerm = 1 / (body1.invMass + body2.invMass);
  83558. var impulse = - contactDamping * rel_vel * massTerm;
  83559. return impulse;
  83560. }
  83561. },{"../collision/Ray":9,"../collision/RaycastResult":10,"../math/Quaternion":28,"../math/Vec3":30,"../objects/WheelInfo":36,"./Body":31}],33:[function(_dereq_,module,exports){
  83562. var Body = _dereq_('./Body');
  83563. var Sphere = _dereq_('../shapes/Sphere');
  83564. var Box = _dereq_('../shapes/Box');
  83565. var Vec3 = _dereq_('../math/Vec3');
  83566. var HingeConstraint = _dereq_('../constraints/HingeConstraint');
  83567. module.exports = RigidVehicle;
  83568. /**
  83569. * Simple vehicle helper class with spherical rigid body wheels.
  83570. * @class RigidVehicle
  83571. * @constructor
  83572. * @param {Body} [options.chassisBody]
  83573. */
  83574. function RigidVehicle(options){
  83575. this.wheelBodies = [];
  83576. /**
  83577. * @property coordinateSystem
  83578. * @type {Vec3}
  83579. */
  83580. this.coordinateSystem = typeof(options.coordinateSystem)==='undefined' ? new Vec3(1, 2, 3) : options.coordinateSystem.clone();
  83581. /**
  83582. * @property {Body} chassisBody
  83583. */
  83584. this.chassisBody = options.chassisBody;
  83585. if(!this.chassisBody){
  83586. // No chassis body given. Create it!
  83587. var chassisShape = new Box(new Vec3(5, 2, 0.5));
  83588. this.chassisBody = new Body(1, chassisShape);
  83589. }
  83590. /**
  83591. * @property constraints
  83592. * @type {Array}
  83593. */
  83594. this.constraints = [];
  83595. this.wheelAxes = [];
  83596. this.wheelForces = [];
  83597. }
  83598. /**
  83599. * Add a wheel
  83600. * @method addWheel
  83601. * @param {object} options
  83602. * @param {boolean} [options.isFrontWheel]
  83603. * @param {Vec3} [options.position] Position of the wheel, locally in the chassis body.
  83604. * @param {Vec3} [options.direction] Slide direction of the wheel along the suspension.
  83605. * @param {Vec3} [options.axis] Axis of rotation of the wheel, locally defined in the chassis.
  83606. * @param {Body} [options.body] The wheel body.
  83607. */
  83608. RigidVehicle.prototype.addWheel = function(options){
  83609. options = options || {};
  83610. var wheelBody = options.body;
  83611. if(!wheelBody){
  83612. wheelBody = new Body(1, new Sphere(1.2));
  83613. }
  83614. this.wheelBodies.push(wheelBody);
  83615. this.wheelForces.push(0);
  83616. // Position constrain wheels
  83617. var zero = new Vec3();
  83618. var position = typeof(options.position) !== 'undefined' ? options.position.clone() : new Vec3();
  83619. // Set position locally to the chassis
  83620. var worldPosition = new Vec3();
  83621. this.chassisBody.pointToWorldFrame(position, worldPosition);
  83622. wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z);
  83623. // Constrain wheel
  83624. var axis = typeof(options.axis) !== 'undefined' ? options.axis.clone() : new Vec3(0, 1, 0);
  83625. this.wheelAxes.push(axis);
  83626. var hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, {
  83627. pivotA: position,
  83628. axisA: axis,
  83629. pivotB: Vec3.ZERO,
  83630. axisB: axis,
  83631. collideConnected: false
  83632. });
  83633. this.constraints.push(hingeConstraint);
  83634. return this.wheelBodies.length - 1;
  83635. };
  83636. /**
  83637. * Set the steering value of a wheel.
  83638. * @method setSteeringValue
  83639. * @param {number} value
  83640. * @param {integer} wheelIndex
  83641. * @todo check coordinateSystem
  83642. */
  83643. RigidVehicle.prototype.setSteeringValue = function(value, wheelIndex){
  83644. // Set angle of the hinge axis
  83645. var axis = this.wheelAxes[wheelIndex];
  83646. var c = Math.cos(value),
  83647. s = Math.sin(value),
  83648. x = axis.x,
  83649. y = axis.y;
  83650. this.constraints[wheelIndex].axisA.set(
  83651. c*x -s*y,
  83652. s*x +c*y,
  83653. 0
  83654. );
  83655. };
  83656. /**
  83657. * Set the target rotational speed of the hinge constraint.
  83658. * @method setMotorSpeed
  83659. * @param {number} value
  83660. * @param {integer} wheelIndex
  83661. */
  83662. RigidVehicle.prototype.setMotorSpeed = function(value, wheelIndex){
  83663. var hingeConstraint = this.constraints[wheelIndex];
  83664. hingeConstraint.enableMotor();
  83665. hingeConstraint.motorTargetVelocity = value;
  83666. };
  83667. /**
  83668. * Set the target rotational speed of the hinge constraint.
  83669. * @method disableMotor
  83670. * @param {number} value
  83671. * @param {integer} wheelIndex
  83672. */
  83673. RigidVehicle.prototype.disableMotor = function(wheelIndex){
  83674. var hingeConstraint = this.constraints[wheelIndex];
  83675. hingeConstraint.disableMotor();
  83676. };
  83677. var torque = new Vec3();
  83678. /**
  83679. * Set the wheel force to apply on one of the wheels each time step
  83680. * @method setWheelForce
  83681. * @param {number} value
  83682. * @param {integer} wheelIndex
  83683. */
  83684. RigidVehicle.prototype.setWheelForce = function(value, wheelIndex){
  83685. this.wheelForces[wheelIndex] = value;
  83686. };
  83687. /**
  83688. * Apply a torque on one of the wheels.
  83689. * @method applyWheelForce
  83690. * @param {number} value
  83691. * @param {integer} wheelIndex
  83692. */
  83693. RigidVehicle.prototype.applyWheelForce = function(value, wheelIndex){
  83694. var axis = this.wheelAxes[wheelIndex];
  83695. var wheelBody = this.wheelBodies[wheelIndex];
  83696. var bodyTorque = wheelBody.torque;
  83697. axis.scale(value, torque);
  83698. wheelBody.vectorToWorldFrame(torque, torque);
  83699. bodyTorque.vadd(torque, bodyTorque);
  83700. };
  83701. /**
  83702. * Add the vehicle including its constraints to the world.
  83703. * @method addToWorld
  83704. * @param {World} world
  83705. */
  83706. RigidVehicle.prototype.addToWorld = function(world){
  83707. var constraints = this.constraints;
  83708. var bodies = this.wheelBodies.concat([this.chassisBody]);
  83709. for (var i = 0; i < bodies.length; i++) {
  83710. world.add(bodies[i]);
  83711. }
  83712. for (var i = 0; i < constraints.length; i++) {
  83713. world.addConstraint(constraints[i]);
  83714. }
  83715. world.addEventListener('preStep', this._update.bind(this));
  83716. };
  83717. RigidVehicle.prototype._update = function(){
  83718. var wheelForces = this.wheelForces;
  83719. for (var i = 0; i < wheelForces.length; i++) {
  83720. this.applyWheelForce(wheelForces[i], i);
  83721. }
  83722. };
  83723. /**
  83724. * Remove the vehicle including its constraints from the world.
  83725. * @method removeFromWorld
  83726. * @param {World} world
  83727. */
  83728. RigidVehicle.prototype.removeFromWorld = function(world){
  83729. var constraints = this.constraints;
  83730. var bodies = this.wheelBodies.concat([this.chassisBody]);
  83731. for (var i = 0; i < bodies.length; i++) {
  83732. world.remove(bodies[i]);
  83733. }
  83734. for (var i = 0; i < constraints.length; i++) {
  83735. world.removeConstraint(constraints[i]);
  83736. }
  83737. };
  83738. var worldAxis = new Vec3();
  83739. /**
  83740. * Get current rotational velocity of a wheel
  83741. * @method getWheelSpeed
  83742. * @param {integer} wheelIndex
  83743. */
  83744. RigidVehicle.prototype.getWheelSpeed = function(wheelIndex){
  83745. var axis = this.wheelAxes[wheelIndex];
  83746. var wheelBody = this.wheelBodies[wheelIndex];
  83747. var w = wheelBody.angularVelocity;
  83748. this.chassisBody.vectorToWorldFrame(axis, worldAxis);
  83749. return w.dot(worldAxis);
  83750. };
  83751. },{"../constraints/HingeConstraint":15,"../math/Vec3":30,"../shapes/Box":37,"../shapes/Sphere":44,"./Body":31}],34:[function(_dereq_,module,exports){
  83752. module.exports = SPHSystem;
  83753. var Shape = _dereq_('../shapes/Shape');
  83754. var Vec3 = _dereq_('../math/Vec3');
  83755. var Quaternion = _dereq_('../math/Quaternion');
  83756. var Particle = _dereq_('../shapes/Particle');
  83757. var Body = _dereq_('../objects/Body');
  83758. var Material = _dereq_('../material/Material');
  83759. /**
  83760. * Smoothed-particle hydrodynamics system
  83761. * @class SPHSystem
  83762. * @constructor
  83763. */
  83764. function SPHSystem(){
  83765. this.particles = [];
  83766. /**
  83767. * Density of the system (kg/m3).
  83768. * @property {number} density
  83769. */
  83770. this.density = 1;
  83771. /**
  83772. * Distance below which two particles are considered to be neighbors.
  83773. * It should be adjusted so there are about 15-20 neighbor particles within this radius.
  83774. * @property {number} smoothingRadius
  83775. */
  83776. this.smoothingRadius = 1;
  83777. this.speedOfSound = 1;
  83778. /**
  83779. * Viscosity of the system.
  83780. * @property {number} viscosity
  83781. */
  83782. this.viscosity = 0.01;
  83783. this.eps = 0.000001;
  83784. // Stuff Computed per particle
  83785. this.pressures = [];
  83786. this.densities = [];
  83787. this.neighbors = [];
  83788. }
  83789. /**
  83790. * Add a particle to the system.
  83791. * @method add
  83792. * @param {Body} particle
  83793. */
  83794. SPHSystem.prototype.add = function(particle){
  83795. this.particles.push(particle);
  83796. if(this.neighbors.length < this.particles.length){
  83797. this.neighbors.push([]);
  83798. }
  83799. };
  83800. /**
  83801. * Remove a particle from the system.
  83802. * @method remove
  83803. * @param {Body} particle
  83804. */
  83805. SPHSystem.prototype.remove = function(particle){
  83806. var idx = this.particles.indexOf(particle);
  83807. if(idx !== -1){
  83808. this.particles.splice(idx,1);
  83809. if(this.neighbors.length > this.particles.length){
  83810. this.neighbors.pop();
  83811. }
  83812. }
  83813. };
  83814. /**
  83815. * Get neighbors within smoothing volume, save in the array neighbors
  83816. * @method getNeighbors
  83817. * @param {Body} particle
  83818. * @param {Array} neighbors
  83819. */
  83820. var SPHSystem_getNeighbors_dist = new Vec3();
  83821. SPHSystem.prototype.getNeighbors = function(particle,neighbors){
  83822. var N = this.particles.length,
  83823. id = particle.id,
  83824. R2 = this.smoothingRadius * this.smoothingRadius,
  83825. dist = SPHSystem_getNeighbors_dist;
  83826. for(var i=0; i!==N; i++){
  83827. var p = this.particles[i];
  83828. p.position.vsub(particle.position,dist);
  83829. if(id!==p.id && dist.norm2() < R2){
  83830. neighbors.push(p);
  83831. }
  83832. }
  83833. };
  83834. // Temp vectors for calculation
  83835. var SPHSystem_update_dist = new Vec3(),
  83836. SPHSystem_update_a_pressure = new Vec3(),
  83837. SPHSystem_update_a_visc = new Vec3(),
  83838. SPHSystem_update_gradW = new Vec3(),
  83839. SPHSystem_update_r_vec = new Vec3(),
  83840. SPHSystem_update_u = new Vec3(); // Relative velocity
  83841. SPHSystem.prototype.update = function(){
  83842. var N = this.particles.length,
  83843. dist = SPHSystem_update_dist,
  83844. cs = this.speedOfSound,
  83845. eps = this.eps;
  83846. for(var i=0; i!==N; i++){
  83847. var p = this.particles[i]; // Current particle
  83848. var neighbors = this.neighbors[i];
  83849. // Get neighbors
  83850. neighbors.length = 0;
  83851. this.getNeighbors(p,neighbors);
  83852. neighbors.push(this.particles[i]); // Add current too
  83853. var numNeighbors = neighbors.length;
  83854. // Accumulate density for the particle
  83855. var sum = 0.0;
  83856. for(var j=0; j!==numNeighbors; j++){
  83857. //printf("Current particle has position %f %f %f\n",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z());
  83858. p.position.vsub(neighbors[j].position, dist);
  83859. var len = dist.norm();
  83860. var weight = this.w(len);
  83861. sum += neighbors[j].mass * weight;
  83862. }
  83863. // Save
  83864. this.densities[i] = sum;
  83865. this.pressures[i] = cs * cs * (this.densities[i] - this.density);
  83866. }
  83867. // Add forces
  83868. // Sum to these accelerations
  83869. var a_pressure= SPHSystem_update_a_pressure;
  83870. var a_visc = SPHSystem_update_a_visc;
  83871. var gradW = SPHSystem_update_gradW;
  83872. var r_vec = SPHSystem_update_r_vec;
  83873. var u = SPHSystem_update_u;
  83874. for(var i=0; i!==N; i++){
  83875. var particle = this.particles[i];
  83876. a_pressure.set(0,0,0);
  83877. a_visc.set(0,0,0);
  83878. // Init vars
  83879. var Pij;
  83880. var nabla;
  83881. var Vij;
  83882. // Sum up for all other neighbors
  83883. var neighbors = this.neighbors[i];
  83884. var numNeighbors = neighbors.length;
  83885. //printf("Neighbors: ");
  83886. for(var j=0; j!==numNeighbors; j++){
  83887. var neighbor = neighbors[j];
  83888. //printf("%d ",nj);
  83889. // Get r once for all..
  83890. particle.position.vsub(neighbor.position,r_vec);
  83891. var r = r_vec.norm();
  83892. // Pressure contribution
  83893. Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i]*this.densities[i] + eps) + this.pressures[j] / (this.densities[j]*this.densities[j] + eps));
  83894. this.gradw(r_vec, gradW);
  83895. // Add to pressure acceleration
  83896. gradW.mult(Pij , gradW);
  83897. a_pressure.vadd(gradW, a_pressure);
  83898. // Viscosity contribution
  83899. neighbor.velocity.vsub(particle.velocity, u);
  83900. u.mult( 1.0 / (0.0001+this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass , u );
  83901. nabla = this.nablaw(r);
  83902. u.mult(nabla,u);
  83903. // Add to viscosity acceleration
  83904. a_visc.vadd( u, a_visc );
  83905. }
  83906. // Calculate force
  83907. a_visc.mult(particle.mass, a_visc);
  83908. a_pressure.mult(particle.mass, a_pressure);
  83909. // Add force to particles
  83910. particle.force.vadd(a_visc, particle.force);
  83911. particle.force.vadd(a_pressure, particle.force);
  83912. }
  83913. };
  83914. // Calculate the weight using the W(r) weightfunction
  83915. SPHSystem.prototype.w = function(r){
  83916. // 315
  83917. var h = this.smoothingRadius;
  83918. return 315.0/(64.0*Math.PI*Math.pow(h,9)) * Math.pow(h*h-r*r,3);
  83919. };
  83920. // calculate gradient of the weight function
  83921. SPHSystem.prototype.gradw = function(rVec,resultVec){
  83922. var r = rVec.norm(),
  83923. h = this.smoothingRadius;
  83924. rVec.mult(945.0/(32.0*Math.PI*Math.pow(h,9)) * Math.pow((h*h-r*r),2) , resultVec);
  83925. };
  83926. // Calculate nabla(W)
  83927. SPHSystem.prototype.nablaw = function(r){
  83928. var h = this.smoothingRadius;
  83929. var nabla = 945.0/(32.0*Math.PI*Math.pow(h,9)) * (h*h-r*r)*(7*r*r - 3*h*h);
  83930. return nabla;
  83931. };
  83932. },{"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Particle":41,"../shapes/Shape":43}],35:[function(_dereq_,module,exports){
  83933. var Vec3 = _dereq_('../math/Vec3');
  83934. module.exports = Spring;
  83935. /**
  83936. * A spring, connecting two bodies.
  83937. *
  83938. * @class Spring
  83939. * @constructor
  83940. * @param {Body} bodyA
  83941. * @param {Body} bodyB
  83942. * @param {Object} [options]
  83943. * @param {number} [options.restLength] A number > 0. Default: 1
  83944. * @param {number} [options.stiffness] A number >= 0. Default: 100
  83945. * @param {number} [options.damping] A number >= 0. Default: 1
  83946. * @param {Vec3} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates.
  83947. * @param {Vec3} [options.worldAnchorB]
  83948. * @param {Vec3} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates.
  83949. * @param {Vec3} [options.localAnchorB]
  83950. */
  83951. function Spring(bodyA,bodyB,options){
  83952. options = options || {};
  83953. /**
  83954. * Rest length of the spring.
  83955. * @property restLength
  83956. * @type {number}
  83957. */
  83958. this.restLength = typeof(options.restLength) === "number" ? options.restLength : 1;
  83959. /**
  83960. * Stiffness of the spring.
  83961. * @property stiffness
  83962. * @type {number}
  83963. */
  83964. this.stiffness = options.stiffness || 100;
  83965. /**
  83966. * Damping of the spring.
  83967. * @property damping
  83968. * @type {number}
  83969. */
  83970. this.damping = options.damping || 1;
  83971. /**
  83972. * First connected body.
  83973. * @property bodyA
  83974. * @type {Body}
  83975. */
  83976. this.bodyA = bodyA;
  83977. /**
  83978. * Second connected body.
  83979. * @property bodyB
  83980. * @type {Body}
  83981. */
  83982. this.bodyB = bodyB;
  83983. /**
  83984. * Anchor for bodyA in local bodyA coordinates.
  83985. * @property localAnchorA
  83986. * @type {Vec3}
  83987. */
  83988. this.localAnchorA = new Vec3();
  83989. /**
  83990. * Anchor for bodyB in local bodyB coordinates.
  83991. * @property localAnchorB
  83992. * @type {Vec3}
  83993. */
  83994. this.localAnchorB = new Vec3();
  83995. if(options.localAnchorA){
  83996. this.localAnchorA.copy(options.localAnchorA);
  83997. }
  83998. if(options.localAnchorB){
  83999. this.localAnchorB.copy(options.localAnchorB);
  84000. }
  84001. if(options.worldAnchorA){
  84002. this.setWorldAnchorA(options.worldAnchorA);
  84003. }
  84004. if(options.worldAnchorB){
  84005. this.setWorldAnchorB(options.worldAnchorB);
  84006. }
  84007. }
  84008. /**
  84009. * Set the anchor point on body A, using world coordinates.
  84010. * @method setWorldAnchorA
  84011. * @param {Vec3} worldAnchorA
  84012. */
  84013. Spring.prototype.setWorldAnchorA = function(worldAnchorA){
  84014. this.bodyA.pointToLocalFrame(worldAnchorA,this.localAnchorA);
  84015. };
  84016. /**
  84017. * Set the anchor point on body B, using world coordinates.
  84018. * @method setWorldAnchorB
  84019. * @param {Vec3} worldAnchorB
  84020. */
  84021. Spring.prototype.setWorldAnchorB = function(worldAnchorB){
  84022. this.bodyB.pointToLocalFrame(worldAnchorB,this.localAnchorB);
  84023. };
  84024. /**
  84025. * Get the anchor point on body A, in world coordinates.
  84026. * @method getWorldAnchorA
  84027. * @param {Vec3} result The vector to store the result in.
  84028. */
  84029. Spring.prototype.getWorldAnchorA = function(result){
  84030. this.bodyA.pointToWorldFrame(this.localAnchorA,result);
  84031. };
  84032. /**
  84033. * Get the anchor point on body B, in world coordinates.
  84034. * @method getWorldAnchorB
  84035. * @param {Vec3} result The vector to store the result in.
  84036. */
  84037. Spring.prototype.getWorldAnchorB = function(result){
  84038. this.bodyB.pointToWorldFrame(this.localAnchorB,result);
  84039. };
  84040. var applyForce_r = new Vec3(),
  84041. applyForce_r_unit = new Vec3(),
  84042. applyForce_u = new Vec3(),
  84043. applyForce_f = new Vec3(),
  84044. applyForce_worldAnchorA = new Vec3(),
  84045. applyForce_worldAnchorB = new Vec3(),
  84046. applyForce_ri = new Vec3(),
  84047. applyForce_rj = new Vec3(),
  84048. applyForce_ri_x_f = new Vec3(),
  84049. applyForce_rj_x_f = new Vec3(),
  84050. applyForce_tmp = new Vec3();
  84051. /**
  84052. * Apply the spring force to the connected bodies.
  84053. * @method applyForce
  84054. */
  84055. Spring.prototype.applyForce = function(){
  84056. var k = this.stiffness,
  84057. d = this.damping,
  84058. l = this.restLength,
  84059. bodyA = this.bodyA,
  84060. bodyB = this.bodyB,
  84061. r = applyForce_r,
  84062. r_unit = applyForce_r_unit,
  84063. u = applyForce_u,
  84064. f = applyForce_f,
  84065. tmp = applyForce_tmp;
  84066. var worldAnchorA = applyForce_worldAnchorA,
  84067. worldAnchorB = applyForce_worldAnchorB,
  84068. ri = applyForce_ri,
  84069. rj = applyForce_rj,
  84070. ri_x_f = applyForce_ri_x_f,
  84071. rj_x_f = applyForce_rj_x_f;
  84072. // Get world anchors
  84073. this.getWorldAnchorA(worldAnchorA);
  84074. this.getWorldAnchorB(worldAnchorB);
  84075. // Get offset points
  84076. worldAnchorA.vsub(bodyA.position,ri);
  84077. worldAnchorB.vsub(bodyB.position,rj);
  84078. // Compute distance vector between world anchor points
  84079. worldAnchorB.vsub(worldAnchorA,r);
  84080. var rlen = r.norm();
  84081. r_unit.copy(r);
  84082. r_unit.normalize();
  84083. // Compute relative velocity of the anchor points, u
  84084. bodyB.velocity.vsub(bodyA.velocity,u);
  84085. // Add rotational velocity
  84086. bodyB.angularVelocity.cross(rj,tmp);
  84087. u.vadd(tmp,u);
  84088. bodyA.angularVelocity.cross(ri,tmp);
  84089. u.vsub(tmp,u);
  84090. // F = - k * ( x - L ) - D * ( u )
  84091. r_unit.mult(-k*(rlen-l) - d*u.dot(r_unit), f);
  84092. // Add forces to bodies
  84093. bodyA.force.vsub(f,bodyA.force);
  84094. bodyB.force.vadd(f,bodyB.force);
  84095. // Angular force
  84096. ri.cross(f,ri_x_f);
  84097. rj.cross(f,rj_x_f);
  84098. bodyA.torque.vsub(ri_x_f,bodyA.torque);
  84099. bodyB.torque.vadd(rj_x_f,bodyB.torque);
  84100. };
  84101. },{"../math/Vec3":30}],36:[function(_dereq_,module,exports){
  84102. var Vec3 = _dereq_('../math/Vec3');
  84103. var Transform = _dereq_('../math/Transform');
  84104. var RaycastResult = _dereq_('../collision/RaycastResult');
  84105. var Utils = _dereq_('../utils/Utils');
  84106. module.exports = WheelInfo;
  84107. /**
  84108. * @class WheelInfo
  84109. * @constructor
  84110. * @param {Object} [options]
  84111. *
  84112. * @param {Vec3} [options.chassisConnectionPointLocal]
  84113. * @param {Vec3} [options.chassisConnectionPointWorld]
  84114. * @param {Vec3} [options.directionLocal]
  84115. * @param {Vec3} [options.directionWorld]
  84116. * @param {Vec3} [options.axleLocal]
  84117. * @param {Vec3} [options.axleWorld]
  84118. * @param {number} [options.suspensionRestLength=1]
  84119. * @param {number} [options.suspensionMaxLength=2]
  84120. * @param {number} [options.radius=1]
  84121. * @param {number} [options.suspensionStiffness=100]
  84122. * @param {number} [options.dampingCompression=10]
  84123. * @param {number} [options.dampingRelaxation=10]
  84124. * @param {number} [options.frictionSlip=10000]
  84125. * @param {number} [options.steering=0]
  84126. * @param {number} [options.rotation=0]
  84127. * @param {number} [options.deltaRotation=0]
  84128. * @param {number} [options.rollInfluence=0.01]
  84129. * @param {number} [options.maxSuspensionForce]
  84130. * @param {boolean} [options.isFrontWheel=true]
  84131. * @param {number} [options.clippedInvContactDotSuspension=1]
  84132. * @param {number} [options.suspensionRelativeVelocity=0]
  84133. * @param {number} [options.suspensionForce=0]
  84134. * @param {number} [options.skidInfo=0]
  84135. * @param {number} [options.suspensionLength=0]
  84136. * @param {number} [options.maxSuspensionTravel=1]
  84137. * @param {boolean} [options.useCustomSlidingRotationalSpeed=false]
  84138. * @param {number} [options.customSlidingRotationalSpeed=-0.1]
  84139. */
  84140. function WheelInfo(options){
  84141. options = Utils.defaults(options, {
  84142. chassisConnectionPointLocal: new Vec3(),
  84143. chassisConnectionPointWorld: new Vec3(),
  84144. directionLocal: new Vec3(),
  84145. directionWorld: new Vec3(),
  84146. axleLocal: new Vec3(),
  84147. axleWorld: new Vec3(),
  84148. suspensionRestLength: 1,
  84149. suspensionMaxLength: 2,
  84150. radius: 1,
  84151. suspensionStiffness: 100,
  84152. dampingCompression: 10,
  84153. dampingRelaxation: 10,
  84154. frictionSlip: 10000,
  84155. steering: 0,
  84156. rotation: 0,
  84157. deltaRotation: 0,
  84158. rollInfluence: 0.01,
  84159. maxSuspensionForce: Number.MAX_VALUE,
  84160. isFrontWheel: true,
  84161. clippedInvContactDotSuspension: 1,
  84162. suspensionRelativeVelocity: 0,
  84163. suspensionForce: 0,
  84164. skidInfo: 0,
  84165. suspensionLength: 0,
  84166. maxSuspensionTravel: 1,
  84167. useCustomSlidingRotationalSpeed: false,
  84168. customSlidingRotationalSpeed: -0.1
  84169. });
  84170. /**
  84171. * Max travel distance of the suspension, in meters.
  84172. * @property {number} maxSuspensionTravel
  84173. */
  84174. this.maxSuspensionTravel = options.maxSuspensionTravel;
  84175. /**
  84176. * Speed to apply to the wheel rotation when the wheel is sliding.
  84177. * @property {number} customSlidingRotationalSpeed
  84178. */
  84179. this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed;
  84180. /**
  84181. * If the customSlidingRotationalSpeed should be used.
  84182. * @property {Boolean} useCustomSlidingRotationalSpeed
  84183. */
  84184. this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed;
  84185. /**
  84186. * @property {Boolean} sliding
  84187. */
  84188. this.sliding = false;
  84189. /**
  84190. * Connection point, defined locally in the chassis body frame.
  84191. * @property {Vec3} chassisConnectionPointLocal
  84192. */
  84193. this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone();
  84194. /**
  84195. * @property {Vec3} chassisConnectionPointWorld
  84196. */
  84197. this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone();
  84198. /**
  84199. * @property {Vec3} directionLocal
  84200. */
  84201. this.directionLocal = options.directionLocal.clone();
  84202. /**
  84203. * @property {Vec3} directionWorld
  84204. */
  84205. this.directionWorld = options.directionWorld.clone();
  84206. /**
  84207. * @property {Vec3} axleLocal
  84208. */
  84209. this.axleLocal = options.axleLocal.clone();
  84210. /**
  84211. * @property {Vec3} axleWorld
  84212. */
  84213. this.axleWorld = options.axleWorld.clone();
  84214. /**
  84215. * @property {number} suspensionRestLength
  84216. */
  84217. this.suspensionRestLength = options.suspensionRestLength;
  84218. /**
  84219. * @property {number} suspensionMaxLength
  84220. */
  84221. this.suspensionMaxLength = options.suspensionMaxLength;
  84222. /**
  84223. * @property {number} radius
  84224. */
  84225. this.radius = options.radius;
  84226. /**
  84227. * @property {number} suspensionStiffness
  84228. */
  84229. this.suspensionStiffness = options.suspensionStiffness;
  84230. /**
  84231. * @property {number} dampingCompression
  84232. */
  84233. this.dampingCompression = options.dampingCompression;
  84234. /**
  84235. * @property {number} dampingRelaxation
  84236. */
  84237. this.dampingRelaxation = options.dampingRelaxation;
  84238. /**
  84239. * @property {number} frictionSlip
  84240. */
  84241. this.frictionSlip = options.frictionSlip;
  84242. /**
  84243. * @property {number} steering
  84244. */
  84245. this.steering = 0;
  84246. /**
  84247. * Rotation value, in radians.
  84248. * @property {number} rotation
  84249. */
  84250. this.rotation = 0;
  84251. /**
  84252. * @property {number} deltaRotation
  84253. */
  84254. this.deltaRotation = 0;
  84255. /**
  84256. * @property {number} rollInfluence
  84257. */
  84258. this.rollInfluence = options.rollInfluence;
  84259. /**
  84260. * @property {number} maxSuspensionForce
  84261. */
  84262. this.maxSuspensionForce = options.maxSuspensionForce;
  84263. /**
  84264. * @property {number} engineForce
  84265. */
  84266. this.engineForce = 0;
  84267. /**
  84268. * @property {number} brake
  84269. */
  84270. this.brake = 0;
  84271. /**
  84272. * @property {number} isFrontWheel
  84273. */
  84274. this.isFrontWheel = options.isFrontWheel;
  84275. /**
  84276. * @property {number} clippedInvContactDotSuspension
  84277. */
  84278. this.clippedInvContactDotSuspension = 1;
  84279. /**
  84280. * @property {number} suspensionRelativeVelocity
  84281. */
  84282. this.suspensionRelativeVelocity = 0;
  84283. /**
  84284. * @property {number} suspensionForce
  84285. */
  84286. this.suspensionForce = 0;
  84287. /**
  84288. * @property {number} skidInfo
  84289. */
  84290. this.skidInfo = 0;
  84291. /**
  84292. * @property {number} suspensionLength
  84293. */
  84294. this.suspensionLength = 0;
  84295. /**
  84296. * @property {number} sideImpulse
  84297. */
  84298. this.sideImpulse = 0;
  84299. /**
  84300. * @property {number} forwardImpulse
  84301. */
  84302. this.forwardImpulse = 0;
  84303. /**
  84304. * The result from raycasting
  84305. * @property {RaycastResult} raycastResult
  84306. */
  84307. this.raycastResult = new RaycastResult();
  84308. /**
  84309. * Wheel world transform
  84310. * @property {Transform} worldTransform
  84311. */
  84312. this.worldTransform = new Transform();
  84313. /**
  84314. * @property {boolean} isInContact
  84315. */
  84316. this.isInContact = false;
  84317. }
  84318. var chassis_velocity_at_contactPoint = new Vec3();
  84319. var relpos = new Vec3();
  84320. var chassis_velocity_at_contactPoint = new Vec3();
  84321. WheelInfo.prototype.updateWheel = function(chassis){
  84322. var raycastResult = this.raycastResult;
  84323. if (this.isInContact){
  84324. var project= raycastResult.hitNormalWorld.dot(raycastResult.directionWorld);
  84325. raycastResult.hitPointWorld.vsub(chassis.position, relpos);
  84326. chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint);
  84327. var projVel = raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint );
  84328. if (project >= -0.1) {
  84329. this.suspensionRelativeVelocity = 0.0;
  84330. this.clippedInvContactDotSuspension = 1.0 / 0.1;
  84331. } else {
  84332. var inv = -1 / project;
  84333. this.suspensionRelativeVelocity = projVel * inv;
  84334. this.clippedInvContactDotSuspension = inv;
  84335. }
  84336. } else {
  84337. // Not in contact : position wheel in a nice (rest length) position
  84338. raycastResult.suspensionLength = this.suspensionRestLength;
  84339. this.suspensionRelativeVelocity = 0.0;
  84340. raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld);
  84341. this.clippedInvContactDotSuspension = 1.0;
  84342. }
  84343. };
  84344. },{"../collision/RaycastResult":10,"../math/Transform":29,"../math/Vec3":30,"../utils/Utils":53}],37:[function(_dereq_,module,exports){
  84345. module.exports = Box;
  84346. var Shape = _dereq_('./Shape');
  84347. var Vec3 = _dereq_('../math/Vec3');
  84348. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  84349. /**
  84350. * A 3d box shape.
  84351. * @class Box
  84352. * @constructor
  84353. * @param {Vec3} halfExtents
  84354. * @author schteppe
  84355. * @extends Shape
  84356. */
  84357. function Box(halfExtents){
  84358. Shape.call(this);
  84359. this.type = Shape.types.BOX;
  84360. /**
  84361. * @property halfExtents
  84362. * @type {Vec3}
  84363. */
  84364. this.halfExtents = halfExtents;
  84365. /**
  84366. * Used by the contact generator to make contacts with other convex polyhedra for example
  84367. * @property convexPolyhedronRepresentation
  84368. * @type {ConvexPolyhedron}
  84369. */
  84370. this.convexPolyhedronRepresentation = null;
  84371. this.updateConvexPolyhedronRepresentation();
  84372. this.updateBoundingSphereRadius();
  84373. }
  84374. Box.prototype = new Shape();
  84375. Box.prototype.constructor = Box;
  84376. /**
  84377. * Updates the local convex polyhedron representation used for some collisions.
  84378. * @method updateConvexPolyhedronRepresentation
  84379. */
  84380. Box.prototype.updateConvexPolyhedronRepresentation = function(){
  84381. var sx = this.halfExtents.x;
  84382. var sy = this.halfExtents.y;
  84383. var sz = this.halfExtents.z;
  84384. var V = Vec3;
  84385. var vertices = [
  84386. new V(-sx,-sy,-sz),
  84387. new V( sx,-sy,-sz),
  84388. new V( sx, sy,-sz),
  84389. new V(-sx, sy,-sz),
  84390. new V(-sx,-sy, sz),
  84391. new V( sx,-sy, sz),
  84392. new V( sx, sy, sz),
  84393. new V(-sx, sy, sz)
  84394. ];
  84395. var indices = [
  84396. [3,2,1,0], // -z
  84397. [4,5,6,7], // +z
  84398. [5,4,0,1], // -y
  84399. [2,3,7,6], // +y
  84400. [0,4,7,3], // -x
  84401. [1,2,6,5], // +x
  84402. ];
  84403. var axes = [
  84404. new V(0, 0, 1),
  84405. new V(0, 1, 0),
  84406. new V(1, 0, 0)
  84407. ];
  84408. var h = new ConvexPolyhedron(vertices, indices);
  84409. this.convexPolyhedronRepresentation = h;
  84410. h.material = this.material;
  84411. };
  84412. /**
  84413. * @method calculateLocalInertia
  84414. * @param {Number} mass
  84415. * @param {Vec3} target
  84416. * @return {Vec3}
  84417. */
  84418. Box.prototype.calculateLocalInertia = function(mass,target){
  84419. target = target || new Vec3();
  84420. Box.calculateInertia(this.halfExtents, mass, target);
  84421. return target;
  84422. };
  84423. Box.calculateInertia = function(halfExtents,mass,target){
  84424. var e = halfExtents;
  84425. target.x = 1.0 / 12.0 * mass * ( 2*e.y*2*e.y + 2*e.z*2*e.z );
  84426. target.y = 1.0 / 12.0 * mass * ( 2*e.x*2*e.x + 2*e.z*2*e.z );
  84427. target.z = 1.0 / 12.0 * mass * ( 2*e.y*2*e.y + 2*e.x*2*e.x );
  84428. };
  84429. /**
  84430. * Get the box 6 side normals
  84431. * @method getSideNormals
  84432. * @param {array} sixTargetVectors An array of 6 vectors, to store the resulting side normals in.
  84433. * @param {Quaternion} quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame.
  84434. * @return {array}
  84435. */
  84436. Box.prototype.getSideNormals = function(sixTargetVectors,quat){
  84437. var sides = sixTargetVectors;
  84438. var ex = this.halfExtents;
  84439. sides[0].set( ex.x, 0, 0);
  84440. sides[1].set( 0, ex.y, 0);
  84441. sides[2].set( 0, 0, ex.z);
  84442. sides[3].set( -ex.x, 0, 0);
  84443. sides[4].set( 0, -ex.y, 0);
  84444. sides[5].set( 0, 0, -ex.z);
  84445. if(quat!==undefined){
  84446. for(var i=0; i!==sides.length; i++){
  84447. quat.vmult(sides[i],sides[i]);
  84448. }
  84449. }
  84450. return sides;
  84451. };
  84452. Box.prototype.volume = function(){
  84453. return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z;
  84454. };
  84455. Box.prototype.updateBoundingSphereRadius = function(){
  84456. this.boundingSphereRadius = this.halfExtents.norm();
  84457. };
  84458. var worldCornerTempPos = new Vec3();
  84459. var worldCornerTempNeg = new Vec3();
  84460. Box.prototype.forEachWorldCorner = function(pos,quat,callback){
  84461. var e = this.halfExtents;
  84462. var corners = [[ e.x, e.y, e.z],
  84463. [ -e.x, e.y, e.z],
  84464. [ -e.x, -e.y, e.z],
  84465. [ -e.x, -e.y, -e.z],
  84466. [ e.x, -e.y, -e.z],
  84467. [ e.x, e.y, -e.z],
  84468. [ -e.x, e.y, -e.z],
  84469. [ e.x, -e.y, e.z]];
  84470. for(var i=0; i<corners.length; i++){
  84471. worldCornerTempPos.set(corners[i][0],corners[i][1],corners[i][2]);
  84472. quat.vmult(worldCornerTempPos,worldCornerTempPos);
  84473. pos.vadd(worldCornerTempPos,worldCornerTempPos);
  84474. callback(worldCornerTempPos.x,
  84475. worldCornerTempPos.y,
  84476. worldCornerTempPos.z);
  84477. }
  84478. };
  84479. var worldCornersTemp = [
  84480. new Vec3(),
  84481. new Vec3(),
  84482. new Vec3(),
  84483. new Vec3(),
  84484. new Vec3(),
  84485. new Vec3(),
  84486. new Vec3(),
  84487. new Vec3()
  84488. ];
  84489. Box.prototype.calculateWorldAABB = function(pos,quat,min,max){
  84490. var e = this.halfExtents;
  84491. worldCornersTemp[0].set(e.x, e.y, e.z);
  84492. worldCornersTemp[1].set(-e.x, e.y, e.z);
  84493. worldCornersTemp[2].set(-e.x, -e.y, e.z);
  84494. worldCornersTemp[3].set(-e.x, -e.y, -e.z);
  84495. worldCornersTemp[4].set(e.x, -e.y, -e.z);
  84496. worldCornersTemp[5].set(e.x, e.y, -e.z);
  84497. worldCornersTemp[6].set(-e.x, e.y, -e.z);
  84498. worldCornersTemp[7].set(e.x, -e.y, e.z);
  84499. var wc = worldCornersTemp[0];
  84500. quat.vmult(wc, wc);
  84501. pos.vadd(wc, wc);
  84502. max.copy(wc);
  84503. min.copy(wc);
  84504. for(var i=1; i<8; i++){
  84505. var wc = worldCornersTemp[i];
  84506. quat.vmult(wc, wc);
  84507. pos.vadd(wc, wc);
  84508. var x = wc.x;
  84509. var y = wc.y;
  84510. var z = wc.z;
  84511. if(x > max.x){
  84512. max.x = x;
  84513. }
  84514. if(y > max.y){
  84515. max.y = y;
  84516. }
  84517. if(z > max.z){
  84518. max.z = z;
  84519. }
  84520. if(x < min.x){
  84521. min.x = x;
  84522. }
  84523. if(y < min.y){
  84524. min.y = y;
  84525. }
  84526. if(z < min.z){
  84527. min.z = z;
  84528. }
  84529. }
  84530. // Get each axis max
  84531. // min.set(Infinity,Infinity,Infinity);
  84532. // max.set(-Infinity,-Infinity,-Infinity);
  84533. // this.forEachWorldCorner(pos,quat,function(x,y,z){
  84534. // if(x > max.x){
  84535. // max.x = x;
  84536. // }
  84537. // if(y > max.y){
  84538. // max.y = y;
  84539. // }
  84540. // if(z > max.z){
  84541. // max.z = z;
  84542. // }
  84543. // if(x < min.x){
  84544. // min.x = x;
  84545. // }
  84546. // if(y < min.y){
  84547. // min.y = y;
  84548. // }
  84549. // if(z < min.z){
  84550. // min.z = z;
  84551. // }
  84552. // });
  84553. };
  84554. },{"../math/Vec3":30,"./ConvexPolyhedron":38,"./Shape":43}],38:[function(_dereq_,module,exports){
  84555. module.exports = ConvexPolyhedron;
  84556. var Shape = _dereq_('./Shape');
  84557. var Vec3 = _dereq_('../math/Vec3');
  84558. var Quaternion = _dereq_('../math/Quaternion');
  84559. var Transform = _dereq_('../math/Transform');
  84560. /**
  84561. * A set of polygons describing a convex shape.
  84562. * @class ConvexPolyhedron
  84563. * @constructor
  84564. * @extends Shape
  84565. * @description The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained
  84566. * in the same 3D plane), instead these should be merged into one polygon.
  84567. *
  84568. * @param {array} points An array of Vec3's
  84569. * @param {array} faces Array of integer arrays, describing which vertices that is included in each face.
  84570. *
  84571. * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f)
  84572. * @author schteppe / https://github.com/schteppe
  84573. * @see http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/
  84574. * @see http://bullet.googlecode.com/svn/trunk/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp
  84575. *
  84576. * @todo Move the clipping functions to ContactGenerator?
  84577. * @todo Automatically merge coplanar polygons in constructor.
  84578. */
  84579. function ConvexPolyhedron(points, faces, uniqueAxes) {
  84580. var that = this;
  84581. Shape.call(this);
  84582. this.type = Shape.types.CONVEXPOLYHEDRON;
  84583. /**
  84584. * Array of Vec3
  84585. * @property vertices
  84586. * @type {Array}
  84587. */
  84588. this.vertices = points||[];
  84589. this.worldVertices = []; // World transformed version of .vertices
  84590. this.worldVerticesNeedsUpdate = true;
  84591. /**
  84592. * Array of integer arrays, indicating which vertices each face consists of
  84593. * @property faces
  84594. * @type {Array}
  84595. */
  84596. this.faces = faces||[];
  84597. /**
  84598. * Array of Vec3
  84599. * @property faceNormals
  84600. * @type {Array}
  84601. */
  84602. this.faceNormals = [];
  84603. this.computeNormals();
  84604. this.worldFaceNormalsNeedsUpdate = true;
  84605. this.worldFaceNormals = []; // World transformed version of .faceNormals
  84606. /**
  84607. * Array of Vec3
  84608. * @property uniqueEdges
  84609. * @type {Array}
  84610. */
  84611. this.uniqueEdges = [];
  84612. /**
  84613. * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check.
  84614. * @property {Array} uniqueAxes
  84615. */
  84616. this.uniqueAxes = uniqueAxes ? uniqueAxes.slice() : null;
  84617. this.computeEdges();
  84618. this.updateBoundingSphereRadius();
  84619. }
  84620. ConvexPolyhedron.prototype = new Shape();
  84621. ConvexPolyhedron.prototype.constructor = ConvexPolyhedron;
  84622. var computeEdges_tmpEdge = new Vec3();
  84623. /**
  84624. * Computes uniqueEdges
  84625. * @method computeEdges
  84626. */
  84627. ConvexPolyhedron.prototype.computeEdges = function(){
  84628. var faces = this.faces;
  84629. var vertices = this.vertices;
  84630. var nv = vertices.length;
  84631. var edges = this.uniqueEdges;
  84632. edges.length = 0;
  84633. var edge = computeEdges_tmpEdge;
  84634. for(var i=0; i !== faces.length; i++){
  84635. var face = faces[i];
  84636. var numVertices = face.length;
  84637. for(var j = 0; j !== numVertices; j++){
  84638. var k = ( j+1 ) % numVertices;
  84639. vertices[face[j]].vsub(vertices[face[k]], edge);
  84640. edge.normalize();
  84641. var found = false;
  84642. for(var p=0; p !== edges.length; p++){
  84643. if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)){
  84644. found = true;
  84645. break;
  84646. }
  84647. }
  84648. if (!found){
  84649. edges.push(edge.clone());
  84650. }
  84651. }
  84652. }
  84653. };
  84654. /**
  84655. * Compute the normals of the faces. Will reuse existing Vec3 objects in the .faceNormals array if they exist.
  84656. * @method computeNormals
  84657. */
  84658. ConvexPolyhedron.prototype.computeNormals = function(){
  84659. this.faceNormals.length = this.faces.length;
  84660. // Generate normals
  84661. for(var i=0; i<this.faces.length; i++){
  84662. // Check so all vertices exists for this face
  84663. for(var j=0; j<this.faces[i].length; j++){
  84664. if(!this.vertices[this.faces[i][j]]){
  84665. throw new Error("Vertex "+this.faces[i][j]+" not found!");
  84666. }
  84667. }
  84668. var n = this.faceNormals[i] || new Vec3();
  84669. this.getFaceNormal(i,n);
  84670. n.negate(n);
  84671. this.faceNormals[i] = n;
  84672. var vertex = this.vertices[this.faces[i][0]];
  84673. if(n.dot(vertex) < 0){
  84674. console.error(".faceNormals[" + i + "] = Vec3("+n.toString()+") looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.");
  84675. for(var j=0; j<this.faces[i].length; j++){
  84676. console.warn(".vertices["+this.faces[i][j]+"] = Vec3("+this.vertices[this.faces[i][j]].toString()+")");
  84677. }
  84678. }
  84679. }
  84680. };
  84681. /**
  84682. * Get face normal given 3 vertices
  84683. * @static
  84684. * @method getFaceNormal
  84685. * @param {Vec3} va
  84686. * @param {Vec3} vb
  84687. * @param {Vec3} vc
  84688. * @param {Vec3} target
  84689. */
  84690. var cb = new Vec3();
  84691. var ab = new Vec3();
  84692. ConvexPolyhedron.computeNormal = function ( va, vb, vc, target ) {
  84693. vb.vsub(va,ab);
  84694. vc.vsub(vb,cb);
  84695. cb.cross(ab,target);
  84696. if ( !target.isZero() ) {
  84697. target.normalize();
  84698. }
  84699. };
  84700. /**
  84701. * Compute the normal of a face from its vertices
  84702. * @method getFaceNormal
  84703. * @param {Number} i
  84704. * @param {Vec3} target
  84705. */
  84706. ConvexPolyhedron.prototype.getFaceNormal = function(i,target){
  84707. var f = this.faces[i];
  84708. var va = this.vertices[f[0]];
  84709. var vb = this.vertices[f[1]];
  84710. var vc = this.vertices[f[2]];
  84711. return ConvexPolyhedron.computeNormal(va,vb,vc,target);
  84712. };
  84713. /**
  84714. * @method clipAgainstHull
  84715. * @param {Vec3} posA
  84716. * @param {Quaternion} quatA
  84717. * @param {ConvexPolyhedron} hullB
  84718. * @param {Vec3} posB
  84719. * @param {Quaternion} quatB
  84720. * @param {Vec3} separatingNormal
  84721. * @param {Number} minDist Clamp distance
  84722. * @param {Number} maxDist
  84723. * @param {array} result The an array of contact point objects, see clipFaceAgainstHull
  84724. * @see http://bullet.googlecode.com/svn/trunk/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp
  84725. */
  84726. var cah_WorldNormal = new Vec3();
  84727. ConvexPolyhedron.prototype.clipAgainstHull = function(posA,quatA,hullB,posB,quatB,separatingNormal,minDist,maxDist,result){
  84728. var WorldNormal = cah_WorldNormal;
  84729. var hullA = this;
  84730. var curMaxDist = maxDist;
  84731. var closestFaceB = -1;
  84732. var dmax = -Number.MAX_VALUE;
  84733. for(var face=0; face < hullB.faces.length; face++){
  84734. WorldNormal.copy(hullB.faceNormals[face]);
  84735. quatB.vmult(WorldNormal,WorldNormal);
  84736. //posB.vadd(WorldNormal,WorldNormal);
  84737. var d = WorldNormal.dot(separatingNormal);
  84738. if (d > dmax){
  84739. dmax = d;
  84740. closestFaceB = face;
  84741. }
  84742. }
  84743. var worldVertsB1 = [];
  84744. var polyB = hullB.faces[closestFaceB];
  84745. var numVertices = polyB.length;
  84746. for(var e0=0; e0<numVertices; e0++){
  84747. var b = hullB.vertices[polyB[e0]];
  84748. var worldb = new Vec3();
  84749. worldb.copy(b);
  84750. quatB.vmult(worldb,worldb);
  84751. posB.vadd(worldb,worldb);
  84752. worldVertsB1.push(worldb);
  84753. }
  84754. if (closestFaceB>=0){
  84755. this.clipFaceAgainstHull(separatingNormal,
  84756. posA,
  84757. quatA,
  84758. worldVertsB1,
  84759. minDist,
  84760. maxDist,
  84761. result);
  84762. }
  84763. };
  84764. /**
  84765. * Find the separating axis between this hull and another
  84766. * @method findSeparatingAxis
  84767. * @param {ConvexPolyhedron} hullB
  84768. * @param {Vec3} posA
  84769. * @param {Quaternion} quatA
  84770. * @param {Vec3} posB
  84771. * @param {Quaternion} quatB
  84772. * @param {Vec3} target The target vector to save the axis in
  84773. * @return {bool} Returns false if a separation is found, else true
  84774. */
  84775. var fsa_faceANormalWS3 = new Vec3(),
  84776. fsa_Worldnormal1 = new Vec3(),
  84777. fsa_deltaC = new Vec3(),
  84778. fsa_worldEdge0 = new Vec3(),
  84779. fsa_worldEdge1 = new Vec3(),
  84780. fsa_Cross = new Vec3();
  84781. ConvexPolyhedron.prototype.findSeparatingAxis = function(hullB,posA,quatA,posB,quatB,target, faceListA, faceListB){
  84782. var faceANormalWS3 = fsa_faceANormalWS3,
  84783. Worldnormal1 = fsa_Worldnormal1,
  84784. deltaC = fsa_deltaC,
  84785. worldEdge0 = fsa_worldEdge0,
  84786. worldEdge1 = fsa_worldEdge1,
  84787. Cross = fsa_Cross;
  84788. var dmin = Number.MAX_VALUE;
  84789. var hullA = this;
  84790. var curPlaneTests=0;
  84791. if(!hullA.uniqueAxes){
  84792. var numFacesA = faceListA ? faceListA.length : hullA.faces.length;
  84793. // Test face normals from hullA
  84794. for(var i=0; i<numFacesA; i++){
  84795. var fi = faceListA ? faceListA[i] : i;
  84796. // Get world face normal
  84797. faceANormalWS3.copy(hullA.faceNormals[fi]);
  84798. quatA.vmult(faceANormalWS3,faceANormalWS3);
  84799. var d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  84800. if(d===false){
  84801. return false;
  84802. }
  84803. if(d<dmin){
  84804. dmin = d;
  84805. target.copy(faceANormalWS3);
  84806. }
  84807. }
  84808. } else {
  84809. // Test unique axes
  84810. for(var i = 0; i !== hullA.uniqueAxes.length; i++){
  84811. // Get world axis
  84812. quatA.vmult(hullA.uniqueAxes[i],faceANormalWS3);
  84813. var d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  84814. if(d===false){
  84815. return false;
  84816. }
  84817. if(d<dmin){
  84818. dmin = d;
  84819. target.copy(faceANormalWS3);
  84820. }
  84821. }
  84822. }
  84823. if(!hullB.uniqueAxes){
  84824. // Test face normals from hullB
  84825. var numFacesB = faceListB ? faceListB.length : hullB.faces.length;
  84826. for(var i=0;i<numFacesB;i++){
  84827. var fi = faceListB ? faceListB[i] : i;
  84828. Worldnormal1.copy(hullB.faceNormals[fi]);
  84829. quatB.vmult(Worldnormal1,Worldnormal1);
  84830. curPlaneTests++;
  84831. var d = hullA.testSepAxis(Worldnormal1, hullB,posA,quatA,posB,quatB);
  84832. if(d===false){
  84833. return false;
  84834. }
  84835. if(d<dmin){
  84836. dmin = d;
  84837. target.copy(Worldnormal1);
  84838. }
  84839. }
  84840. } else {
  84841. // Test unique axes in B
  84842. for(var i = 0; i !== hullB.uniqueAxes.length; i++){
  84843. quatB.vmult(hullB.uniqueAxes[i],Worldnormal1);
  84844. curPlaneTests++;
  84845. var d = hullA.testSepAxis(Worldnormal1, hullB,posA,quatA,posB,quatB);
  84846. if(d===false){
  84847. return false;
  84848. }
  84849. if(d<dmin){
  84850. dmin = d;
  84851. target.copy(Worldnormal1);
  84852. }
  84853. }
  84854. }
  84855. // Test edges
  84856. for(var e0=0; e0 !== hullA.uniqueEdges.length; e0++){
  84857. // Get world edge
  84858. quatA.vmult(hullA.uniqueEdges[e0],worldEdge0);
  84859. for(var e1=0; e1 !== hullB.uniqueEdges.length; e1++){
  84860. // Get world edge 2
  84861. quatB.vmult(hullB.uniqueEdges[e1], worldEdge1);
  84862. worldEdge0.cross(worldEdge1,Cross);
  84863. if(!Cross.almostZero()){
  84864. Cross.normalize();
  84865. var dist = hullA.testSepAxis(Cross, hullB, posA, quatA, posB, quatB);
  84866. if(dist === false){
  84867. return false;
  84868. }
  84869. if(dist < dmin){
  84870. dmin = dist;
  84871. target.copy(Cross);
  84872. }
  84873. }
  84874. }
  84875. }
  84876. posB.vsub(posA,deltaC);
  84877. if((deltaC.dot(target))>0.0){
  84878. target.negate(target);
  84879. }
  84880. return true;
  84881. };
  84882. var maxminA=[], maxminB=[];
  84883. /**
  84884. * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one.
  84885. * @method testSepAxis
  84886. * @param {Vec3} axis
  84887. * @param {ConvexPolyhedron} hullB
  84888. * @param {Vec3} posA
  84889. * @param {Quaternion} quatA
  84890. * @param {Vec3} posB
  84891. * @param {Quaternion} quatB
  84892. * @return {number} The overlap depth, or FALSE if no penetration.
  84893. */
  84894. ConvexPolyhedron.prototype.testSepAxis = function(axis, hullB, posA, quatA, posB, quatB){
  84895. var hullA=this;
  84896. ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA);
  84897. ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB);
  84898. var maxA = maxminA[0];
  84899. var minA = maxminA[1];
  84900. var maxB = maxminB[0];
  84901. var minB = maxminB[1];
  84902. if(maxA<minB || maxB<minA){
  84903. return false; // Separated
  84904. }
  84905. var d0 = maxA - minB;
  84906. var d1 = maxB - minA;
  84907. var depth = d0<d1 ? d0:d1;
  84908. return depth;
  84909. };
  84910. var cli_aabbmin = new Vec3(),
  84911. cli_aabbmax = new Vec3();
  84912. /**
  84913. * @method calculateLocalInertia
  84914. * @param {Number} mass
  84915. * @param {Vec3} target
  84916. */
  84917. ConvexPolyhedron.prototype.calculateLocalInertia = function(mass,target){
  84918. // Approximate with box inertia
  84919. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  84920. this.computeLocalAABB(cli_aabbmin,cli_aabbmax);
  84921. var x = cli_aabbmax.x - cli_aabbmin.x,
  84922. y = cli_aabbmax.y - cli_aabbmin.y,
  84923. z = cli_aabbmax.z - cli_aabbmin.z;
  84924. target.x = 1.0 / 12.0 * mass * ( 2*y*2*y + 2*z*2*z );
  84925. target.y = 1.0 / 12.0 * mass * ( 2*x*2*x + 2*z*2*z );
  84926. target.z = 1.0 / 12.0 * mass * ( 2*y*2*y + 2*x*2*x );
  84927. };
  84928. /**
  84929. * @method getPlaneConstantOfFace
  84930. * @param {Number} face_i Index of the face
  84931. * @return {Number}
  84932. */
  84933. ConvexPolyhedron.prototype.getPlaneConstantOfFace = function(face_i){
  84934. var f = this.faces[face_i];
  84935. var n = this.faceNormals[face_i];
  84936. var v = this.vertices[f[0]];
  84937. var c = -n.dot(v);
  84938. return c;
  84939. };
  84940. /**
  84941. * Clip a face against a hull.
  84942. * @method clipFaceAgainstHull
  84943. * @param {Vec3} separatingNormal
  84944. * @param {Vec3} posA
  84945. * @param {Quaternion} quatA
  84946. * @param {Array} worldVertsB1 An array of Vec3 with vertices in the world frame.
  84947. * @param {Number} minDist Distance clamping
  84948. * @param {Number} maxDist
  84949. * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.
  84950. */
  84951. var cfah_faceANormalWS = new Vec3(),
  84952. cfah_edge0 = new Vec3(),
  84953. cfah_WorldEdge0 = new Vec3(),
  84954. cfah_worldPlaneAnormal1 = new Vec3(),
  84955. cfah_planeNormalWS1 = new Vec3(),
  84956. cfah_worldA1 = new Vec3(),
  84957. cfah_localPlaneNormal = new Vec3(),
  84958. cfah_planeNormalWS = new Vec3();
  84959. ConvexPolyhedron.prototype.clipFaceAgainstHull = function(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist,result){
  84960. var faceANormalWS = cfah_faceANormalWS,
  84961. edge0 = cfah_edge0,
  84962. WorldEdge0 = cfah_WorldEdge0,
  84963. worldPlaneAnormal1 = cfah_worldPlaneAnormal1,
  84964. planeNormalWS1 = cfah_planeNormalWS1,
  84965. worldA1 = cfah_worldA1,
  84966. localPlaneNormal = cfah_localPlaneNormal,
  84967. planeNormalWS = cfah_planeNormalWS;
  84968. var hullA = this;
  84969. var worldVertsB2 = [];
  84970. var pVtxIn = worldVertsB1;
  84971. var pVtxOut = worldVertsB2;
  84972. // Find the face with normal closest to the separating axis
  84973. var closestFaceA = -1;
  84974. var dmin = Number.MAX_VALUE;
  84975. for(var face=0; face<hullA.faces.length; face++){
  84976. faceANormalWS.copy(hullA.faceNormals[face]);
  84977. quatA.vmult(faceANormalWS,faceANormalWS);
  84978. //posA.vadd(faceANormalWS,faceANormalWS);
  84979. var d = faceANormalWS.dot(separatingNormal);
  84980. if (d < dmin){
  84981. dmin = d;
  84982. closestFaceA = face;
  84983. }
  84984. }
  84985. if (closestFaceA < 0){
  84986. // console.log("--- did not find any closest face... ---");
  84987. return;
  84988. }
  84989. //console.log("closest A: ",closestFaceA);
  84990. // Get the face and construct connected faces
  84991. var polyA = hullA.faces[closestFaceA];
  84992. polyA.connectedFaces = [];
  84993. for(var i=0; i<hullA.faces.length; i++){
  84994. for(var j=0; j<hullA.faces[i].length; j++){
  84995. if(polyA.indexOf(hullA.faces[i][j])!==-1 /* Sharing a vertex*/ && i!==closestFaceA /* Not the one we are looking for connections from */ && polyA.connectedFaces.indexOf(i)===-1 /* Not already added */ ){
  84996. polyA.connectedFaces.push(i);
  84997. }
  84998. }
  84999. }
  85000. // Clip the polygon to the back of the planes of all faces of hull A, that are adjacent to the witness face
  85001. var numContacts = pVtxIn.length;
  85002. var numVerticesA = polyA.length;
  85003. var res = [];
  85004. for(var e0=0; e0<numVerticesA; e0++){
  85005. var a = hullA.vertices[polyA[e0]];
  85006. var b = hullA.vertices[polyA[(e0+1)%numVerticesA]];
  85007. a.vsub(b,edge0);
  85008. WorldEdge0.copy(edge0);
  85009. quatA.vmult(WorldEdge0,WorldEdge0);
  85010. posA.vadd(WorldEdge0,WorldEdge0);
  85011. worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]);//transA.getBasis()* btVector3(polyA.m_plane[0],polyA.m_plane[1],polyA.m_plane[2]);
  85012. quatA.vmult(worldPlaneAnormal1,worldPlaneAnormal1);
  85013. posA.vadd(worldPlaneAnormal1,worldPlaneAnormal1);
  85014. WorldEdge0.cross(worldPlaneAnormal1,planeNormalWS1);
  85015. planeNormalWS1.negate(planeNormalWS1);
  85016. worldA1.copy(a);
  85017. quatA.vmult(worldA1,worldA1);
  85018. posA.vadd(worldA1,worldA1);
  85019. var planeEqWS1 = -worldA1.dot(planeNormalWS1);
  85020. var planeEqWS;
  85021. if(true){
  85022. var otherFace = polyA.connectedFaces[e0];
  85023. localPlaneNormal.copy(this.faceNormals[otherFace]);
  85024. var localPlaneEq = this.getPlaneConstantOfFace(otherFace);
  85025. planeNormalWS.copy(localPlaneNormal);
  85026. quatA.vmult(planeNormalWS,planeNormalWS);
  85027. //posA.vadd(planeNormalWS,planeNormalWS);
  85028. var planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
  85029. } else {
  85030. planeNormalWS.copy(planeNormalWS1);
  85031. planeEqWS = planeEqWS1;
  85032. }
  85033. // Clip face against our constructed plane
  85034. this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS);
  85035. // Throw away all clipped points, but save the reamining until next clip
  85036. while(pVtxIn.length){
  85037. pVtxIn.shift();
  85038. }
  85039. while(pVtxOut.length){
  85040. pVtxIn.push(pVtxOut.shift());
  85041. }
  85042. }
  85043. //console.log("Resulting points after clip:",pVtxIn);
  85044. // only keep contact points that are behind the witness face
  85045. localPlaneNormal.copy(this.faceNormals[closestFaceA]);
  85046. var localPlaneEq = this.getPlaneConstantOfFace(closestFaceA);
  85047. planeNormalWS.copy(localPlaneNormal);
  85048. quatA.vmult(planeNormalWS,planeNormalWS);
  85049. var planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
  85050. for (var i=0; i<pVtxIn.length; i++){
  85051. var depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; //???
  85052. /*console.log("depth calc from normal=",planeNormalWS.toString()," and constant "+planeEqWS+" and vertex ",pVtxIn[i].toString()," gives "+depth);*/
  85053. if (depth <=minDist){
  85054. console.log("clamped: depth="+depth+" to minDist="+(minDist+""));
  85055. depth = minDist;
  85056. }
  85057. if (depth <=maxDist){
  85058. var point = pVtxIn[i];
  85059. if(depth<=0){
  85060. /*console.log("Got contact point ",point.toString(),
  85061. ", depth=",depth,
  85062. "contact normal=",separatingNormal.toString(),
  85063. "plane",planeNormalWS.toString(),
  85064. "planeConstant",planeEqWS);*/
  85065. var p = {
  85066. point:point,
  85067. normal:planeNormalWS,
  85068. depth: depth,
  85069. };
  85070. result.push(p);
  85071. }
  85072. }
  85073. }
  85074. };
  85075. /**
  85076. * Clip a face in a hull against the back of a plane.
  85077. * @method clipFaceAgainstPlane
  85078. * @param {Array} inVertices
  85079. * @param {Array} outVertices
  85080. * @param {Vec3} planeNormal
  85081. * @param {Number} planeConstant The constant in the mathematical plane equation
  85082. */
  85083. ConvexPolyhedron.prototype.clipFaceAgainstPlane = function(inVertices,outVertices, planeNormal, planeConstant){
  85084. var n_dot_first, n_dot_last;
  85085. var numVerts = inVertices.length;
  85086. if(numVerts < 2){
  85087. return outVertices;
  85088. }
  85089. var firstVertex = inVertices[inVertices.length-1],
  85090. lastVertex = inVertices[0];
  85091. n_dot_first = planeNormal.dot(firstVertex) + planeConstant;
  85092. for(var vi = 0; vi < numVerts; vi++){
  85093. lastVertex = inVertices[vi];
  85094. n_dot_last = planeNormal.dot(lastVertex) + planeConstant;
  85095. if(n_dot_first < 0){
  85096. if(n_dot_last < 0){
  85097. // Start < 0, end < 0, so output lastVertex
  85098. var newv = new Vec3();
  85099. newv.copy(lastVertex);
  85100. outVertices.push(newv);
  85101. } else {
  85102. // Start < 0, end >= 0, so output intersection
  85103. var newv = new Vec3();
  85104. firstVertex.lerp(lastVertex,
  85105. n_dot_first / (n_dot_first - n_dot_last),
  85106. newv);
  85107. outVertices.push(newv);
  85108. }
  85109. } else {
  85110. if(n_dot_last<0){
  85111. // Start >= 0, end < 0 so output intersection and end
  85112. var newv = new Vec3();
  85113. firstVertex.lerp(lastVertex,
  85114. n_dot_first / (n_dot_first - n_dot_last),
  85115. newv);
  85116. outVertices.push(newv);
  85117. outVertices.push(lastVertex);
  85118. }
  85119. }
  85120. firstVertex = lastVertex;
  85121. n_dot_first = n_dot_last;
  85122. }
  85123. return outVertices;
  85124. };
  85125. // Updates .worldVertices and sets .worldVerticesNeedsUpdate to false.
  85126. ConvexPolyhedron.prototype.computeWorldVertices = function(position,quat){
  85127. var N = this.vertices.length;
  85128. while(this.worldVertices.length < N){
  85129. this.worldVertices.push( new Vec3() );
  85130. }
  85131. var verts = this.vertices,
  85132. worldVerts = this.worldVertices;
  85133. for(var i=0; i!==N; i++){
  85134. quat.vmult( verts[i] , worldVerts[i] );
  85135. position.vadd( worldVerts[i] , worldVerts[i] );
  85136. }
  85137. this.worldVerticesNeedsUpdate = false;
  85138. };
  85139. var computeLocalAABB_worldVert = new Vec3();
  85140. ConvexPolyhedron.prototype.computeLocalAABB = function(aabbmin,aabbmax){
  85141. var n = this.vertices.length,
  85142. vertices = this.vertices,
  85143. worldVert = computeLocalAABB_worldVert;
  85144. aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85145. aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85146. for(var i=0; i<n; i++){
  85147. var v = vertices[i];
  85148. if (v.x < aabbmin.x){
  85149. aabbmin.x = v.x;
  85150. } else if(v.x > aabbmax.x){
  85151. aabbmax.x = v.x;
  85152. }
  85153. if (v.y < aabbmin.y){
  85154. aabbmin.y = v.y;
  85155. } else if(v.y > aabbmax.y){
  85156. aabbmax.y = v.y;
  85157. }
  85158. if (v.z < aabbmin.z){
  85159. aabbmin.z = v.z;
  85160. } else if(v.z > aabbmax.z){
  85161. aabbmax.z = v.z;
  85162. }
  85163. }
  85164. };
  85165. /**
  85166. * Updates .worldVertices and sets .worldVerticesNeedsUpdate to false.
  85167. * @method computeWorldFaceNormals
  85168. * @param {Quaternion} quat
  85169. */
  85170. ConvexPolyhedron.prototype.computeWorldFaceNormals = function(quat){
  85171. var N = this.faceNormals.length;
  85172. while(this.worldFaceNormals.length < N){
  85173. this.worldFaceNormals.push( new Vec3() );
  85174. }
  85175. var normals = this.faceNormals,
  85176. worldNormals = this.worldFaceNormals;
  85177. for(var i=0; i!==N; i++){
  85178. quat.vmult( normals[i] , worldNormals[i] );
  85179. }
  85180. this.worldFaceNormalsNeedsUpdate = false;
  85181. };
  85182. /**
  85183. * @method updateBoundingSphereRadius
  85184. */
  85185. ConvexPolyhedron.prototype.updateBoundingSphereRadius = function(){
  85186. // Assume points are distributed with local (0,0,0) as center
  85187. var max2 = 0;
  85188. var verts = this.vertices;
  85189. for(var i=0, N=verts.length; i!==N; i++) {
  85190. var norm2 = verts[i].norm2();
  85191. if(norm2 > max2){
  85192. max2 = norm2;
  85193. }
  85194. }
  85195. this.boundingSphereRadius = Math.sqrt(max2);
  85196. };
  85197. var tempWorldVertex = new Vec3();
  85198. /**
  85199. * @method calculateWorldAABB
  85200. * @param {Vec3} pos
  85201. * @param {Quaternion} quat
  85202. * @param {Vec3} min
  85203. * @param {Vec3} max
  85204. */
  85205. ConvexPolyhedron.prototype.calculateWorldAABB = function(pos,quat,min,max){
  85206. var n = this.vertices.length, verts = this.vertices;
  85207. var minx,miny,minz,maxx,maxy,maxz;
  85208. for(var i=0; i<n; i++){
  85209. tempWorldVertex.copy(verts[i]);
  85210. quat.vmult(tempWorldVertex,tempWorldVertex);
  85211. pos.vadd(tempWorldVertex,tempWorldVertex);
  85212. var v = tempWorldVertex;
  85213. if (v.x < minx || minx===undefined){
  85214. minx = v.x;
  85215. } else if(v.x > maxx || maxx===undefined){
  85216. maxx = v.x;
  85217. }
  85218. if (v.y < miny || miny===undefined){
  85219. miny = v.y;
  85220. } else if(v.y > maxy || maxy===undefined){
  85221. maxy = v.y;
  85222. }
  85223. if (v.z < minz || minz===undefined){
  85224. minz = v.z;
  85225. } else if(v.z > maxz || maxz===undefined){
  85226. maxz = v.z;
  85227. }
  85228. }
  85229. min.set(minx,miny,minz);
  85230. max.set(maxx,maxy,maxz);
  85231. };
  85232. /**
  85233. * Get approximate convex volume
  85234. * @method volume
  85235. * @return {Number}
  85236. */
  85237. ConvexPolyhedron.prototype.volume = function(){
  85238. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  85239. };
  85240. /**
  85241. * Get an average of all the vertices positions
  85242. * @method getAveragePointLocal
  85243. * @param {Vec3} target
  85244. * @return {Vec3}
  85245. */
  85246. ConvexPolyhedron.prototype.getAveragePointLocal = function(target){
  85247. target = target || new Vec3();
  85248. var n = this.vertices.length,
  85249. verts = this.vertices;
  85250. for(var i=0; i<n; i++){
  85251. target.vadd(verts[i],target);
  85252. }
  85253. target.mult(1/n,target);
  85254. return target;
  85255. };
  85256. /**
  85257. * Transform all local points. Will change the .vertices
  85258. * @method transformAllPoints
  85259. * @param {Vec3} offset
  85260. * @param {Quaternion} quat
  85261. */
  85262. ConvexPolyhedron.prototype.transformAllPoints = function(offset,quat){
  85263. var n = this.vertices.length,
  85264. verts = this.vertices;
  85265. // Apply rotation
  85266. if(quat){
  85267. // Rotate vertices
  85268. for(var i=0; i<n; i++){
  85269. var v = verts[i];
  85270. quat.vmult(v,v);
  85271. }
  85272. // Rotate face normals
  85273. for(var i=0; i<this.faceNormals.length; i++){
  85274. var v = this.faceNormals[i];
  85275. quat.vmult(v,v);
  85276. }
  85277. /*
  85278. // Rotate edges
  85279. for(var i=0; i<this.uniqueEdges.length; i++){
  85280. var v = this.uniqueEdges[i];
  85281. quat.vmult(v,v);
  85282. }*/
  85283. }
  85284. // Apply offset
  85285. if(offset){
  85286. for(var i=0; i<n; i++){
  85287. var v = verts[i];
  85288. v.vadd(offset,v);
  85289. }
  85290. }
  85291. };
  85292. /**
  85293. * Checks whether p is inside the polyhedra. Must be in local coords. The point lies outside of the convex hull of the other points if and only if the direction of all the vectors from it to those other points are on less than one half of a sphere around it.
  85294. * @method pointIsInside
  85295. * @param {Vec3} p A point given in local coordinates
  85296. * @return {Boolean}
  85297. */
  85298. var ConvexPolyhedron_pointIsInside = new Vec3();
  85299. var ConvexPolyhedron_vToP = new Vec3();
  85300. var ConvexPolyhedron_vToPointInside = new Vec3();
  85301. ConvexPolyhedron.prototype.pointIsInside = function(p){
  85302. var n = this.vertices.length,
  85303. verts = this.vertices,
  85304. faces = this.faces,
  85305. normals = this.faceNormals;
  85306. var positiveResult = null;
  85307. var N = this.faces.length;
  85308. var pointInside = ConvexPolyhedron_pointIsInside;
  85309. this.getAveragePointLocal(pointInside);
  85310. for(var i=0; i<N; i++){
  85311. var numVertices = this.faces[i].length;
  85312. var n = normals[i];
  85313. var v = verts[faces[i][0]]; // We only need one point in the face
  85314. // This dot product determines which side of the edge the point is
  85315. var vToP = ConvexPolyhedron_vToP;
  85316. p.vsub(v,vToP);
  85317. var r1 = n.dot(vToP);
  85318. var vToPointInside = ConvexPolyhedron_vToPointInside;
  85319. pointInside.vsub(v,vToPointInside);
  85320. var r2 = n.dot(vToPointInside);
  85321. if((r1<0 && r2>0) || (r1>0 && r2<0)){
  85322. return false; // Encountered some other sign. Exit.
  85323. } else {
  85324. }
  85325. }
  85326. // If we got here, all dot products were of the same sign.
  85327. return positiveResult ? 1 : -1;
  85328. };
  85329. /**
  85330. * Get max and min dot product of a convex hull at position (pos,quat) projected onto an axis. Results are saved in the array maxmin.
  85331. * @static
  85332. * @method project
  85333. * @param {ConvexPolyhedron} hull
  85334. * @param {Vec3} axis
  85335. * @param {Vec3} pos
  85336. * @param {Quaternion} quat
  85337. * @param {array} result result[0] and result[1] will be set to maximum and minimum, respectively.
  85338. */
  85339. var project_worldVertex = new Vec3();
  85340. var project_localAxis = new Vec3();
  85341. var project_localOrigin = new Vec3();
  85342. ConvexPolyhedron.project = function(hull, axis, pos, quat, result){
  85343. var n = hull.vertices.length,
  85344. worldVertex = project_worldVertex,
  85345. localAxis = project_localAxis,
  85346. max = 0,
  85347. min = 0,
  85348. localOrigin = project_localOrigin,
  85349. vs = hull.vertices;
  85350. localOrigin.setZero();
  85351. // Transform the axis to local
  85352. Transform.vectorToLocalFrame(pos, quat, axis, localAxis);
  85353. Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin);
  85354. var add = localOrigin.dot(localAxis);
  85355. min = max = vs[0].dot(localAxis);
  85356. for(var i = 1; i < n; i++){
  85357. var val = vs[i].dot(localAxis);
  85358. if(val > max){
  85359. max = val;
  85360. }
  85361. if(val < min){
  85362. min = val;
  85363. }
  85364. }
  85365. min -= add;
  85366. max -= add;
  85367. if(min > max){
  85368. // Inconsistent - swap
  85369. var temp = min;
  85370. min = max;
  85371. max = temp;
  85372. }
  85373. // Output
  85374. result[0] = max;
  85375. result[1] = min;
  85376. };
  85377. },{"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"./Shape":43}],39:[function(_dereq_,module,exports){
  85378. module.exports = Cylinder;
  85379. var Shape = _dereq_('./Shape');
  85380. var Vec3 = _dereq_('../math/Vec3');
  85381. var Quaternion = _dereq_('../math/Quaternion');
  85382. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  85383. /**
  85384. * @class Cylinder
  85385. * @constructor
  85386. * @extends ConvexPolyhedron
  85387. * @author schteppe / https://github.com/schteppe
  85388. * @param {Number} radiusTop
  85389. * @param {Number} radiusBottom
  85390. * @param {Number} height
  85391. * @param {Number} numSegments The number of segments to build the cylinder out of
  85392. */
  85393. function Cylinder( radiusTop, radiusBottom, height , numSegments ) {
  85394. var N = numSegments,
  85395. verts = [],
  85396. axes = [],
  85397. faces = [],
  85398. bottomface = [],
  85399. topface = [],
  85400. cos = Math.cos,
  85401. sin = Math.sin;
  85402. // First bottom point
  85403. verts.push(new Vec3(radiusBottom*cos(0),
  85404. radiusBottom*sin(0),
  85405. -height*0.5));
  85406. bottomface.push(0);
  85407. // First top point
  85408. verts.push(new Vec3(radiusTop*cos(0),
  85409. radiusTop*sin(0),
  85410. height*0.5));
  85411. topface.push(1);
  85412. for(var i=0; i<N; i++){
  85413. var theta = 2*Math.PI/N * (i+1);
  85414. var thetaN = 2*Math.PI/N * (i+0.5);
  85415. if(i<N-1){
  85416. // Bottom
  85417. verts.push(new Vec3(radiusBottom*cos(theta),
  85418. radiusBottom*sin(theta),
  85419. -height*0.5));
  85420. bottomface.push(2*i+2);
  85421. // Top
  85422. verts.push(new Vec3(radiusTop*cos(theta),
  85423. radiusTop*sin(theta),
  85424. height*0.5));
  85425. topface.push(2*i+3);
  85426. // Face
  85427. faces.push([2*i+2, 2*i+3, 2*i+1,2*i]);
  85428. } else {
  85429. faces.push([0,1, 2*i+1, 2*i]); // Connect
  85430. }
  85431. // Axis: we can cut off half of them if we have even number of segments
  85432. if(N % 2 === 1 || i < N / 2){
  85433. axes.push(new Vec3(cos(thetaN), sin(thetaN), 0));
  85434. }
  85435. }
  85436. faces.push(topface);
  85437. axes.push(new Vec3(0,0,1));
  85438. // Reorder bottom face
  85439. var temp = [];
  85440. for(var i=0; i<bottomface.length; i++){
  85441. temp.push(bottomface[bottomface.length - i - 1]);
  85442. }
  85443. faces.push(temp);
  85444. this.type = Shape.types.CONVEXPOLYHEDRON;
  85445. ConvexPolyhedron.call( this, verts, faces, axes );
  85446. }
  85447. Cylinder.prototype = new ConvexPolyhedron();
  85448. },{"../math/Quaternion":28,"../math/Vec3":30,"./ConvexPolyhedron":38,"./Shape":43}],40:[function(_dereq_,module,exports){
  85449. var Shape = _dereq_('./Shape');
  85450. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  85451. var Vec3 = _dereq_('../math/Vec3');
  85452. var Utils = _dereq_('../utils/Utils');
  85453. module.exports = Heightfield;
  85454. /**
  85455. * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.
  85456. * @class Heightfield
  85457. * @extends Shape
  85458. * @constructor
  85459. * @param {Array} data An array of Y values that will be used to construct the terrain.
  85460. * @param {object} options
  85461. * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given.
  85462. * @param {Number} [options.maxValue] Maximum value.
  85463. * @param {Number} [options.elementSize=0.1] World spacing between the data points in X direction.
  85464. * @todo Should be possible to use along all axes, not just y
  85465. *
  85466. * @example
  85467. * // Generate some height data (y-values).
  85468. * var data = [];
  85469. * for(var i = 0; i < 1000; i++){
  85470. * var y = 0.5 * Math.cos(0.2 * i);
  85471. * data.push(y);
  85472. * }
  85473. *
  85474. * // Create the heightfield shape
  85475. * var heightfieldShape = new Heightfield(data, {
  85476. * elementSize: 1 // Distance between the data points in X and Y directions
  85477. * });
  85478. * var heightfieldBody = new Body();
  85479. * heightfieldBody.addShape(heightfieldShape);
  85480. * world.addBody(heightfieldBody);
  85481. */
  85482. function Heightfield(data, options){
  85483. options = Utils.defaults(options, {
  85484. maxValue : null,
  85485. minValue : null,
  85486. elementSize : 1
  85487. });
  85488. /**
  85489. * An array of numbers, or height values, that are spread out along the x axis.
  85490. * @property {array} data
  85491. */
  85492. this.data = data;
  85493. /**
  85494. * Max value of the data
  85495. * @property {number} maxValue
  85496. */
  85497. this.maxValue = options.maxValue;
  85498. /**
  85499. * Max value of the data
  85500. * @property {number} minValue
  85501. */
  85502. this.minValue = options.minValue;
  85503. /**
  85504. * The width of each element
  85505. * @property {number} elementSize
  85506. * @todo elementSizeX and Y
  85507. */
  85508. this.elementSize = options.elementSize;
  85509. if(options.minValue === null){
  85510. this.updateMinValue();
  85511. }
  85512. if(options.maxValue === null){
  85513. this.updateMaxValue();
  85514. }
  85515. this.cacheEnabled = true;
  85516. Shape.call(this);
  85517. this.pillarConvex = new ConvexPolyhedron();
  85518. this.pillarOffset = new Vec3();
  85519. this.type = Shape.types.HEIGHTFIELD;
  85520. this.updateBoundingSphereRadius();
  85521. // "i_j_isUpper" => { convex: ..., offset: ... }
  85522. // for example:
  85523. // _cachedPillars["0_2_1"]
  85524. this._cachedPillars = {};
  85525. }
  85526. Heightfield.prototype = new Shape();
  85527. /**
  85528. * Call whenever you change the data array.
  85529. * @method update
  85530. */
  85531. Heightfield.prototype.update = function(){
  85532. this._cachedPillars = {};
  85533. };
  85534. /**
  85535. * Update the .minValue property
  85536. * @method updateMinValue
  85537. */
  85538. Heightfield.prototype.updateMinValue = function(){
  85539. var data = this.data;
  85540. var minValue = data[0][0];
  85541. for(var i=0; i !== data.length; i++){
  85542. for(var j=0; j !== data[i].length; j++){
  85543. var v = data[i][j];
  85544. if(v < minValue){
  85545. minValue = v;
  85546. }
  85547. }
  85548. }
  85549. this.minValue = minValue;
  85550. };
  85551. /**
  85552. * Update the .maxValue property
  85553. * @method updateMaxValue
  85554. */
  85555. Heightfield.prototype.updateMaxValue = function(){
  85556. var data = this.data;
  85557. var maxValue = data[0][0];
  85558. for(var i=0; i !== data.length; i++){
  85559. for(var j=0; j !== data[i].length; j++){
  85560. var v = data[i][j];
  85561. if(v > maxValue){
  85562. maxValue = v;
  85563. }
  85564. }
  85565. }
  85566. this.maxValue = maxValue;
  85567. };
  85568. /**
  85569. * Set the height value at an index. Don't forget to update maxValue and minValue after you're done.
  85570. * @method setHeightValueAtIndex
  85571. * @param {integer} xi
  85572. * @param {integer} yi
  85573. * @param {number} value
  85574. */
  85575. Heightfield.prototype.setHeightValueAtIndex = function(xi, yi, value){
  85576. var data = this.data;
  85577. data[xi][yi] = value;
  85578. // Invalidate cache
  85579. this.clearCachedConvexTrianglePillar(xi, yi, false);
  85580. if(xi > 0){
  85581. this.clearCachedConvexTrianglePillar(xi - 1, yi, true);
  85582. this.clearCachedConvexTrianglePillar(xi - 1, yi, false);
  85583. }
  85584. if(yi > 0){
  85585. this.clearCachedConvexTrianglePillar(xi, yi - 1, true);
  85586. this.clearCachedConvexTrianglePillar(xi, yi - 1, false);
  85587. }
  85588. if(yi > 0 && xi > 0){
  85589. this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);
  85590. }
  85591. };
  85592. /**
  85593. * Get max/min in a rectangle in the matrix data
  85594. * @method getRectMinMax
  85595. * @param {integer} iMinX
  85596. * @param {integer} iMinY
  85597. * @param {integer} iMaxX
  85598. * @param {integer} iMaxY
  85599. * @param {array} [result] An array to store the results in.
  85600. * @return {array} The result array, if it was passed in. Minimum will be at position 0 and max at 1.
  85601. */
  85602. Heightfield.prototype.getRectMinMax = function (iMinX, iMinY, iMaxX, iMaxY, result) {
  85603. result = result || [];
  85604. // Get max and min of the data
  85605. var data = this.data,
  85606. max = this.minValue; // Set first value
  85607. for(var i = iMinX; i <= iMaxX; i++){
  85608. for(var j = iMinY; j <= iMaxY; j++){
  85609. var height = data[i][j];
  85610. if(height > max){
  85611. max = height;
  85612. }
  85613. }
  85614. }
  85615. result[0] = this.minValue;
  85616. result[1] = max;
  85617. };
  85618. /**
  85619. * Get the index of a local position on the heightfield. The indexes indicate the rectangles, so if your terrain is made of N x N height data points, you will have rectangle indexes ranging from 0 to N-1.
  85620. * @method getIndexOfPosition
  85621. * @param {number} x
  85622. * @param {number} y
  85623. * @param {array} result Two-element array
  85624. * @param {boolean} clamp If the position should be clamped to the heightfield edge.
  85625. * @return {boolean}
  85626. */
  85627. Heightfield.prototype.getIndexOfPosition = function (x, y, result, clamp) {
  85628. // Get the index of the data points to test against
  85629. var w = this.elementSize;
  85630. var data = this.data;
  85631. var xi = Math.floor(x / w);
  85632. var yi = Math.floor(y / w);
  85633. result[0] = xi;
  85634. result[1] = yi;
  85635. if(clamp){
  85636. // Clamp index to edges
  85637. if(xi < 0){ xi = 0; }
  85638. if(yi < 0){ yi = 0; }
  85639. if(xi >= data.length - 1){ xi = data.length - 1; }
  85640. if(yi >= data[0].length - 1){ yi = data[0].length - 1; }
  85641. }
  85642. // Bail out if we are out of the terrain
  85643. if(xi < 0 || yi < 0 || xi >= data.length-1 || yi >= data[0].length-1){
  85644. return false;
  85645. }
  85646. return true;
  85647. };
  85648. Heightfield.prototype.getHeightAt = function(x, y, edgeClamp){
  85649. var idx = [];
  85650. this.getIndexOfPosition(x, y, idx, edgeClamp);
  85651. // TODO: get upper or lower triangle, then use barycentric interpolation to get the height in the triangle.
  85652. var minmax = [];
  85653. this.getRectMinMax(idx[0], idx[1] + 1, idx[0], idx[1] + 1, minmax);
  85654. return (minmax[0] + minmax[1]) / 2; // average
  85655. };
  85656. Heightfield.prototype.getCacheConvexTrianglePillarKey = function(xi, yi, getUpperTriangle){
  85657. return xi + '_' + yi + '_' + (getUpperTriangle ? 1 : 0);
  85658. };
  85659. Heightfield.prototype.getCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  85660. return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  85661. };
  85662. Heightfield.prototype.setCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle, convex, offset){
  85663. this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = {
  85664. convex: convex,
  85665. offset: offset
  85666. };
  85667. };
  85668. Heightfield.prototype.clearCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  85669. delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  85670. };
  85671. /**
  85672. * Get a triangle in the terrain in the form of a triangular convex shape.
  85673. * @method getConvexTrianglePillar
  85674. * @param {integer} i
  85675. * @param {integer} j
  85676. * @param {boolean} getUpperTriangle
  85677. */
  85678. Heightfield.prototype.getConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  85679. var result = this.pillarConvex;
  85680. var offsetResult = this.pillarOffset;
  85681. if(this.cacheEnabled){
  85682. var data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);
  85683. if(data){
  85684. this.pillarConvex = data.convex;
  85685. this.pillarOffset = data.offset;
  85686. return;
  85687. }
  85688. result = new ConvexPolyhedron();
  85689. offsetResult = new Vec3();
  85690. this.pillarConvex = result;
  85691. this.pillarOffset = offsetResult;
  85692. }
  85693. var data = this.data;
  85694. var elementSize = this.elementSize;
  85695. var faces = result.faces;
  85696. // Reuse verts if possible
  85697. result.vertices.length = 6;
  85698. for (var i = 0; i < 6; i++) {
  85699. if(!result.vertices[i]){
  85700. result.vertices[i] = new Vec3();
  85701. }
  85702. }
  85703. // Reuse faces if possible
  85704. faces.length = 5;
  85705. for (var i = 0; i < 5; i++) {
  85706. if(!faces[i]){
  85707. faces[i] = [];
  85708. }
  85709. }
  85710. var verts = result.vertices;
  85711. var h = (Math.min(
  85712. data[xi][yi],
  85713. data[xi+1][yi],
  85714. data[xi][yi+1],
  85715. data[xi+1][yi+1]
  85716. ) - this.minValue ) / 2 + this.minValue;
  85717. if (!getUpperTriangle) {
  85718. // Center of the triangle pillar - all polygons are given relative to this one
  85719. offsetResult.set(
  85720. (xi + 0.25) * elementSize, // sort of center of a triangle
  85721. (yi + 0.25) * elementSize,
  85722. h // vertical center
  85723. );
  85724. // Top triangle verts
  85725. verts[0].set(
  85726. -0.25 * elementSize,
  85727. -0.25 * elementSize,
  85728. data[xi][yi] - h
  85729. );
  85730. verts[1].set(
  85731. 0.75 * elementSize,
  85732. -0.25 * elementSize,
  85733. data[xi + 1][yi] - h
  85734. );
  85735. verts[2].set(
  85736. -0.25 * elementSize,
  85737. 0.75 * elementSize,
  85738. data[xi][yi + 1] - h
  85739. );
  85740. // bottom triangle verts
  85741. verts[3].set(
  85742. -0.25 * elementSize,
  85743. -0.25 * elementSize,
  85744. -h-1
  85745. );
  85746. verts[4].set(
  85747. 0.75 * elementSize,
  85748. -0.25 * elementSize,
  85749. -h-1
  85750. );
  85751. verts[5].set(
  85752. -0.25 * elementSize,
  85753. 0.75 * elementSize,
  85754. -h-1
  85755. );
  85756. // top triangle
  85757. faces[0][0] = 0;
  85758. faces[0][1] = 1;
  85759. faces[0][2] = 2;
  85760. // bottom triangle
  85761. faces[1][0] = 5;
  85762. faces[1][1] = 4;
  85763. faces[1][2] = 3;
  85764. // -x facing quad
  85765. faces[2][0] = 0;
  85766. faces[2][1] = 2;
  85767. faces[2][2] = 5;
  85768. faces[2][3] = 3;
  85769. // -y facing quad
  85770. faces[3][0] = 1;
  85771. faces[3][1] = 0;
  85772. faces[3][2] = 3;
  85773. faces[3][3] = 4;
  85774. // +xy facing quad
  85775. faces[4][0] = 4;
  85776. faces[4][1] = 5;
  85777. faces[4][2] = 2;
  85778. faces[4][3] = 1;
  85779. } else {
  85780. // Center of the triangle pillar - all polygons are given relative to this one
  85781. offsetResult.set(
  85782. (xi + 0.75) * elementSize, // sort of center of a triangle
  85783. (yi + 0.75) * elementSize,
  85784. h // vertical center
  85785. );
  85786. // Top triangle verts
  85787. verts[0].set(
  85788. 0.25 * elementSize,
  85789. 0.25 * elementSize,
  85790. data[xi + 1][yi + 1] - h
  85791. );
  85792. verts[1].set(
  85793. -0.75 * elementSize,
  85794. 0.25 * elementSize,
  85795. data[xi][yi + 1] - h
  85796. );
  85797. verts[2].set(
  85798. 0.25 * elementSize,
  85799. -0.75 * elementSize,
  85800. data[xi + 1][yi] - h
  85801. );
  85802. // bottom triangle verts
  85803. verts[3].set(
  85804. 0.25 * elementSize,
  85805. 0.25 * elementSize,
  85806. - h-1
  85807. );
  85808. verts[4].set(
  85809. -0.75 * elementSize,
  85810. 0.25 * elementSize,
  85811. - h-1
  85812. );
  85813. verts[5].set(
  85814. 0.25 * elementSize,
  85815. -0.75 * elementSize,
  85816. - h-1
  85817. );
  85818. // Top triangle
  85819. faces[0][0] = 0;
  85820. faces[0][1] = 1;
  85821. faces[0][2] = 2;
  85822. // bottom triangle
  85823. faces[1][0] = 5;
  85824. faces[1][1] = 4;
  85825. faces[1][2] = 3;
  85826. // +x facing quad
  85827. faces[2][0] = 2;
  85828. faces[2][1] = 5;
  85829. faces[2][2] = 3;
  85830. faces[2][3] = 0;
  85831. // +y facing quad
  85832. faces[3][0] = 3;
  85833. faces[3][1] = 4;
  85834. faces[3][2] = 1;
  85835. faces[3][3] = 0;
  85836. // -xy facing quad
  85837. faces[4][0] = 1;
  85838. faces[4][1] = 4;
  85839. faces[4][2] = 5;
  85840. faces[4][3] = 2;
  85841. }
  85842. result.computeNormals();
  85843. result.computeEdges();
  85844. result.updateBoundingSphereRadius();
  85845. this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);
  85846. };
  85847. Heightfield.prototype.calculateLocalInertia = function(mass, target){
  85848. target = target || new Vec3();
  85849. target.set(0, 0, 0);
  85850. return target;
  85851. };
  85852. Heightfield.prototype.volume = function(){
  85853. return Number.MAX_VALUE; // The terrain is infinite
  85854. };
  85855. Heightfield.prototype.calculateWorldAABB = function(pos, quat, min, max){
  85856. // TODO: do it properly
  85857. min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85858. max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85859. };
  85860. Heightfield.prototype.updateBoundingSphereRadius = function(){
  85861. // Use the bounding box of the min/max values
  85862. var data = this.data,
  85863. s = this.elementSize;
  85864. this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).norm();
  85865. };
  85866. },{"../math/Vec3":30,"../utils/Utils":53,"./ConvexPolyhedron":38,"./Shape":43}],41:[function(_dereq_,module,exports){
  85867. module.exports = Particle;
  85868. var Shape = _dereq_('./Shape');
  85869. var Vec3 = _dereq_('../math/Vec3');
  85870. /**
  85871. * Particle shape.
  85872. * @class Particle
  85873. * @constructor
  85874. * @author schteppe
  85875. * @extends Shape
  85876. */
  85877. function Particle(){
  85878. Shape.call(this);
  85879. this.type = Shape.types.PARTICLE;
  85880. }
  85881. Particle.prototype = new Shape();
  85882. Particle.prototype.constructor = Particle;
  85883. /**
  85884. * @method calculateLocalInertia
  85885. * @param {Number} mass
  85886. * @param {Vec3} target
  85887. * @return {Vec3}
  85888. */
  85889. Particle.prototype.calculateLocalInertia = function(mass,target){
  85890. target = target || new Vec3();
  85891. target.set(0, 0, 0);
  85892. return target;
  85893. };
  85894. Particle.prototype.volume = function(){
  85895. return 0;
  85896. };
  85897. Particle.prototype.updateBoundingSphereRadius = function(){
  85898. this.boundingSphereRadius = 0;
  85899. };
  85900. Particle.prototype.calculateWorldAABB = function(pos,quat,min,max){
  85901. // Get each axis max
  85902. min.copy(pos);
  85903. max.copy(pos);
  85904. };
  85905. },{"../math/Vec3":30,"./Shape":43}],42:[function(_dereq_,module,exports){
  85906. module.exports = Plane;
  85907. var Shape = _dereq_('./Shape');
  85908. var Vec3 = _dereq_('../math/Vec3');
  85909. /**
  85910. * A plane, facing in the Z direction. The plane has its surface at z=0 and everything below z=0 is assumed to be solid plane. To make the plane face in some other direction than z, you must put it inside a RigidBody and rotate that body. See the demos.
  85911. * @class Plane
  85912. * @constructor
  85913. * @extends Shape
  85914. * @author schteppe
  85915. */
  85916. function Plane(){
  85917. Shape.call(this);
  85918. this.type = Shape.types.PLANE;
  85919. // World oriented normal
  85920. this.worldNormal = new Vec3();
  85921. this.worldNormalNeedsUpdate = true;
  85922. this.boundingSphereRadius = Number.MAX_VALUE;
  85923. }
  85924. Plane.prototype = new Shape();
  85925. Plane.prototype.constructor = Plane;
  85926. Plane.prototype.computeWorldNormal = function(quat){
  85927. var n = this.worldNormal;
  85928. n.set(0,0,1);
  85929. quat.vmult(n,n);
  85930. this.worldNormalNeedsUpdate = false;
  85931. };
  85932. Plane.prototype.calculateLocalInertia = function(mass,target){
  85933. target = target || new Vec3();
  85934. return target;
  85935. };
  85936. Plane.prototype.volume = function(){
  85937. return Number.MAX_VALUE; // The plane is infinite...
  85938. };
  85939. var tempNormal = new Vec3();
  85940. Plane.prototype.calculateWorldAABB = function(pos, quat, min, max){
  85941. // The plane AABB is infinite, except if the normal is pointing along any axis
  85942. tempNormal.set(0,0,1); // Default plane normal is z
  85943. quat.vmult(tempNormal,tempNormal);
  85944. var maxVal = Number.MAX_VALUE;
  85945. min.set(-maxVal, -maxVal, -maxVal);
  85946. max.set(maxVal, maxVal, maxVal);
  85947. if(tempNormal.x === 1){ max.x = pos.x; }
  85948. if(tempNormal.y === 1){ max.y = pos.y; }
  85949. if(tempNormal.z === 1){ max.z = pos.z; }
  85950. if(tempNormal.x === -1){ min.x = pos.x; }
  85951. if(tempNormal.y === -1){ min.y = pos.y; }
  85952. if(tempNormal.z === -1){ min.z = pos.z; }
  85953. };
  85954. Plane.prototype.updateBoundingSphereRadius = function(){
  85955. this.boundingSphereRadius = Number.MAX_VALUE;
  85956. };
  85957. },{"../math/Vec3":30,"./Shape":43}],43:[function(_dereq_,module,exports){
  85958. module.exports = Shape;
  85959. var Shape = _dereq_('./Shape');
  85960. var Vec3 = _dereq_('../math/Vec3');
  85961. var Quaternion = _dereq_('../math/Quaternion');
  85962. var Material = _dereq_('../material/Material');
  85963. /**
  85964. * Base class for shapes
  85965. * @class Shape
  85966. * @constructor
  85967. * @author schteppe
  85968. * @todo Should have a mechanism for caching bounding sphere radius instead of calculating it each time
  85969. */
  85970. function Shape(){
  85971. /**
  85972. * Identifyer of the Shape.
  85973. * @property {number} id
  85974. */
  85975. this.id = Shape.idCounter++;
  85976. /**
  85977. * The type of this shape. Must be set to an int > 0 by subclasses.
  85978. * @property type
  85979. * @type {Number}
  85980. * @see Shape.types
  85981. */
  85982. this.type = 0;
  85983. /**
  85984. * The local bounding sphere radius of this shape.
  85985. * @property {Number} boundingSphereRadius
  85986. */
  85987. this.boundingSphereRadius = 0;
  85988. /**
  85989. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  85990. * @property {boolean} collisionResponse
  85991. */
  85992. this.collisionResponse = true;
  85993. /**
  85994. * @property {Material} material
  85995. */
  85996. this.material = null;
  85997. }
  85998. Shape.prototype.constructor = Shape;
  85999. /**
  86000. * Computes the bounding sphere radius. The result is stored in the property .boundingSphereRadius
  86001. * @method updateBoundingSphereRadius
  86002. * @return {Number}
  86003. */
  86004. Shape.prototype.updateBoundingSphereRadius = function(){
  86005. throw "computeBoundingSphereRadius() not implemented for shape type "+this.type;
  86006. };
  86007. /**
  86008. * Get the volume of this shape
  86009. * @method volume
  86010. * @return {Number}
  86011. */
  86012. Shape.prototype.volume = function(){
  86013. throw "volume() not implemented for shape type "+this.type;
  86014. };
  86015. /**
  86016. * Calculates the inertia in the local frame for this shape.
  86017. * @method calculateLocalInertia
  86018. * @return {Vec3}
  86019. * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia
  86020. */
  86021. Shape.prototype.calculateLocalInertia = function(mass,target){
  86022. throw "calculateLocalInertia() not implemented for shape type "+this.type;
  86023. };
  86024. Shape.idCounter = 0;
  86025. /**
  86026. * The available shape types.
  86027. * @static
  86028. * @property types
  86029. * @type {Object}
  86030. */
  86031. Shape.types = {
  86032. SPHERE:1,
  86033. PLANE:2,
  86034. BOX:4,
  86035. COMPOUND:8,
  86036. CONVEXPOLYHEDRON:16,
  86037. HEIGHTFIELD:32,
  86038. PARTICLE:64,
  86039. CYLINDER:128,
  86040. TRIMESH:256
  86041. };
  86042. },{"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"./Shape":43}],44:[function(_dereq_,module,exports){
  86043. module.exports = Sphere;
  86044. var Shape = _dereq_('./Shape');
  86045. var Vec3 = _dereq_('../math/Vec3');
  86046. /**
  86047. * Spherical shape
  86048. * @class Sphere
  86049. * @constructor
  86050. * @extends Shape
  86051. * @param {Number} radius The radius of the sphere, a non-negative number.
  86052. * @author schteppe / http://github.com/schteppe
  86053. */
  86054. function Sphere(radius){
  86055. Shape.call(this);
  86056. /**
  86057. * @property {Number} radius
  86058. */
  86059. this.radius = radius!==undefined ? Number(radius) : 1.0;
  86060. this.type = Shape.types.SPHERE;
  86061. if(this.radius < 0){
  86062. throw new Error('The sphere radius cannot be negative.');
  86063. }
  86064. this.updateBoundingSphereRadius();
  86065. }
  86066. Sphere.prototype = new Shape();
  86067. Sphere.prototype.constructor = Sphere;
  86068. Sphere.prototype.calculateLocalInertia = function(mass,target){
  86069. target = target || new Vec3();
  86070. var I = 2.0*mass*this.radius*this.radius/5.0;
  86071. target.x = I;
  86072. target.y = I;
  86073. target.z = I;
  86074. return target;
  86075. };
  86076. Sphere.prototype.volume = function(){
  86077. return 4.0 * Math.PI * this.radius / 3.0;
  86078. };
  86079. Sphere.prototype.updateBoundingSphereRadius = function(){
  86080. this.boundingSphereRadius = this.radius;
  86081. };
  86082. Sphere.prototype.calculateWorldAABB = function(pos,quat,min,max){
  86083. var r = this.radius;
  86084. var axes = ['x','y','z'];
  86085. for(var i=0; i<axes.length; i++){
  86086. var ax = axes[i];
  86087. min[ax] = pos[ax] - r;
  86088. max[ax] = pos[ax] + r;
  86089. }
  86090. };
  86091. },{"../math/Vec3":30,"./Shape":43}],45:[function(_dereq_,module,exports){
  86092. module.exports = Trimesh;
  86093. var Shape = _dereq_('./Shape');
  86094. var Vec3 = _dereq_('../math/Vec3');
  86095. var Quaternion = _dereq_('../math/Quaternion');
  86096. var Transform = _dereq_('../math/Transform');
  86097. var AABB = _dereq_('../collision/AABB');
  86098. var Octree = _dereq_('../utils/Octree');
  86099. /**
  86100. * @class Trimesh
  86101. * @constructor
  86102. * @param {array} vertices
  86103. * @param {array} indices
  86104. * @extends Shape
  86105. * @example
  86106. * // How to make a mesh with a single triangle
  86107. * var vertices = [
  86108. * 0, 0, 0, // vertex 0
  86109. * 1, 0, 0, // vertex 1
  86110. * 0, 1, 0 // vertex 2
  86111. * ];
  86112. * var indices = [
  86113. * 0, 1, 2 // triangle 0
  86114. * ];
  86115. * var trimeshShape = new Trimesh(vertices, indices);
  86116. */
  86117. function Trimesh(vertices, indices) {
  86118. Shape.call(this);
  86119. this.type = Shape.types.TRIMESH;
  86120. /**
  86121. * @property vertices
  86122. * @type {Array}
  86123. */
  86124. this.vertices = new Float32Array(vertices);
  86125. /**
  86126. * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles.
  86127. * @property indices
  86128. * @type {Array}
  86129. */
  86130. this.indices = new Int16Array(indices);
  86131. /**
  86132. * The normals data.
  86133. * @property normals
  86134. * @type {Array}
  86135. */
  86136. this.normals = new Float32Array(indices.length);
  86137. /**
  86138. * The local AABB of the mesh.
  86139. * @property aabb
  86140. * @type {Array}
  86141. */
  86142. this.aabb = new AABB();
  86143. /**
  86144. * References to vertex pairs, making up all unique edges in the trimesh.
  86145. * @property {array} edges
  86146. */
  86147. this.edges = null;
  86148. /**
  86149. * Local scaling of the mesh. Use .setScale() to set it.
  86150. * @property {Vec3} scale
  86151. */
  86152. this.scale = new Vec3(1, 1, 1);
  86153. /**
  86154. * The indexed triangles. Use .updateTree() to update it.
  86155. * @property {Octree} tree
  86156. */
  86157. this.tree = new Octree();
  86158. this.updateEdges();
  86159. this.updateNormals();
  86160. this.updateAABB();
  86161. this.updateBoundingSphereRadius();
  86162. this.updateTree();
  86163. }
  86164. Trimesh.prototype = new Shape();
  86165. Trimesh.prototype.constructor = Trimesh;
  86166. var computeNormals_n = new Vec3();
  86167. /**
  86168. * @method updateTree
  86169. */
  86170. Trimesh.prototype.updateTree = function(){
  86171. var tree = this.tree;
  86172. tree.reset();
  86173. tree.aabb.copy(this.aabb);
  86174. var scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled
  86175. tree.aabb.lowerBound.x *= 1 / scale.x;
  86176. tree.aabb.lowerBound.y *= 1 / scale.y;
  86177. tree.aabb.lowerBound.z *= 1 / scale.z;
  86178. tree.aabb.upperBound.x *= 1 / scale.x;
  86179. tree.aabb.upperBound.y *= 1 / scale.y;
  86180. tree.aabb.upperBound.z *= 1 / scale.z;
  86181. // Insert all triangles
  86182. var triangleAABB = new AABB();
  86183. var a = new Vec3();
  86184. var b = new Vec3();
  86185. var c = new Vec3();
  86186. var points = [a, b, c];
  86187. for (var i = 0; i < this.indices.length / 3; i++) {
  86188. //this.getTriangleVertices(i, a, b, c);
  86189. // Get unscaled triangle verts
  86190. var i3 = i * 3;
  86191. this._getUnscaledVertex(this.indices[i3], a);
  86192. this._getUnscaledVertex(this.indices[i3 + 1], b);
  86193. this._getUnscaledVertex(this.indices[i3 + 2], c);
  86194. triangleAABB.setFromPoints(points);
  86195. tree.insert(triangleAABB, i);
  86196. }
  86197. tree.removeEmptyNodes();
  86198. };
  86199. var unscaledAABB = new AABB();
  86200. /**
  86201. * Get triangles in a local AABB from the trimesh.
  86202. * @method getTrianglesInAABB
  86203. * @param {AABB} aabb
  86204. * @param {array} result An array of integers, referencing the queried triangles.
  86205. */
  86206. Trimesh.prototype.getTrianglesInAABB = function(aabb, result){
  86207. unscaledAABB.copy(aabb);
  86208. // Scale it to local
  86209. var scale = this.scale;
  86210. var isx = scale.x;
  86211. var isy = scale.y;
  86212. var isz = scale.z;
  86213. var l = unscaledAABB.lowerBound;
  86214. var u = unscaledAABB.upperBound;
  86215. l.x /= isx;
  86216. l.y /= isy;
  86217. l.z /= isz;
  86218. u.x /= isx;
  86219. u.y /= isy;
  86220. u.z /= isz;
  86221. return this.tree.aabbQuery(unscaledAABB, result);
  86222. };
  86223. /**
  86224. * @method setScale
  86225. * @param {Vec3} scale
  86226. */
  86227. Trimesh.prototype.setScale = function(scale){
  86228. var wasUniform = this.scale.x === this.scale.y === this.scale.z;
  86229. var isUniform = scale.x === scale.y === scale.z;
  86230. if(!(wasUniform && isUniform)){
  86231. // Non-uniform scaling. Need to update normals.
  86232. this.updateNormals();
  86233. }
  86234. this.scale.copy(scale);
  86235. this.updateAABB();
  86236. this.updateBoundingSphereRadius();
  86237. };
  86238. /**
  86239. * Compute the normals of the faces. Will save in the .normals array.
  86240. * @method updateNormals
  86241. */
  86242. Trimesh.prototype.updateNormals = function(){
  86243. var n = computeNormals_n;
  86244. // Generate normals
  86245. var normals = this.normals;
  86246. for(var i=0; i < this.indices.length / 3; i++){
  86247. var i3 = i * 3;
  86248. var a = this.indices[i3],
  86249. b = this.indices[i3 + 1],
  86250. c = this.indices[i3 + 2];
  86251. this.getVertex(a, va);
  86252. this.getVertex(b, vb);
  86253. this.getVertex(c, vc);
  86254. Trimesh.computeNormal(vb, va, vc, n);
  86255. normals[i3] = n.x;
  86256. normals[i3 + 1] = n.y;
  86257. normals[i3 + 2] = n.z;
  86258. }
  86259. };
  86260. /**
  86261. * Update the .edges property
  86262. * @method updateEdges
  86263. */
  86264. Trimesh.prototype.updateEdges = function(){
  86265. var edges = {};
  86266. var add = function(indexA, indexB){
  86267. var key = a < b ? a + '_' + b : b + '_' + a;
  86268. edges[key] = true;
  86269. };
  86270. for(var i=0; i < this.indices.length / 3; i++){
  86271. var i3 = i * 3;
  86272. var a = this.indices[i3],
  86273. b = this.indices[i3 + 1],
  86274. c = this.indices[i3 + 2];
  86275. add(a,b);
  86276. add(b,c);
  86277. add(c,a);
  86278. }
  86279. var keys = Object.keys(edges);
  86280. this.edges = new Int16Array(keys.length * 2);
  86281. for (var i = 0; i < keys.length; i++) {
  86282. var indices = keys[i].split('_');
  86283. this.edges[2 * i] = parseInt(indices[0], 10);
  86284. this.edges[2 * i + 1] = parseInt(indices[1], 10);
  86285. }
  86286. };
  86287. /**
  86288. * Get an edge vertex
  86289. * @method getEdgeVertex
  86290. * @param {number} edgeIndex
  86291. * @param {number} firstOrSecond 0 or 1, depending on which one of the vertices you need.
  86292. * @param {Vec3} vertexStore Where to store the result
  86293. */
  86294. Trimesh.prototype.getEdgeVertex = function(edgeIndex, firstOrSecond, vertexStore){
  86295. var vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)];
  86296. this.getVertex(vertexIndex, vertexStore);
  86297. };
  86298. var getEdgeVector_va = new Vec3();
  86299. var getEdgeVector_vb = new Vec3();
  86300. /**
  86301. * Get a vector along an edge.
  86302. * @method getEdgeVector
  86303. * @param {number} edgeIndex
  86304. * @param {Vec3} vectorStore
  86305. */
  86306. Trimesh.prototype.getEdgeVector = function(edgeIndex, vectorStore){
  86307. var va = getEdgeVector_va;
  86308. var vb = getEdgeVector_vb;
  86309. this.getEdgeVertex(edgeIndex, 0, va);
  86310. this.getEdgeVertex(edgeIndex, 1, vb);
  86311. vb.vsub(va, vectorStore);
  86312. };
  86313. /**
  86314. * Get face normal given 3 vertices
  86315. * @static
  86316. * @method computeNormal
  86317. * @param {Vec3} va
  86318. * @param {Vec3} vb
  86319. * @param {Vec3} vc
  86320. * @param {Vec3} target
  86321. */
  86322. var cb = new Vec3();
  86323. var ab = new Vec3();
  86324. Trimesh.computeNormal = function ( va, vb, vc, target ) {
  86325. vb.vsub(va,ab);
  86326. vc.vsub(vb,cb);
  86327. cb.cross(ab,target);
  86328. if ( !target.isZero() ) {
  86329. target.normalize();
  86330. }
  86331. };
  86332. var va = new Vec3();
  86333. var vb = new Vec3();
  86334. var vc = new Vec3();
  86335. /**
  86336. * Get vertex i.
  86337. * @method getVertex
  86338. * @param {number} i
  86339. * @param {Vec3} out
  86340. * @return {Vec3} The "out" vector object
  86341. */
  86342. Trimesh.prototype.getVertex = function(i, out){
  86343. var scale = this.scale;
  86344. this._getUnscaledVertex(i, out);
  86345. out.x *= scale.x;
  86346. out.y *= scale.y;
  86347. out.z *= scale.z;
  86348. return out;
  86349. };
  86350. /**
  86351. * Get raw vertex i
  86352. * @private
  86353. * @method _getUnscaledVertex
  86354. * @param {number} i
  86355. * @param {Vec3} out
  86356. * @return {Vec3} The "out" vector object
  86357. */
  86358. Trimesh.prototype._getUnscaledVertex = function(i, out){
  86359. var i3 = i * 3;
  86360. var vertices = this.vertices;
  86361. return out.set(
  86362. vertices[i3],
  86363. vertices[i3 + 1],
  86364. vertices[i3 + 2]
  86365. );
  86366. };
  86367. /**
  86368. * Get a vertex from the trimesh,transformed by the given position and quaternion.
  86369. * @method getWorldVertex
  86370. * @param {number} i
  86371. * @param {Vec3} pos
  86372. * @param {Quaternion} quat
  86373. * @param {Vec3} out
  86374. * @return {Vec3} The "out" vector object
  86375. */
  86376. Trimesh.prototype.getWorldVertex = function(i, pos, quat, out){
  86377. this.getVertex(i, out);
  86378. Transform.pointToWorldFrame(pos, quat, out, out);
  86379. return out;
  86380. };
  86381. /**
  86382. * Get the three vertices for triangle i.
  86383. * @method getTriangleVertices
  86384. * @param {number} i
  86385. * @param {Vec3} a
  86386. * @param {Vec3} b
  86387. * @param {Vec3} c
  86388. */
  86389. Trimesh.prototype.getTriangleVertices = function(i, a, b, c){
  86390. var i3 = i * 3;
  86391. this.getVertex(this.indices[i3], a);
  86392. this.getVertex(this.indices[i3 + 1], b);
  86393. this.getVertex(this.indices[i3 + 2], c);
  86394. };
  86395. /**
  86396. * Compute the normal of triangle i.
  86397. * @method getNormal
  86398. * @param {Number} i
  86399. * @param {Vec3} target
  86400. * @return {Vec3} The "target" vector object
  86401. */
  86402. Trimesh.prototype.getNormal = function(i, target){
  86403. var i3 = i * 3;
  86404. return target.set(
  86405. this.normals[i3],
  86406. this.normals[i3 + 1],
  86407. this.normals[i3 + 2]
  86408. );
  86409. };
  86410. var cli_aabb = new AABB();
  86411. /**
  86412. * @method calculateLocalInertia
  86413. * @param {Number} mass
  86414. * @param {Vec3} target
  86415. * @return {Vec3} The "target" vector object
  86416. */
  86417. Trimesh.prototype.calculateLocalInertia = function(mass,target){
  86418. // Approximate with box inertia
  86419. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  86420. this.computeLocalAABB(cli_aabb);
  86421. var x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x,
  86422. y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y,
  86423. z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z;
  86424. return target.set(
  86425. 1.0 / 12.0 * mass * ( 2*y*2*y + 2*z*2*z ),
  86426. 1.0 / 12.0 * mass * ( 2*x*2*x + 2*z*2*z ),
  86427. 1.0 / 12.0 * mass * ( 2*y*2*y + 2*x*2*x )
  86428. );
  86429. };
  86430. var computeLocalAABB_worldVert = new Vec3();
  86431. /**
  86432. * Compute the local AABB for the trimesh
  86433. * @method computeLocalAABB
  86434. * @param {AABB} aabb
  86435. */
  86436. Trimesh.prototype.computeLocalAABB = function(aabb){
  86437. var l = aabb.lowerBound,
  86438. u = aabb.upperBound,
  86439. n = this.vertices.length,
  86440. vertices = this.vertices,
  86441. v = computeLocalAABB_worldVert;
  86442. this.getVertex(0, v);
  86443. l.copy(v);
  86444. u.copy(v);
  86445. for(var i=0; i !== n; i++){
  86446. this.getVertex(i, v);
  86447. if(v.x < l.x){
  86448. l.x = v.x;
  86449. } else if(v.x > u.x){
  86450. u.x = v.x;
  86451. }
  86452. if(v.y < l.y){
  86453. l.y = v.y;
  86454. } else if(v.y > u.y){
  86455. u.y = v.y;
  86456. }
  86457. if(v.z < l.z){
  86458. l.z = v.z;
  86459. } else if(v.z > u.z){
  86460. u.z = v.z;
  86461. }
  86462. }
  86463. };
  86464. /**
  86465. * Update the .aabb property
  86466. * @method updateAABB
  86467. */
  86468. Trimesh.prototype.updateAABB = function(){
  86469. this.computeLocalAABB(this.aabb);
  86470. };
  86471. /**
  86472. * Will update the .boundingSphereRadius property
  86473. * @method updateBoundingSphereRadius
  86474. */
  86475. Trimesh.prototype.updateBoundingSphereRadius = function(){
  86476. // Assume points are distributed with local (0,0,0) as center
  86477. var max2 = 0;
  86478. var vertices = this.vertices;
  86479. var v = new Vec3();
  86480. for(var i=0, N=vertices.length / 3; i !== N; i++) {
  86481. this.getVertex(i, v);
  86482. var norm2 = v.norm2();
  86483. if(norm2 > max2){
  86484. max2 = norm2;
  86485. }
  86486. }
  86487. this.boundingSphereRadius = Math.sqrt(max2);
  86488. };
  86489. var tempWorldVertex = new Vec3();
  86490. var calculateWorldAABB_frame = new Transform();
  86491. var calculateWorldAABB_aabb = new AABB();
  86492. /**
  86493. * @method calculateWorldAABB
  86494. * @param {Vec3} pos
  86495. * @param {Quaternion} quat
  86496. * @param {Vec3} min
  86497. * @param {Vec3} max
  86498. */
  86499. Trimesh.prototype.calculateWorldAABB = function(pos,quat,min,max){
  86500. /*
  86501. var n = this.vertices.length / 3,
  86502. verts = this.vertices;
  86503. var minx,miny,minz,maxx,maxy,maxz;
  86504. var v = tempWorldVertex;
  86505. for(var i=0; i<n; i++){
  86506. this.getVertex(i, v);
  86507. quat.vmult(v, v);
  86508. pos.vadd(v, v);
  86509. if (v.x < minx || minx===undefined){
  86510. minx = v.x;
  86511. } else if(v.x > maxx || maxx===undefined){
  86512. maxx = v.x;
  86513. }
  86514. if (v.y < miny || miny===undefined){
  86515. miny = v.y;
  86516. } else if(v.y > maxy || maxy===undefined){
  86517. maxy = v.y;
  86518. }
  86519. if (v.z < minz || minz===undefined){
  86520. minz = v.z;
  86521. } else if(v.z > maxz || maxz===undefined){
  86522. maxz = v.z;
  86523. }
  86524. }
  86525. min.set(minx,miny,minz);
  86526. max.set(maxx,maxy,maxz);
  86527. */
  86528. // Faster approximation using local AABB
  86529. var frame = calculateWorldAABB_frame;
  86530. var result = calculateWorldAABB_aabb;
  86531. frame.position = pos;
  86532. frame.quaternion = quat;
  86533. this.aabb.toWorldFrame(frame, result);
  86534. min.copy(result.lowerBound);
  86535. max.copy(result.upperBound);
  86536. };
  86537. /**
  86538. * Get approximate volume
  86539. * @method volume
  86540. * @return {Number}
  86541. */
  86542. Trimesh.prototype.volume = function(){
  86543. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  86544. };
  86545. /**
  86546. * Create a Trimesh instance, shaped as a torus.
  86547. * @static
  86548. * @method createTorus
  86549. * @param {number} [radius=1]
  86550. * @param {number} [tube=0.5]
  86551. * @param {number} [radialSegments=8]
  86552. * @param {number} [tubularSegments=6]
  86553. * @param {number} [arc=6.283185307179586]
  86554. * @return {Trimesh} A torus
  86555. */
  86556. Trimesh.createTorus = function (radius, tube, radialSegments, tubularSegments, arc) {
  86557. radius = radius || 1;
  86558. tube = tube || 0.5;
  86559. radialSegments = radialSegments || 8;
  86560. tubularSegments = tubularSegments || 6;
  86561. arc = arc || Math.PI * 2;
  86562. var vertices = [];
  86563. var indices = [];
  86564. for ( var j = 0; j <= radialSegments; j ++ ) {
  86565. for ( var i = 0; i <= tubularSegments; i ++ ) {
  86566. var u = i / tubularSegments * arc;
  86567. var v = j / radialSegments * Math.PI * 2;
  86568. var x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  86569. var y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  86570. var z = tube * Math.sin( v );
  86571. vertices.push( x, y, z );
  86572. }
  86573. }
  86574. for ( var j = 1; j <= radialSegments; j ++ ) {
  86575. for ( var i = 1; i <= tubularSegments; i ++ ) {
  86576. var a = ( tubularSegments + 1 ) * j + i - 1;
  86577. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  86578. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  86579. var d = ( tubularSegments + 1 ) * j + i;
  86580. indices.push(a, b, d);
  86581. indices.push(b, c, d);
  86582. }
  86583. }
  86584. return new Trimesh(vertices, indices);
  86585. };
  86586. },{"../collision/AABB":3,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../utils/Octree":50,"./Shape":43}],46:[function(_dereq_,module,exports){
  86587. module.exports = GSSolver;
  86588. var Vec3 = _dereq_('../math/Vec3');
  86589. var Quaternion = _dereq_('../math/Quaternion');
  86590. var Solver = _dereq_('./Solver');
  86591. /**
  86592. * Constraint equation Gauss-Seidel solver.
  86593. * @class GSSolver
  86594. * @constructor
  86595. * @todo The spook parameters should be specified for each constraint, not globally.
  86596. * @author schteppe / https://github.com/schteppe
  86597. * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf
  86598. * @extends Solver
  86599. */
  86600. function GSSolver(){
  86601. Solver.call(this);
  86602. /**
  86603. * The number of solver iterations determines quality of the constraints in the world. The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.
  86604. * @property iterations
  86605. * @type {Number}
  86606. * @todo write more about solver and iterations in the wiki
  86607. */
  86608. this.iterations = 10;
  86609. /**
  86610. * When tolerance is reached, the system is assumed to be converged.
  86611. * @property tolerance
  86612. * @type {Number}
  86613. */
  86614. this.tolerance = 1e-7;
  86615. }
  86616. GSSolver.prototype = new Solver();
  86617. var GSSolver_solve_lambda = []; // Just temporary number holders that we want to reuse each solve.
  86618. var GSSolver_solve_invCs = [];
  86619. var GSSolver_solve_Bs = [];
  86620. GSSolver.prototype.solve = function(dt,world){
  86621. var iter = 0,
  86622. maxIter = this.iterations,
  86623. tolSquared = this.tolerance*this.tolerance,
  86624. equations = this.equations,
  86625. Neq = equations.length,
  86626. bodies = world.bodies,
  86627. Nbodies = bodies.length,
  86628. h = dt,
  86629. q, B, invC, deltalambda, deltalambdaTot, GWlambda, lambdaj;
  86630. // Update solve mass
  86631. if(Neq !== 0){
  86632. for(var i=0; i!==Nbodies; i++){
  86633. bodies[i].updateSolveMassProperties();
  86634. }
  86635. }
  86636. // Things that does not change during iteration can be computed once
  86637. var invCs = GSSolver_solve_invCs,
  86638. Bs = GSSolver_solve_Bs,
  86639. lambda = GSSolver_solve_lambda;
  86640. invCs.length = Neq;
  86641. Bs.length = Neq;
  86642. lambda.length = Neq;
  86643. for(var i=0; i!==Neq; i++){
  86644. var c = equations[i];
  86645. lambda[i] = 0.0;
  86646. Bs[i] = c.computeB(h);
  86647. invCs[i] = 1.0 / c.computeC();
  86648. }
  86649. if(Neq !== 0){
  86650. // Reset vlambda
  86651. for(var i=0; i!==Nbodies; i++){
  86652. var b=bodies[i],
  86653. vlambda=b.vlambda,
  86654. wlambda=b.wlambda;
  86655. vlambda.set(0,0,0);
  86656. if(wlambda){
  86657. wlambda.set(0,0,0);
  86658. }
  86659. }
  86660. // Iterate over equations
  86661. for(iter=0; iter!==maxIter; iter++){
  86662. // Accumulate the total error for each iteration.
  86663. deltalambdaTot = 0.0;
  86664. for(var j=0; j!==Neq; j++){
  86665. var c = equations[j];
  86666. // Compute iteration
  86667. B = Bs[j];
  86668. invC = invCs[j];
  86669. lambdaj = lambda[j];
  86670. GWlambda = c.computeGWlambda();
  86671. deltalambda = invC * ( B - GWlambda - c.eps * lambdaj );
  86672. // Clamp if we are not within the min/max interval
  86673. if(lambdaj + deltalambda < c.minForce){
  86674. deltalambda = c.minForce - lambdaj;
  86675. } else if(lambdaj + deltalambda > c.maxForce){
  86676. deltalambda = c.maxForce - lambdaj;
  86677. }
  86678. lambda[j] += deltalambda;
  86679. deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda)
  86680. c.addToWlambda(deltalambda);
  86681. }
  86682. // If the total error is small enough - stop iterate
  86683. if(deltalambdaTot*deltalambdaTot < tolSquared){
  86684. break;
  86685. }
  86686. }
  86687. // Add result to velocity
  86688. for(var i=0; i!==Nbodies; i++){
  86689. var b=bodies[i],
  86690. v=b.velocity,
  86691. w=b.angularVelocity;
  86692. v.vadd(b.vlambda, v);
  86693. if(w){
  86694. w.vadd(b.wlambda, w);
  86695. }
  86696. }
  86697. }
  86698. return iter;
  86699. };
  86700. },{"../math/Quaternion":28,"../math/Vec3":30,"./Solver":47}],47:[function(_dereq_,module,exports){
  86701. module.exports = Solver;
  86702. /**
  86703. * Constraint equation solver base class.
  86704. * @class Solver
  86705. * @constructor
  86706. * @author schteppe / https://github.com/schteppe
  86707. */
  86708. function Solver(){
  86709. /**
  86710. * All equations to be solved
  86711. * @property {Array} equations
  86712. */
  86713. this.equations = [];
  86714. }
  86715. /**
  86716. * Should be implemented in subclasses!
  86717. * @method solve
  86718. * @param {Number} dt
  86719. * @param {World} world
  86720. */
  86721. Solver.prototype.solve = function(dt,world){
  86722. // Should return the number of iterations done!
  86723. return 0;
  86724. };
  86725. /**
  86726. * Add an equation
  86727. * @method addEquation
  86728. * @param {Equation} eq
  86729. */
  86730. Solver.prototype.addEquation = function(eq){
  86731. if (eq.enabled) {
  86732. this.equations.push(eq);
  86733. }
  86734. };
  86735. /**
  86736. * Remove an equation
  86737. * @method removeEquation
  86738. * @param {Equation} eq
  86739. */
  86740. Solver.prototype.removeEquation = function(eq){
  86741. var eqs = this.equations;
  86742. var i = eqs.indexOf(eq);
  86743. if(i !== -1){
  86744. eqs.splice(i,1);
  86745. }
  86746. };
  86747. /**
  86748. * Add all equations
  86749. * @method removeAllEquations
  86750. */
  86751. Solver.prototype.removeAllEquations = function(){
  86752. this.equations.length = 0;
  86753. };
  86754. },{}],48:[function(_dereq_,module,exports){
  86755. module.exports = SplitSolver;
  86756. var Vec3 = _dereq_('../math/Vec3');
  86757. var Quaternion = _dereq_('../math/Quaternion');
  86758. var Solver = _dereq_('./Solver');
  86759. var Body = _dereq_('../objects/Body');
  86760. /**
  86761. * Splits the equations into islands and solves them independently. Can improve performance.
  86762. * @class SplitSolver
  86763. * @constructor
  86764. * @extends Solver
  86765. * @param {Solver} subsolver
  86766. */
  86767. function SplitSolver(subsolver){
  86768. Solver.call(this);
  86769. this.iterations = 10;
  86770. this.tolerance = 1e-7;
  86771. this.subsolver = subsolver;
  86772. this.nodes = [];
  86773. this.nodePool = [];
  86774. // Create needed nodes, reuse if possible
  86775. while(this.nodePool.length < 128){
  86776. this.nodePool.push(this.createNode());
  86777. }
  86778. }
  86779. SplitSolver.prototype = new Solver();
  86780. // Returns the number of subsystems
  86781. var SplitSolver_solve_nodes = []; // All allocated node objects
  86782. var SplitSolver_solve_nodePool = []; // All allocated node objects
  86783. var SplitSolver_solve_eqs = []; // Temp array
  86784. var SplitSolver_solve_bds = []; // Temp array
  86785. var SplitSolver_solve_dummyWorld = {bodies:[]}; // Temp object
  86786. var STATIC = Body.STATIC;
  86787. function getUnvisitedNode(nodes){
  86788. var Nnodes = nodes.length;
  86789. for(var i=0; i!==Nnodes; i++){
  86790. var node = nodes[i];
  86791. if(!node.visited && !(node.body.type & STATIC)){
  86792. return node;
  86793. }
  86794. }
  86795. return false;
  86796. }
  86797. var queue = [];
  86798. function bfs(root,visitFunc,bds,eqs){
  86799. queue.push(root);
  86800. root.visited = true;
  86801. visitFunc(root,bds,eqs);
  86802. while(queue.length) {
  86803. var node = queue.pop();
  86804. // Loop over unvisited child nodes
  86805. var child;
  86806. while((child = getUnvisitedNode(node.children))) {
  86807. child.visited = true;
  86808. visitFunc(child,bds,eqs);
  86809. queue.push(child);
  86810. }
  86811. }
  86812. }
  86813. function visitFunc(node,bds,eqs){
  86814. bds.push(node.body);
  86815. var Neqs = node.eqs.length;
  86816. for(var i=0; i!==Neqs; i++){
  86817. var eq = node.eqs[i];
  86818. if(eqs.indexOf(eq) === -1){
  86819. eqs.push(eq);
  86820. }
  86821. }
  86822. }
  86823. SplitSolver.prototype.createNode = function(){
  86824. return { body:null, children:[], eqs:[], visited:false };
  86825. };
  86826. /**
  86827. * Solve the subsystems
  86828. * @method solve
  86829. * @param {Number} dt
  86830. * @param {World} world
  86831. */
  86832. SplitSolver.prototype.solve = function(dt,world){
  86833. var nodes=SplitSolver_solve_nodes,
  86834. nodePool=this.nodePool,
  86835. bodies=world.bodies,
  86836. equations=this.equations,
  86837. Neq=equations.length,
  86838. Nbodies=bodies.length,
  86839. subsolver=this.subsolver;
  86840. // Create needed nodes, reuse if possible
  86841. while(nodePool.length < Nbodies){
  86842. nodePool.push(this.createNode());
  86843. }
  86844. nodes.length = Nbodies;
  86845. for (var i = 0; i < Nbodies; i++) {
  86846. nodes[i] = nodePool[i];
  86847. }
  86848. // Reset node values
  86849. for(var i=0; i!==Nbodies; i++){
  86850. var node = nodes[i];
  86851. node.body = bodies[i];
  86852. node.children.length = 0;
  86853. node.eqs.length = 0;
  86854. node.visited = false;
  86855. }
  86856. for(var k=0; k!==Neq; k++){
  86857. var eq=equations[k],
  86858. i=bodies.indexOf(eq.bi),
  86859. j=bodies.indexOf(eq.bj),
  86860. ni=nodes[i],
  86861. nj=nodes[j];
  86862. ni.children.push(nj);
  86863. ni.eqs.push(eq);
  86864. nj.children.push(ni);
  86865. nj.eqs.push(eq);
  86866. }
  86867. var child, n=0, eqs=SplitSolver_solve_eqs;
  86868. subsolver.tolerance = this.tolerance;
  86869. subsolver.iterations = this.iterations;
  86870. var dummyWorld = SplitSolver_solve_dummyWorld;
  86871. while((child = getUnvisitedNode(nodes))){
  86872. eqs.length = 0;
  86873. dummyWorld.bodies.length = 0;
  86874. bfs(child, visitFunc, dummyWorld.bodies, eqs);
  86875. var Neqs = eqs.length;
  86876. eqs = eqs.sort(sortById);
  86877. for(var i=0; i!==Neqs; i++){
  86878. subsolver.addEquation(eqs[i]);
  86879. }
  86880. var iter = subsolver.solve(dt,dummyWorld);
  86881. subsolver.removeAllEquations();
  86882. n++;
  86883. }
  86884. return n;
  86885. };
  86886. function sortById(a, b){
  86887. return b.id - a.id;
  86888. }
  86889. },{"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"./Solver":47}],49:[function(_dereq_,module,exports){
  86890. /**
  86891. * Base class for objects that dispatches events.
  86892. * @class EventTarget
  86893. * @constructor
  86894. */
  86895. var EventTarget = function () {
  86896. };
  86897. module.exports = EventTarget;
  86898. EventTarget.prototype = {
  86899. constructor: EventTarget,
  86900. /**
  86901. * Add an event listener
  86902. * @method addEventListener
  86903. * @param {String} type
  86904. * @param {Function} listener
  86905. * @return {EventTarget} The self object, for chainability.
  86906. */
  86907. addEventListener: function ( type, listener ) {
  86908. if ( this._listeners === undefined ){ this._listeners = {}; }
  86909. var listeners = this._listeners;
  86910. if ( listeners[ type ] === undefined ) {
  86911. listeners[ type ] = [];
  86912. }
  86913. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  86914. listeners[ type ].push( listener );
  86915. }
  86916. return this;
  86917. },
  86918. /**
  86919. * Check if an event listener is added
  86920. * @method hasEventListener
  86921. * @param {String} type
  86922. * @param {Function} listener
  86923. * @return {Boolean}
  86924. */
  86925. hasEventListener: function ( type, listener ) {
  86926. if ( this._listeners === undefined ){ return false; }
  86927. var listeners = this._listeners;
  86928. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  86929. return true;
  86930. }
  86931. return false;
  86932. },
  86933. /**
  86934. * Remove an event listener
  86935. * @method removeEventListener
  86936. * @param {String} type
  86937. * @param {Function} listener
  86938. * @return {EventTarget} The self object, for chainability.
  86939. */
  86940. removeEventListener: function ( type, listener ) {
  86941. if ( this._listeners === undefined ){ return this; }
  86942. var listeners = this._listeners;
  86943. if ( listeners[type] === undefined ){ return this; }
  86944. var index = listeners[ type ].indexOf( listener );
  86945. if ( index !== - 1 ) {
  86946. listeners[ type ].splice( index, 1 );
  86947. }
  86948. return this;
  86949. },
  86950. /**
  86951. * Emit an event.
  86952. * @method dispatchEvent
  86953. * @param {Object} event
  86954. * @param {String} event.type
  86955. * @return {EventTarget} The self object, for chainability.
  86956. */
  86957. dispatchEvent: function ( event ) {
  86958. if ( this._listeners === undefined ){ return this; }
  86959. var listeners = this._listeners;
  86960. var listenerArray = listeners[ event.type ];
  86961. if ( listenerArray !== undefined ) {
  86962. event.target = this;
  86963. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  86964. listenerArray[ i ].call( this, event );
  86965. }
  86966. }
  86967. return this;
  86968. }
  86969. };
  86970. },{}],50:[function(_dereq_,module,exports){
  86971. var AABB = _dereq_('../collision/AABB');
  86972. var Vec3 = _dereq_('../math/Vec3');
  86973. module.exports = Octree;
  86974. /**
  86975. * @class OctreeNode
  86976. * @param {object} [options]
  86977. * @param {Octree} [options.root]
  86978. * @param {AABB} [options.aabb]
  86979. */
  86980. function OctreeNode(options){
  86981. options = options || {};
  86982. /**
  86983. * The root node
  86984. * @property {OctreeNode} root
  86985. */
  86986. this.root = options.root || null;
  86987. /**
  86988. * Boundary of this node
  86989. * @property {AABB} aabb
  86990. */
  86991. this.aabb = options.aabb ? options.aabb.clone() : new AABB();
  86992. /**
  86993. * Contained data at the current node level.
  86994. * @property {Array} data
  86995. */
  86996. this.data = [];
  86997. /**
  86998. * Children to this node
  86999. * @property {Array} children
  87000. */
  87001. this.children = [];
  87002. }
  87003. /**
  87004. * @class Octree
  87005. * @param {AABB} aabb The total AABB of the tree
  87006. * @param {object} [options]
  87007. * @param {number} [options.maxDepth=8]
  87008. * @extends OctreeNode
  87009. */
  87010. function Octree(aabb, options){
  87011. options = options || {};
  87012. options.root = null;
  87013. options.aabb = aabb;
  87014. OctreeNode.call(this, options);
  87015. /**
  87016. * Maximum subdivision depth
  87017. * @property {number} maxDepth
  87018. */
  87019. this.maxDepth = typeof(options.maxDepth) !== 'undefined' ? options.maxDepth : 8;
  87020. }
  87021. Octree.prototype = new OctreeNode();
  87022. OctreeNode.prototype.reset = function(aabb, options){
  87023. this.children.length = this.data.length = 0;
  87024. };
  87025. /**
  87026. * Insert data into this node
  87027. * @method insert
  87028. * @param {AABB} aabb
  87029. * @param {object} elementData
  87030. * @return {boolean} True if successful, otherwise false
  87031. */
  87032. OctreeNode.prototype.insert = function(aabb, elementData, level){
  87033. var nodeData = this.data;
  87034. level = level || 0;
  87035. // Ignore objects that do not belong in this node
  87036. if (!this.aabb.contains(aabb)){
  87037. return false; // object cannot be added
  87038. }
  87039. var children = this.children;
  87040. if(level < (this.maxDepth || this.root.maxDepth)){
  87041. // Subdivide if there are no children yet
  87042. var subdivided = false;
  87043. if (!children.length){
  87044. this.subdivide();
  87045. subdivided = true;
  87046. }
  87047. // add to whichever node will accept it
  87048. for (var i = 0; i !== 8; i++) {
  87049. if (children[i].insert(aabb, elementData, level + 1)){
  87050. return true;
  87051. }
  87052. }
  87053. if(subdivided){
  87054. // No children accepted! Might as well just remove em since they contain none
  87055. children.length = 0;
  87056. }
  87057. }
  87058. // Too deep, or children didnt want it. add it in current node
  87059. nodeData.push(elementData);
  87060. return true;
  87061. };
  87062. var halfDiagonal = new Vec3();
  87063. /**
  87064. * Create 8 equally sized children nodes and put them in the .children array.
  87065. * @method subdivide
  87066. */
  87067. OctreeNode.prototype.subdivide = function() {
  87068. var aabb = this.aabb;
  87069. var l = aabb.lowerBound;
  87070. var u = aabb.upperBound;
  87071. var children = this.children;
  87072. children.push(
  87073. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,0,0) }) }),
  87074. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,0,0) }) }),
  87075. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,1,0) }) }),
  87076. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,1,1) }) }),
  87077. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,1,1) }) }),
  87078. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,0,1) }) }),
  87079. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,0,1) }) }),
  87080. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,1,0) }) })
  87081. );
  87082. u.vsub(l, halfDiagonal);
  87083. halfDiagonal.scale(0.5, halfDiagonal);
  87084. var root = this.root || this;
  87085. for (var i = 0; i !== 8; i++) {
  87086. var child = children[i];
  87087. // Set current node as root
  87088. child.root = root;
  87089. // Compute bounds
  87090. var lowerBound = child.aabb.lowerBound;
  87091. lowerBound.x *= halfDiagonal.x;
  87092. lowerBound.y *= halfDiagonal.y;
  87093. lowerBound.z *= halfDiagonal.z;
  87094. lowerBound.vadd(l, lowerBound);
  87095. // Upper bound is always lower bound + halfDiagonal
  87096. lowerBound.vadd(halfDiagonal, child.aabb.upperBound);
  87097. }
  87098. };
  87099. /**
  87100. * Get all data, potentially within an AABB
  87101. * @method aabbQuery
  87102. * @param {AABB} aabb
  87103. * @param {array} result
  87104. * @return {array} The "result" object
  87105. */
  87106. OctreeNode.prototype.aabbQuery = function(aabb, result) {
  87107. var nodeData = this.data;
  87108. // abort if the range does not intersect this node
  87109. // if (!this.aabb.overlaps(aabb)){
  87110. // return result;
  87111. // }
  87112. // Add objects at this level
  87113. // Array.prototype.push.apply(result, nodeData);
  87114. // Add child data
  87115. // @todo unwrap recursion into a queue / loop, that's faster in JS
  87116. var children = this.children;
  87117. // for (var i = 0, N = this.children.length; i !== N; i++) {
  87118. // children[i].aabbQuery(aabb, result);
  87119. // }
  87120. var queue = [this];
  87121. while (queue.length) {
  87122. var node = queue.pop();
  87123. if (node.aabb.overlaps(aabb)){
  87124. Array.prototype.push.apply(result, node.data);
  87125. }
  87126. Array.prototype.push.apply(queue, node.children);
  87127. }
  87128. return result;
  87129. };
  87130. var tmpAABB = new AABB();
  87131. /**
  87132. * Get all data, potentially intersected by a ray.
  87133. * @method rayQuery
  87134. * @param {Ray} ray
  87135. * @param {Transform} treeTransform
  87136. * @param {array} result
  87137. * @return {array} The "result" object
  87138. */
  87139. OctreeNode.prototype.rayQuery = function(ray, treeTransform, result) {
  87140. // Use aabb query for now.
  87141. // @todo implement real ray query which needs less lookups
  87142. ray.getAABB(tmpAABB);
  87143. tmpAABB.toLocalFrame(treeTransform, tmpAABB);
  87144. this.aabbQuery(tmpAABB, result);
  87145. return result;
  87146. };
  87147. /**
  87148. * @method removeEmptyNodes
  87149. */
  87150. OctreeNode.prototype.removeEmptyNodes = function() {
  87151. var queue = [this];
  87152. while (queue.length) {
  87153. var node = queue.pop();
  87154. for (var i = node.children.length - 1; i >= 0; i--) {
  87155. if(!node.children[i].data.length){
  87156. node.children.splice(i, 1);
  87157. }
  87158. }
  87159. Array.prototype.push.apply(queue, node.children);
  87160. }
  87161. };
  87162. },{"../collision/AABB":3,"../math/Vec3":30}],51:[function(_dereq_,module,exports){
  87163. module.exports = Pool;
  87164. /**
  87165. * For pooling objects that can be reused.
  87166. * @class Pool
  87167. * @constructor
  87168. */
  87169. function Pool(){
  87170. /**
  87171. * The pooled objects
  87172. * @property {Array} objects
  87173. */
  87174. this.objects = [];
  87175. /**
  87176. * Constructor of the objects
  87177. * @property {mixed} type
  87178. */
  87179. this.type = Object;
  87180. }
  87181. /**
  87182. * Release an object after use
  87183. * @method release
  87184. * @param {Object} obj
  87185. */
  87186. Pool.prototype.release = function(){
  87187. var Nargs = arguments.length;
  87188. for(var i=0; i!==Nargs; i++){
  87189. this.objects.push(arguments[i]);
  87190. }
  87191. };
  87192. /**
  87193. * Get an object
  87194. * @method get
  87195. * @return {mixed}
  87196. */
  87197. Pool.prototype.get = function(){
  87198. if(this.objects.length===0){
  87199. return this.constructObject();
  87200. } else {
  87201. return this.objects.pop();
  87202. }
  87203. };
  87204. /**
  87205. * Construct an object. Should be implmented in each subclass.
  87206. * @method constructObject
  87207. * @return {mixed}
  87208. */
  87209. Pool.prototype.constructObject = function(){
  87210. throw new Error("constructObject() not implemented in this Pool subclass yet!");
  87211. };
  87212. },{}],52:[function(_dereq_,module,exports){
  87213. module.exports = TupleDictionary;
  87214. /**
  87215. * @class TupleDictionary
  87216. * @constructor
  87217. */
  87218. function TupleDictionary() {
  87219. /**
  87220. * The data storage
  87221. * @property data
  87222. * @type {Object}
  87223. */
  87224. this.data = { keys:[] };
  87225. }
  87226. /**
  87227. * @method get
  87228. * @param {Number} i
  87229. * @param {Number} j
  87230. * @return {Number}
  87231. */
  87232. TupleDictionary.prototype.get = function(i, j) {
  87233. if (i > j) {
  87234. // swap
  87235. var temp = j;
  87236. j = i;
  87237. i = temp;
  87238. }
  87239. return this.data[i+'-'+j];
  87240. };
  87241. /**
  87242. * @method set
  87243. * @param {Number} i
  87244. * @param {Number} j
  87245. * @param {Number} value
  87246. */
  87247. TupleDictionary.prototype.set = function(i, j, value) {
  87248. if (i > j) {
  87249. var temp = j;
  87250. j = i;
  87251. i = temp;
  87252. }
  87253. var key = i+'-'+j;
  87254. // Check if key already exists
  87255. if(!this.get(i,j)){
  87256. this.data.keys.push(key);
  87257. }
  87258. this.data[key] = value;
  87259. };
  87260. /**
  87261. * @method reset
  87262. */
  87263. TupleDictionary.prototype.reset = function() {
  87264. var data = this.data,
  87265. keys = data.keys;
  87266. while(keys.length > 0){
  87267. var key = keys.pop();
  87268. delete data[key];
  87269. }
  87270. };
  87271. },{}],53:[function(_dereq_,module,exports){
  87272. function Utils(){}
  87273. module.exports = Utils;
  87274. /**
  87275. * Extend an options object with default values.
  87276. * @static
  87277. * @method defaults
  87278. * @param {object} options The options object. May be falsy: in this case, a new object is created and returned.
  87279. * @param {object} defaults An object containing default values.
  87280. * @return {object} The modified options object.
  87281. */
  87282. Utils.defaults = function(options, defaults){
  87283. options = options || {};
  87284. for(var key in defaults){
  87285. if(!(key in options)){
  87286. options[key] = defaults[key];
  87287. }
  87288. }
  87289. return options;
  87290. };
  87291. },{}],54:[function(_dereq_,module,exports){
  87292. module.exports = Vec3Pool;
  87293. var Vec3 = _dereq_('../math/Vec3');
  87294. var Pool = _dereq_('./Pool');
  87295. /**
  87296. * @class Vec3Pool
  87297. * @constructor
  87298. * @extends Pool
  87299. */
  87300. function Vec3Pool(){
  87301. Pool.call(this);
  87302. this.type = Vec3;
  87303. }
  87304. Vec3Pool.prototype = new Pool();
  87305. /**
  87306. * Construct a vector
  87307. * @method constructObject
  87308. * @return {Vec3}
  87309. */
  87310. Vec3Pool.prototype.constructObject = function(){
  87311. return new Vec3();
  87312. };
  87313. },{"../math/Vec3":30,"./Pool":51}],55:[function(_dereq_,module,exports){
  87314. module.exports = Narrowphase;
  87315. var AABB = _dereq_('../collision/AABB');
  87316. var Shape = _dereq_('../shapes/Shape');
  87317. var Ray = _dereq_('../collision/Ray');
  87318. var Vec3 = _dereq_('../math/Vec3');
  87319. var Transform = _dereq_('../math/Transform');
  87320. var ConvexPolyhedron = _dereq_('../shapes/ConvexPolyhedron');
  87321. var Quaternion = _dereq_('../math/Quaternion');
  87322. var Solver = _dereq_('../solver/Solver');
  87323. var Vec3Pool = _dereq_('../utils/Vec3Pool');
  87324. var ContactEquation = _dereq_('../equations/ContactEquation');
  87325. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  87326. /**
  87327. * Helper class for the World. Generates ContactEquations.
  87328. * @class Narrowphase
  87329. * @constructor
  87330. * @todo Sphere-ConvexPolyhedron contacts
  87331. * @todo Contact reduction
  87332. * @todo should move methods to prototype
  87333. */
  87334. function Narrowphase(world){
  87335. /**
  87336. * Internal storage of pooled contact points.
  87337. * @property {Array} contactPointPool
  87338. */
  87339. this.contactPointPool = [];
  87340. this.frictionEquationPool = [];
  87341. this.result = [];
  87342. this.frictionResult = [];
  87343. /**
  87344. * Pooled vectors.
  87345. * @property {Vec3Pool} v3pool
  87346. */
  87347. this.v3pool = new Vec3Pool();
  87348. this.world = world;
  87349. this.currentContactMaterial = null;
  87350. /**
  87351. * @property {Boolean} enableFrictionReduction
  87352. */
  87353. this.enableFrictionReduction = false;
  87354. }
  87355. /**
  87356. * Make a contact object, by using the internal pool or creating a new one.
  87357. * @method createContactEquation
  87358. * @return {ContactEquation}
  87359. */
  87360. Narrowphase.prototype.createContactEquation = function(bi, bj, si, sj, rsi, rsj){
  87361. var c;
  87362. if(this.contactPointPool.length){
  87363. c = this.contactPointPool.pop();
  87364. c.bi = bi;
  87365. c.bj = bj;
  87366. } else {
  87367. c = new ContactEquation(bi, bj);
  87368. }
  87369. c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  87370. var cm = this.currentContactMaterial;
  87371. c.restitution = cm.restitution;
  87372. c.setSpookParams(
  87373. cm.contactEquationStiffness,
  87374. cm.contactEquationRelaxation,
  87375. this.world.dt
  87376. );
  87377. var matA = si.material || bi.material;
  87378. var matB = sj.material || bj.material;
  87379. if(matA && matB && matA.restitution >= 0 && matB.restitution >= 0){
  87380. c.restitution = matA.restitution * matB.restitution;
  87381. }
  87382. c.si = rsi || si;
  87383. c.sj = rsj || sj;
  87384. return c;
  87385. };
  87386. Narrowphase.prototype.createFrictionEquationsFromContact = function(contactEquation, outArray){
  87387. var bodyA = contactEquation.bi;
  87388. var bodyB = contactEquation.bj;
  87389. var shapeA = contactEquation.si;
  87390. var shapeB = contactEquation.sj;
  87391. var world = this.world;
  87392. var cm = this.currentContactMaterial;
  87393. // If friction or restitution were specified in the material, use them
  87394. var friction = cm.friction;
  87395. var matA = shapeA.material || bodyA.material;
  87396. var matB = shapeB.material || bodyB.material;
  87397. if(matA && matB && matA.friction >= 0 && matB.friction >= 0){
  87398. friction = matA.friction * matB.friction;
  87399. }
  87400. if(friction > 0){
  87401. // Create 2 tangent equations
  87402. var mug = friction * world.gravity.length();
  87403. var reducedMass = (bodyA.invMass + bodyB.invMass);
  87404. if(reducedMass > 0){
  87405. reducedMass = 1/reducedMass;
  87406. }
  87407. var pool = this.frictionEquationPool;
  87408. var c1 = pool.length ? pool.pop() : new FrictionEquation(bodyA,bodyB,mug*reducedMass);
  87409. var c2 = pool.length ? pool.pop() : new FrictionEquation(bodyA,bodyB,mug*reducedMass);
  87410. c1.bi = c2.bi = bodyA;
  87411. c1.bj = c2.bj = bodyB;
  87412. c1.minForce = c2.minForce = -mug*reducedMass;
  87413. c1.maxForce = c2.maxForce = mug*reducedMass;
  87414. // Copy over the relative vectors
  87415. c1.ri.copy(contactEquation.ri);
  87416. c1.rj.copy(contactEquation.rj);
  87417. c2.ri.copy(contactEquation.ri);
  87418. c2.rj.copy(contactEquation.rj);
  87419. // Construct tangents
  87420. contactEquation.ni.tangents(c1.t, c2.t);
  87421. // Set spook params
  87422. c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  87423. c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  87424. c1.enabled = c2.enabled = contactEquation.enabled;
  87425. outArray.push(c1, c2);
  87426. return true;
  87427. }
  87428. return false;
  87429. };
  87430. var averageNormal = new Vec3();
  87431. var averageContactPointA = new Vec3();
  87432. var averageContactPointB = new Vec3();
  87433. // Take the average N latest contact point on the plane.
  87434. Narrowphase.prototype.createFrictionFromAverage = function(numContacts){
  87435. // The last contactEquation
  87436. var c = this.result[this.result.length - 1];
  87437. // Create the result: two "average" friction equations
  87438. if (!this.createFrictionEquationsFromContact(c, this.frictionResult) || numContacts === 1) {
  87439. return;
  87440. }
  87441. var f1 = this.frictionResult[this.frictionResult.length - 2];
  87442. var f2 = this.frictionResult[this.frictionResult.length - 1];
  87443. averageNormal.setZero();
  87444. averageContactPointA.setZero();
  87445. averageContactPointB.setZero();
  87446. var bodyA = c.bi;
  87447. var bodyB = c.bj;
  87448. for(var i=0; i!==numContacts; i++){
  87449. c = this.result[this.result.length - 1 - i];
  87450. if(c.bodyA !== bodyA){
  87451. averageNormal.vadd(c.ni, averageNormal); // vec2.add(eq.t, eq.t, c.normalA);
  87452. averageContactPointA.vadd(c.ri, averageContactPointA); // vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointA);
  87453. averageContactPointB.vadd(c.rj, averageContactPointB);
  87454. } else {
  87455. averageNormal.vsub(c.ni, averageNormal); // vec2.sub(eq.t, eq.t, c.normalA);
  87456. averageContactPointA.vadd(c.rj, averageContactPointA); // vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointA);
  87457. averageContactPointB.vadd(c.ri, averageContactPointB);
  87458. }
  87459. }
  87460. var invNumContacts = 1 / numContacts;
  87461. averageContactPointA.scale(invNumContacts, f1.ri); // vec2.scale(eq.contactPointA, eq.contactPointA, invNumContacts);
  87462. averageContactPointB.scale(invNumContacts, f1.rj); // vec2.scale(eq.contactPointB, eq.contactPointB, invNumContacts);
  87463. f2.ri.copy(f1.ri); // Should be the same
  87464. f2.rj.copy(f1.rj);
  87465. averageNormal.normalize();
  87466. averageNormal.tangents(f1.t, f2.t);
  87467. // return eq;
  87468. };
  87469. var tmpVec1 = new Vec3();
  87470. var tmpVec2 = new Vec3();
  87471. var tmpQuat1 = new Quaternion();
  87472. var tmpQuat2 = new Quaternion();
  87473. /**
  87474. * Generate all contacts between a list of body pairs
  87475. * @method getContacts
  87476. * @param {array} p1 Array of body indices
  87477. * @param {array} p2 Array of body indices
  87478. * @param {World} world
  87479. * @param {array} result Array to store generated contacts
  87480. * @param {array} oldcontacts Optional. Array of reusable contact objects
  87481. */
  87482. Narrowphase.prototype.getContacts = function(p1, p2, world, result, oldcontacts, frictionResult, frictionPool){
  87483. // Save old contact objects
  87484. this.contactPointPool = oldcontacts;
  87485. this.frictionEquationPool = frictionPool;
  87486. this.result = result;
  87487. this.frictionResult = frictionResult;
  87488. var qi = tmpQuat1;
  87489. var qj = tmpQuat2;
  87490. var xi = tmpVec1;
  87491. var xj = tmpVec2;
  87492. for(var k=0, N=p1.length; k!==N; k++){
  87493. // Get current collision bodies
  87494. var bi = p1[k],
  87495. bj = p2[k];
  87496. // Get contact material
  87497. var bodyContactMaterial = null;
  87498. if(bi.material && bj.material){
  87499. bodyContactMaterial = world.getContactMaterial(bi.material,bj.material) || null;
  87500. }
  87501. for (var i = 0; i < bi.shapes.length; i++) {
  87502. bi.quaternion.mult(bi.shapeOrientations[i], qi);
  87503. bi.quaternion.vmult(bi.shapeOffsets[i], xi);
  87504. xi.vadd(bi.position, xi);
  87505. var si = bi.shapes[i];
  87506. for (var j = 0; j < bj.shapes.length; j++) {
  87507. // Compute world transform of shapes
  87508. bj.quaternion.mult(bj.shapeOrientations[j], qj);
  87509. bj.quaternion.vmult(bj.shapeOffsets[j], xj);
  87510. xj.vadd(bj.position, xj);
  87511. var sj = bj.shapes[j];
  87512. if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  87513. continue;
  87514. }
  87515. // Get collision material
  87516. var shapeContactMaterial = null;
  87517. if(si.material && sj.material){
  87518. shapeContactMaterial = world.getContactMaterial(si.material,sj.material) || null;
  87519. }
  87520. this.currentContactMaterial = shapeContactMaterial || bodyContactMaterial || world.defaultContactMaterial;
  87521. // Get contacts
  87522. var resolver = this[si.type | sj.type];
  87523. if(resolver){
  87524. if (si.type < sj.type) {
  87525. resolver.call(this, si, sj, xi, xj, qi, qj, bi, bj, si, sj);
  87526. } else {
  87527. resolver.call(this, sj, si, xj, xi, qj, qi, bj, bi, si, sj);
  87528. }
  87529. }
  87530. }
  87531. }
  87532. }
  87533. };
  87534. var numWarnings = 0;
  87535. var maxWarnings = 10;
  87536. function warn(msg){
  87537. if(numWarnings > maxWarnings){
  87538. return;
  87539. }
  87540. numWarnings++;
  87541. console.warn(msg);
  87542. }
  87543. Narrowphase.prototype[Shape.types.BOX | Shape.types.BOX] =
  87544. Narrowphase.prototype.boxBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  87545. si.convexPolyhedronRepresentation.material = si.material;
  87546. sj.convexPolyhedronRepresentation.material = sj.material;
  87547. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  87548. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  87549. this.convexConvex(si.convexPolyhedronRepresentation,sj.convexPolyhedronRepresentation,xi,xj,qi,qj,bi,bj,si,sj);
  87550. };
  87551. Narrowphase.prototype[Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON] =
  87552. Narrowphase.prototype.boxConvex = function(si,sj,xi,xj,qi,qj,bi,bj){
  87553. si.convexPolyhedronRepresentation.material = si.material;
  87554. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  87555. this.convexConvex(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj);
  87556. };
  87557. Narrowphase.prototype[Shape.types.BOX | Shape.types.PARTICLE] =
  87558. Narrowphase.prototype.boxParticle = function(si,sj,xi,xj,qi,qj,bi,bj){
  87559. si.convexPolyhedronRepresentation.material = si.material;
  87560. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  87561. this.convexParticle(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj);
  87562. };
  87563. /**
  87564. * @method sphereSphere
  87565. * @param {Shape} si
  87566. * @param {Shape} sj
  87567. * @param {Vec3} xi
  87568. * @param {Vec3} xj
  87569. * @param {Quaternion} qi
  87570. * @param {Quaternion} qj
  87571. * @param {Body} bi
  87572. * @param {Body} bj
  87573. */
  87574. Narrowphase.prototype[Shape.types.SPHERE] =
  87575. Narrowphase.prototype.sphereSphere = function(si,sj,xi,xj,qi,qj,bi,bj){
  87576. // We will have only one contact in this case
  87577. var r = this.createContactEquation(bi,bj,si,sj);
  87578. // Contact normal
  87579. xj.vsub(xi, r.ni);
  87580. r.ni.normalize();
  87581. // Contact point locations
  87582. r.ri.copy(r.ni);
  87583. r.rj.copy(r.ni);
  87584. r.ri.mult(si.radius, r.ri);
  87585. r.rj.mult(-sj.radius, r.rj);
  87586. r.ri.vadd(xi, r.ri);
  87587. r.ri.vsub(bi.position, r.ri);
  87588. r.rj.vadd(xj, r.rj);
  87589. r.rj.vsub(bj.position, r.rj);
  87590. this.result.push(r);
  87591. this.createFrictionEquationsFromContact(r, this.frictionResult);
  87592. };
  87593. /**
  87594. * @method planeTrimesh
  87595. * @param {Shape} si
  87596. * @param {Shape} sj
  87597. * @param {Vec3} xi
  87598. * @param {Vec3} xj
  87599. * @param {Quaternion} qi
  87600. * @param {Quaternion} qj
  87601. * @param {Body} bi
  87602. * @param {Body} bj
  87603. */
  87604. var planeTrimesh_normal = new Vec3();
  87605. var planeTrimesh_relpos = new Vec3();
  87606. var planeTrimesh_projected = new Vec3();
  87607. Narrowphase.prototype[Shape.types.PLANE | Shape.types.TRIMESH] =
  87608. Narrowphase.prototype.planeTrimesh = function(
  87609. planeShape,
  87610. trimeshShape,
  87611. planePos,
  87612. trimeshPos,
  87613. planeQuat,
  87614. trimeshQuat,
  87615. planeBody,
  87616. trimeshBody
  87617. ){
  87618. // Make contacts!
  87619. var v = new Vec3();
  87620. var normal = planeTrimesh_normal;
  87621. normal.set(0,0,1);
  87622. planeQuat.vmult(normal,normal); // Turn normal according to plane
  87623. for(var i=0; i<trimeshShape.vertices.length / 3; i++){
  87624. // Get world vertex from trimesh
  87625. trimeshShape.getVertex(i, v);
  87626. // Safe up
  87627. var v2 = new Vec3();
  87628. v2.copy(v);
  87629. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
  87630. // Check plane side
  87631. var relpos = planeTrimesh_relpos;
  87632. v.vsub(planePos, relpos);
  87633. var dot = normal.dot(relpos);
  87634. if(dot <= 0.0){
  87635. var r = this.createContactEquation(planeBody,trimeshBody,planeShape,trimeshShape);
  87636. r.ni.copy(normal); // Contact normal is the plane normal
  87637. // Get vertex position projected on plane
  87638. var projected = planeTrimesh_projected;
  87639. normal.scale(relpos.dot(normal), projected);
  87640. v.vsub(projected,projected);
  87641. // ri is the projected world position minus plane position
  87642. r.ri.copy(projected);
  87643. r.ri.vsub(planeBody.position, r.ri);
  87644. r.rj.copy(v);
  87645. r.rj.vsub(trimeshBody.position, r.rj);
  87646. // Store result
  87647. this.result.push(r);
  87648. this.createFrictionEquationsFromContact(r, this.frictionResult);
  87649. }
  87650. }
  87651. };
  87652. /**
  87653. * @method sphereTrimesh
  87654. * @param {Shape} sphereShape
  87655. * @param {Shape} trimeshShape
  87656. * @param {Vec3} spherePos
  87657. * @param {Vec3} trimeshPos
  87658. * @param {Quaternion} sphereQuat
  87659. * @param {Quaternion} trimeshQuat
  87660. * @param {Body} sphereBody
  87661. * @param {Body} trimeshBody
  87662. */
  87663. var sphereTrimesh_normal = new Vec3();
  87664. var sphereTrimesh_relpos = new Vec3();
  87665. var sphereTrimesh_projected = new Vec3();
  87666. var sphereTrimesh_v = new Vec3();
  87667. var sphereTrimesh_v2 = new Vec3();
  87668. var sphereTrimesh_edgeVertexA = new Vec3();
  87669. var sphereTrimesh_edgeVertexB = new Vec3();
  87670. var sphereTrimesh_edgeVector = new Vec3();
  87671. var sphereTrimesh_edgeVectorUnit = new Vec3();
  87672. var sphereTrimesh_localSpherePos = new Vec3();
  87673. var sphereTrimesh_tmp = new Vec3();
  87674. var sphereTrimesh_va = new Vec3();
  87675. var sphereTrimesh_vb = new Vec3();
  87676. var sphereTrimesh_vc = new Vec3();
  87677. var sphereTrimesh_localSphereAABB = new AABB();
  87678. var sphereTrimesh_triangles = [];
  87679. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.TRIMESH] =
  87680. Narrowphase.prototype.sphereTrimesh = function (
  87681. sphereShape,
  87682. trimeshShape,
  87683. spherePos,
  87684. trimeshPos,
  87685. sphereQuat,
  87686. trimeshQuat,
  87687. sphereBody,
  87688. trimeshBody
  87689. ) {
  87690. var edgeVertexA = sphereTrimesh_edgeVertexA;
  87691. var edgeVertexB = sphereTrimesh_edgeVertexB;
  87692. var edgeVector = sphereTrimesh_edgeVector;
  87693. var edgeVectorUnit = sphereTrimesh_edgeVectorUnit;
  87694. var localSpherePos = sphereTrimesh_localSpherePos;
  87695. var tmp = sphereTrimesh_tmp;
  87696. var localSphereAABB = sphereTrimesh_localSphereAABB;
  87697. var v2 = sphereTrimesh_v2;
  87698. var relpos = sphereTrimesh_relpos;
  87699. var triangles = sphereTrimesh_triangles;
  87700. // Convert sphere position to local in the trimesh
  87701. Transform.pointToLocalFrame(trimeshPos, trimeshQuat, spherePos, localSpherePos);
  87702. // Get the aabb of the sphere locally in the trimesh
  87703. var sphereRadius = sphereShape.radius;
  87704. localSphereAABB.lowerBound.set(
  87705. localSpherePos.x - sphereRadius,
  87706. localSpherePos.y - sphereRadius,
  87707. localSpherePos.z - sphereRadius
  87708. );
  87709. localSphereAABB.upperBound.set(
  87710. localSpherePos.x + sphereRadius,
  87711. localSpherePos.y + sphereRadius,
  87712. localSpherePos.z + sphereRadius
  87713. );
  87714. trimeshShape.getTrianglesInAABB(localSphereAABB, triangles);
  87715. //for (var i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All
  87716. // Vertices
  87717. var v = sphereTrimesh_v;
  87718. var radiusSquared = sphereShape.radius * sphereShape.radius;
  87719. for(var i=0; i<triangles.length; i++){
  87720. for (var j = 0; j < 3; j++) {
  87721. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v);
  87722. // Check vertex overlap in sphere
  87723. v.vsub(localSpherePos, relpos);
  87724. if(relpos.norm2() <= radiusSquared){
  87725. // Safe up
  87726. v2.copy(v);
  87727. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
  87728. v.vsub(spherePos, relpos);
  87729. var r = this.createContactEquation(sphereBody,trimeshBody,sphereShape,trimeshShape);
  87730. r.ni.copy(relpos);
  87731. r.ni.normalize();
  87732. // ri is the vector from sphere center to the sphere surface
  87733. r.ri.copy(r.ni);
  87734. r.ri.scale(sphereShape.radius, r.ri);
  87735. r.ri.vadd(spherePos, r.ri);
  87736. r.ri.vsub(sphereBody.position, r.ri);
  87737. r.rj.copy(v);
  87738. r.rj.vsub(trimeshBody.position, r.rj);
  87739. // Store result
  87740. this.result.push(r);
  87741. this.createFrictionEquationsFromContact(r, this.frictionResult);
  87742. }
  87743. }
  87744. }
  87745. // Check all edges
  87746. for(var i=0; i<triangles.length; i++){
  87747. for (var j = 0; j < 3; j++) {
  87748. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], edgeVertexA);
  87749. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + ((j+1)%3)], edgeVertexB);
  87750. edgeVertexB.vsub(edgeVertexA, edgeVector);
  87751. // Project sphere position to the edge
  87752. localSpherePos.vsub(edgeVertexB, tmp);
  87753. var positionAlongEdgeB = tmp.dot(edgeVector);
  87754. localSpherePos.vsub(edgeVertexA, tmp);
  87755. var positionAlongEdgeA = tmp.dot(edgeVector);
  87756. if(positionAlongEdgeA > 0 && positionAlongEdgeB < 0){
  87757. // Now check the orthogonal distance from edge to sphere center
  87758. localSpherePos.vsub(edgeVertexA, tmp);
  87759. edgeVectorUnit.copy(edgeVector);
  87760. edgeVectorUnit.normalize();
  87761. positionAlongEdgeA = tmp.dot(edgeVectorUnit);
  87762. edgeVectorUnit.scale(positionAlongEdgeA, tmp);
  87763. tmp.vadd(edgeVertexA, tmp);
  87764. // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame
  87765. var dist = tmp.distanceTo(localSpherePos);
  87766. if(dist < sphereShape.radius){
  87767. var r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape);
  87768. tmp.vsub(localSpherePos, r.ni);
  87769. r.ni.normalize();
  87770. r.ni.scale(sphereShape.radius, r.ri);
  87771. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  87772. tmp.vsub(trimeshBody.position, r.rj);
  87773. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  87774. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  87775. this.result.push(r);
  87776. this.createFrictionEquationsFromContact(r, this.frictionResult);
  87777. }
  87778. }
  87779. }
  87780. }
  87781. // Triangle faces
  87782. var va = sphereTrimesh_va;
  87783. var vb = sphereTrimesh_vb;
  87784. var vc = sphereTrimesh_vc;
  87785. var normal = sphereTrimesh_normal;
  87786. for(var i=0, N = triangles.length; i !== N; i++){
  87787. trimeshShape.getTriangleVertices(triangles[i], va, vb, vc);
  87788. trimeshShape.getNormal(triangles[i], normal);
  87789. localSpherePos.vsub(va, tmp);
  87790. var dist = tmp.dot(normal);
  87791. normal.scale(dist, tmp);
  87792. localSpherePos.vsub(tmp, tmp);
  87793. // tmp is now the sphere position projected to the triangle plane
  87794. dist = tmp.distanceTo(localSpherePos);
  87795. if(Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius){
  87796. var r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape);
  87797. tmp.vsub(localSpherePos, r.ni);
  87798. r.ni.normalize();
  87799. r.ni.scale(sphereShape.radius, r.ri);
  87800. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  87801. tmp.vsub(trimeshBody.position, r.rj);
  87802. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  87803. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  87804. this.result.push(r);
  87805. this.createFrictionEquationsFromContact(r, this.frictionResult);
  87806. }
  87807. }
  87808. triangles.length = 0;
  87809. };
  87810. var point_on_plane_to_sphere = new Vec3();
  87811. var plane_to_sphere_ortho = new Vec3();
  87812. /**
  87813. * @method spherePlane
  87814. * @param {Shape} si
  87815. * @param {Shape} sj
  87816. * @param {Vec3} xi
  87817. * @param {Vec3} xj
  87818. * @param {Quaternion} qi
  87819. * @param {Quaternion} qj
  87820. * @param {Body} bi
  87821. * @param {Body} bj
  87822. */
  87823. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.PLANE] =
  87824. Narrowphase.prototype.spherePlane = function(si,sj,xi,xj,qi,qj,bi,bj){
  87825. // We will have one contact in this case
  87826. var r = this.createContactEquation(bi,bj,si,sj);
  87827. // Contact normal
  87828. r.ni.set(0,0,1);
  87829. qj.vmult(r.ni, r.ni);
  87830. r.ni.negate(r.ni); // body i is the sphere, flip normal
  87831. r.ni.normalize(); // Needed?
  87832. // Vector from sphere center to contact point
  87833. r.ni.mult(si.radius, r.ri);
  87834. // Project down sphere on plane
  87835. xi.vsub(xj, point_on_plane_to_sphere);
  87836. r.ni.mult(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho);
  87837. point_on_plane_to_sphere.vsub(plane_to_sphere_ortho,r.rj); // The sphere position projected to plane
  87838. if(-point_on_plane_to_sphere.dot(r.ni) <= si.radius){
  87839. // Make it relative to the body
  87840. var ri = r.ri;
  87841. var rj = r.rj;
  87842. ri.vadd(xi, ri);
  87843. ri.vsub(bi.position, ri);
  87844. rj.vadd(xj, rj);
  87845. rj.vsub(bj.position, rj);
  87846. this.result.push(r);
  87847. this.createFrictionEquationsFromContact(r, this.frictionResult);
  87848. }
  87849. };
  87850. // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html
  87851. var pointInPolygon_edge = new Vec3();
  87852. var pointInPolygon_edge_x_normal = new Vec3();
  87853. var pointInPolygon_vtp = new Vec3();
  87854. function pointInPolygon(verts, normal, p){
  87855. var positiveResult = null;
  87856. var N = verts.length;
  87857. for(var i=0; i!==N; i++){
  87858. var v = verts[i];
  87859. // Get edge to the next vertex
  87860. var edge = pointInPolygon_edge;
  87861. verts[(i+1) % (N)].vsub(v,edge);
  87862. // Get cross product between polygon normal and the edge
  87863. var edge_x_normal = pointInPolygon_edge_x_normal;
  87864. //var edge_x_normal = new Vec3();
  87865. edge.cross(normal,edge_x_normal);
  87866. // Get vector between point and current vertex
  87867. var vertex_to_p = pointInPolygon_vtp;
  87868. p.vsub(v,vertex_to_p);
  87869. // This dot product determines which side of the edge the point is
  87870. var r = edge_x_normal.dot(vertex_to_p);
  87871. // If all such dot products have same sign, we are inside the polygon.
  87872. if(positiveResult===null || (r>0 && positiveResult===true) || (r<=0 && positiveResult===false)){
  87873. if(positiveResult===null){
  87874. positiveResult = r>0;
  87875. }
  87876. continue;
  87877. } else {
  87878. return false; // Encountered some other sign. Exit.
  87879. }
  87880. }
  87881. // If we got here, all dot products were of the same sign.
  87882. return true;
  87883. }
  87884. var box_to_sphere = new Vec3();
  87885. var sphereBox_ns = new Vec3();
  87886. var sphereBox_ns1 = new Vec3();
  87887. var sphereBox_ns2 = new Vec3();
  87888. var sphereBox_sides = [new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3()];
  87889. var sphereBox_sphere_to_corner = new Vec3();
  87890. var sphereBox_side_ns = new Vec3();
  87891. var sphereBox_side_ns1 = new Vec3();
  87892. var sphereBox_side_ns2 = new Vec3();
  87893. /**
  87894. * @method sphereBox
  87895. * @param {Shape} si
  87896. * @param {Shape} sj
  87897. * @param {Vec3} xi
  87898. * @param {Vec3} xj
  87899. * @param {Quaternion} qi
  87900. * @param {Quaternion} qj
  87901. * @param {Body} bi
  87902. * @param {Body} bj
  87903. */
  87904. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.BOX] =
  87905. Narrowphase.prototype.sphereBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  87906. var v3pool = this.v3pool;
  87907. // we refer to the box as body j
  87908. var sides = sphereBox_sides;
  87909. xi.vsub(xj,box_to_sphere);
  87910. sj.getSideNormals(sides,qj);
  87911. var R = si.radius;
  87912. var penetrating_sides = [];
  87913. // Check side (plane) intersections
  87914. var found = false;
  87915. // Store the resulting side penetration info
  87916. var side_ns = sphereBox_side_ns;
  87917. var side_ns1 = sphereBox_side_ns1;
  87918. var side_ns2 = sphereBox_side_ns2;
  87919. var side_h = null;
  87920. var side_penetrations = 0;
  87921. var side_dot1 = 0;
  87922. var side_dot2 = 0;
  87923. var side_distance = null;
  87924. for(var idx=0,nsides=sides.length; idx!==nsides && found===false; idx++){
  87925. // Get the plane side normal (ns)
  87926. var ns = sphereBox_ns;
  87927. ns.copy(sides[idx]);
  87928. var h = ns.norm();
  87929. ns.normalize();
  87930. // The normal/distance dot product tells which side of the plane we are
  87931. var dot = box_to_sphere.dot(ns);
  87932. if(dot<h+R && dot>0){
  87933. // Intersects plane. Now check the other two dimensions
  87934. var ns1 = sphereBox_ns1;
  87935. var ns2 = sphereBox_ns2;
  87936. ns1.copy(sides[(idx+1)%3]);
  87937. ns2.copy(sides[(idx+2)%3]);
  87938. var h1 = ns1.norm();
  87939. var h2 = ns2.norm();
  87940. ns1.normalize();
  87941. ns2.normalize();
  87942. var dot1 = box_to_sphere.dot(ns1);
  87943. var dot2 = box_to_sphere.dot(ns2);
  87944. if(dot1<h1 && dot1>-h1 && dot2<h2 && dot2>-h2){
  87945. var dist = Math.abs(dot-h-R);
  87946. if(side_distance===null || dist < side_distance){
  87947. side_distance = dist;
  87948. side_dot1 = dot1;
  87949. side_dot2 = dot2;
  87950. side_h = h;
  87951. side_ns.copy(ns);
  87952. side_ns1.copy(ns1);
  87953. side_ns2.copy(ns2);
  87954. side_penetrations++;
  87955. }
  87956. }
  87957. }
  87958. }
  87959. if(side_penetrations){
  87960. found = true;
  87961. var r = this.createContactEquation(bi,bj,si,sj);
  87962. side_ns.mult(-R,r.ri); // Sphere r
  87963. r.ni.copy(side_ns);
  87964. r.ni.negate(r.ni); // Normal should be out of sphere
  87965. side_ns.mult(side_h,side_ns);
  87966. side_ns1.mult(side_dot1,side_ns1);
  87967. side_ns.vadd(side_ns1,side_ns);
  87968. side_ns2.mult(side_dot2,side_ns2);
  87969. side_ns.vadd(side_ns2,r.rj);
  87970. // Make relative to bodies
  87971. r.ri.vadd(xi, r.ri);
  87972. r.ri.vsub(bi.position, r.ri);
  87973. r.rj.vadd(xj, r.rj);
  87974. r.rj.vsub(bj.position, r.rj);
  87975. this.result.push(r);
  87976. this.createFrictionEquationsFromContact(r, this.frictionResult);
  87977. }
  87978. // Check corners
  87979. var rj = v3pool.get();
  87980. var sphere_to_corner = sphereBox_sphere_to_corner;
  87981. for(var j=0; j!==2 && !found; j++){
  87982. for(var k=0; k!==2 && !found; k++){
  87983. for(var l=0; l!==2 && !found; l++){
  87984. rj.set(0,0,0);
  87985. if(j){
  87986. rj.vadd(sides[0],rj);
  87987. } else {
  87988. rj.vsub(sides[0],rj);
  87989. }
  87990. if(k){
  87991. rj.vadd(sides[1],rj);
  87992. } else {
  87993. rj.vsub(sides[1],rj);
  87994. }
  87995. if(l){
  87996. rj.vadd(sides[2],rj);
  87997. } else {
  87998. rj.vsub(sides[2],rj);
  87999. }
  88000. // World position of corner
  88001. xj.vadd(rj,sphere_to_corner);
  88002. sphere_to_corner.vsub(xi,sphere_to_corner);
  88003. if(sphere_to_corner.norm2() < R*R){
  88004. found = true;
  88005. var r = this.createContactEquation(bi,bj,si,sj);
  88006. r.ri.copy(sphere_to_corner);
  88007. r.ri.normalize();
  88008. r.ni.copy(r.ri);
  88009. r.ri.mult(R,r.ri);
  88010. r.rj.copy(rj);
  88011. // Make relative to bodies
  88012. r.ri.vadd(xi, r.ri);
  88013. r.ri.vsub(bi.position, r.ri);
  88014. r.rj.vadd(xj, r.rj);
  88015. r.rj.vsub(bj.position, r.rj);
  88016. this.result.push(r);
  88017. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88018. }
  88019. }
  88020. }
  88021. }
  88022. v3pool.release(rj);
  88023. rj = null;
  88024. // Check edges
  88025. var edgeTangent = v3pool.get();
  88026. var edgeCenter = v3pool.get();
  88027. var r = v3pool.get(); // r = edge center to sphere center
  88028. var orthogonal = v3pool.get();
  88029. var dist = v3pool.get();
  88030. var Nsides = sides.length;
  88031. for(var j=0; j!==Nsides && !found; j++){
  88032. for(var k=0; k!==Nsides && !found; k++){
  88033. if(j%3 !== k%3){
  88034. // Get edge tangent
  88035. sides[k].cross(sides[j],edgeTangent);
  88036. edgeTangent.normalize();
  88037. sides[j].vadd(sides[k], edgeCenter);
  88038. r.copy(xi);
  88039. r.vsub(edgeCenter,r);
  88040. r.vsub(xj,r);
  88041. var orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction
  88042. edgeTangent.mult(orthonorm,orthogonal); // Vector from edge center to sphere center in the tangent direction
  88043. // Find the third side orthogonal to this one
  88044. var l = 0;
  88045. while(l===j%3 || l===k%3){
  88046. l++;
  88047. }
  88048. // vec from edge center to sphere projected to the plane orthogonal to the edge tangent
  88049. dist.copy(xi);
  88050. dist.vsub(orthogonal,dist);
  88051. dist.vsub(edgeCenter,dist);
  88052. dist.vsub(xj,dist);
  88053. // Distances in tangent direction and distance in the plane orthogonal to it
  88054. var tdist = Math.abs(orthonorm);
  88055. var ndist = dist.norm();
  88056. if(tdist < sides[l].norm() && ndist<R){
  88057. found = true;
  88058. var res = this.createContactEquation(bi,bj,si,sj);
  88059. edgeCenter.vadd(orthogonal,res.rj); // box rj
  88060. res.rj.copy(res.rj);
  88061. dist.negate(res.ni);
  88062. res.ni.normalize();
  88063. res.ri.copy(res.rj);
  88064. res.ri.vadd(xj,res.ri);
  88065. res.ri.vsub(xi,res.ri);
  88066. res.ri.normalize();
  88067. res.ri.mult(R,res.ri);
  88068. // Make relative to bodies
  88069. res.ri.vadd(xi, res.ri);
  88070. res.ri.vsub(bi.position, res.ri);
  88071. res.rj.vadd(xj, res.rj);
  88072. res.rj.vsub(bj.position, res.rj);
  88073. this.result.push(res);
  88074. this.createFrictionEquationsFromContact(res, this.frictionResult);
  88075. }
  88076. }
  88077. }
  88078. }
  88079. v3pool.release(edgeTangent,edgeCenter,r,orthogonal,dist);
  88080. };
  88081. var convex_to_sphere = new Vec3();
  88082. var sphereConvex_edge = new Vec3();
  88083. var sphereConvex_edgeUnit = new Vec3();
  88084. var sphereConvex_sphereToCorner = new Vec3();
  88085. var sphereConvex_worldCorner = new Vec3();
  88086. var sphereConvex_worldNormal = new Vec3();
  88087. var sphereConvex_worldPoint = new Vec3();
  88088. var sphereConvex_worldSpherePointClosestToPlane = new Vec3();
  88089. var sphereConvex_penetrationVec = new Vec3();
  88090. var sphereConvex_sphereToWorldPoint = new Vec3();
  88091. /**
  88092. * @method sphereConvex
  88093. * @param {Shape} si
  88094. * @param {Shape} sj
  88095. * @param {Vec3} xi
  88096. * @param {Vec3} xj
  88097. * @param {Quaternion} qi
  88098. * @param {Quaternion} qj
  88099. * @param {Body} bi
  88100. * @param {Body} bj
  88101. */
  88102. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON] =
  88103. Narrowphase.prototype.sphereConvex = function(si,sj,xi,xj,qi,qj,bi,bj){
  88104. var v3pool = this.v3pool;
  88105. xi.vsub(xj,convex_to_sphere);
  88106. var normals = sj.faceNormals;
  88107. var faces = sj.faces;
  88108. var verts = sj.vertices;
  88109. var R = si.radius;
  88110. var penetrating_sides = [];
  88111. // if(convex_to_sphere.norm2() > si.boundingSphereRadius + sj.boundingSphereRadius){
  88112. // return;
  88113. // }
  88114. // Check corners
  88115. for(var i=0; i!==verts.length; i++){
  88116. var v = verts[i];
  88117. // World position of corner
  88118. var worldCorner = sphereConvex_worldCorner;
  88119. qj.vmult(v,worldCorner);
  88120. xj.vadd(worldCorner,worldCorner);
  88121. var sphere_to_corner = sphereConvex_sphereToCorner;
  88122. worldCorner.vsub(xi, sphere_to_corner);
  88123. if(sphere_to_corner.norm2() < R * R){
  88124. found = true;
  88125. var r = this.createContactEquation(bi,bj,si,sj);
  88126. r.ri.copy(sphere_to_corner);
  88127. r.ri.normalize();
  88128. r.ni.copy(r.ri);
  88129. r.ri.mult(R,r.ri);
  88130. worldCorner.vsub(xj,r.rj);
  88131. // Should be relative to the body.
  88132. r.ri.vadd(xi, r.ri);
  88133. r.ri.vsub(bi.position, r.ri);
  88134. // Should be relative to the body.
  88135. r.rj.vadd(xj, r.rj);
  88136. r.rj.vsub(bj.position, r.rj);
  88137. this.result.push(r);
  88138. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88139. return;
  88140. }
  88141. }
  88142. // Check side (plane) intersections
  88143. var found = false;
  88144. for(var i=0, nfaces=faces.length; i!==nfaces && found===false; i++){
  88145. var normal = normals[i];
  88146. var face = faces[i];
  88147. // Get world-transformed normal of the face
  88148. var worldNormal = sphereConvex_worldNormal;
  88149. qj.vmult(normal,worldNormal);
  88150. // Get a world vertex from the face
  88151. var worldPoint = sphereConvex_worldPoint;
  88152. qj.vmult(verts[face[0]],worldPoint);
  88153. worldPoint.vadd(xj,worldPoint);
  88154. // Get a point on the sphere, closest to the face normal
  88155. var worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane;
  88156. worldNormal.mult(-R, worldSpherePointClosestToPlane);
  88157. xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane);
  88158. // Vector from a face point to the closest point on the sphere
  88159. var penetrationVec = sphereConvex_penetrationVec;
  88160. worldSpherePointClosestToPlane.vsub(worldPoint,penetrationVec);
  88161. // The penetration. Negative value means overlap.
  88162. var penetration = penetrationVec.dot(worldNormal);
  88163. var worldPointToSphere = sphereConvex_sphereToWorldPoint;
  88164. xi.vsub(worldPoint, worldPointToSphere);
  88165. if(penetration < 0 && worldPointToSphere.dot(worldNormal)>0){
  88166. // Intersects plane. Now check if the sphere is inside the face polygon
  88167. var faceVerts = []; // Face vertices, in world coords
  88168. for(var j=0, Nverts=face.length; j!==Nverts; j++){
  88169. var worldVertex = v3pool.get();
  88170. qj.vmult(verts[face[j]], worldVertex);
  88171. xj.vadd(worldVertex,worldVertex);
  88172. faceVerts.push(worldVertex);
  88173. }
  88174. if(pointInPolygon(faceVerts,worldNormal,xi)){ // Is the sphere center in the face polygon?
  88175. found = true;
  88176. var r = this.createContactEquation(bi,bj,si,sj);
  88177. worldNormal.mult(-R, r.ri); // Contact offset, from sphere center to contact
  88178. worldNormal.negate(r.ni); // Normal pointing out of sphere
  88179. var penetrationVec2 = v3pool.get();
  88180. worldNormal.mult(-penetration, penetrationVec2);
  88181. var penetrationSpherePoint = v3pool.get();
  88182. worldNormal.mult(-R, penetrationSpherePoint);
  88183. //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj);
  88184. xi.vsub(xj,r.rj);
  88185. r.rj.vadd(penetrationSpherePoint,r.rj);
  88186. r.rj.vadd(penetrationVec2 , r.rj);
  88187. // Should be relative to the body.
  88188. r.rj.vadd(xj, r.rj);
  88189. r.rj.vsub(bj.position, r.rj);
  88190. // Should be relative to the body.
  88191. r.ri.vadd(xi, r.ri);
  88192. r.ri.vsub(bi.position, r.ri);
  88193. v3pool.release(penetrationVec2);
  88194. v3pool.release(penetrationSpherePoint);
  88195. this.result.push(r);
  88196. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88197. // Release world vertices
  88198. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  88199. v3pool.release(faceVerts[j]);
  88200. }
  88201. return; // We only expect *one* face contact
  88202. } else {
  88203. // Edge?
  88204. for(var j=0; j!==face.length; j++){
  88205. // Get two world transformed vertices
  88206. var v1 = v3pool.get();
  88207. var v2 = v3pool.get();
  88208. qj.vmult(verts[face[(j+1)%face.length]], v1);
  88209. qj.vmult(verts[face[(j+2)%face.length]], v2);
  88210. xj.vadd(v1, v1);
  88211. xj.vadd(v2, v2);
  88212. // Construct edge vector
  88213. var edge = sphereConvex_edge;
  88214. v2.vsub(v1,edge);
  88215. // Construct the same vector, but normalized
  88216. var edgeUnit = sphereConvex_edgeUnit;
  88217. edge.unit(edgeUnit);
  88218. // p is xi projected onto the edge
  88219. var p = v3pool.get();
  88220. var v1_to_xi = v3pool.get();
  88221. xi.vsub(v1, v1_to_xi);
  88222. var dot = v1_to_xi.dot(edgeUnit);
  88223. edgeUnit.mult(dot, p);
  88224. p.vadd(v1, p);
  88225. // Compute a vector from p to the center of the sphere
  88226. var xi_to_p = v3pool.get();
  88227. p.vsub(xi, xi_to_p);
  88228. // Collision if the edge-sphere distance is less than the radius
  88229. // AND if p is in between v1 and v2
  88230. if(dot > 0 && dot*dot<edge.norm2() && xi_to_p.norm2() < R*R){ // Collision if the edge-sphere distance is less than the radius
  88231. // Edge contact!
  88232. var r = this.createContactEquation(bi,bj,si,sj);
  88233. p.vsub(xj,r.rj);
  88234. p.vsub(xi,r.ni);
  88235. r.ni.normalize();
  88236. r.ni.mult(R,r.ri);
  88237. // Should be relative to the body.
  88238. r.rj.vadd(xj, r.rj);
  88239. r.rj.vsub(bj.position, r.rj);
  88240. // Should be relative to the body.
  88241. r.ri.vadd(xi, r.ri);
  88242. r.ri.vsub(bi.position, r.ri);
  88243. this.result.push(r);
  88244. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88245. // Release world vertices
  88246. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  88247. v3pool.release(faceVerts[j]);
  88248. }
  88249. v3pool.release(v1);
  88250. v3pool.release(v2);
  88251. v3pool.release(p);
  88252. v3pool.release(xi_to_p);
  88253. v3pool.release(v1_to_xi);
  88254. return;
  88255. }
  88256. v3pool.release(v1);
  88257. v3pool.release(v2);
  88258. v3pool.release(p);
  88259. v3pool.release(xi_to_p);
  88260. v3pool.release(v1_to_xi);
  88261. }
  88262. }
  88263. // Release world vertices
  88264. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  88265. v3pool.release(faceVerts[j]);
  88266. }
  88267. }
  88268. }
  88269. };
  88270. var planeBox_normal = new Vec3();
  88271. var plane_to_corner = new Vec3();
  88272. /**
  88273. * @method planeBox
  88274. * @param {Array} result
  88275. * @param {Shape} si
  88276. * @param {Shape} sj
  88277. * @param {Vec3} xi
  88278. * @param {Vec3} xj
  88279. * @param {Quaternion} qi
  88280. * @param {Quaternion} qj
  88281. * @param {Body} bi
  88282. * @param {Body} bj
  88283. */
  88284. Narrowphase.prototype[Shape.types.PLANE | Shape.types.BOX] =
  88285. Narrowphase.prototype.planeBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  88286. sj.convexPolyhedronRepresentation.material = sj.material;
  88287. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  88288. this.planeConvex(si,sj.convexPolyhedronRepresentation,xi,xj,qi,qj,bi,bj);
  88289. };
  88290. var planeConvex_v = new Vec3();
  88291. var planeConvex_normal = new Vec3();
  88292. var planeConvex_relpos = new Vec3();
  88293. var planeConvex_projected = new Vec3();
  88294. /**
  88295. * @method planeConvex
  88296. * @param {Shape} si
  88297. * @param {Shape} sj
  88298. * @param {Vec3} xi
  88299. * @param {Vec3} xj
  88300. * @param {Quaternion} qi
  88301. * @param {Quaternion} qj
  88302. * @param {Body} bi
  88303. * @param {Body} bj
  88304. */
  88305. Narrowphase.prototype[Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON] =
  88306. Narrowphase.prototype.planeConvex = function(
  88307. planeShape,
  88308. convexShape,
  88309. planePosition,
  88310. convexPosition,
  88311. planeQuat,
  88312. convexQuat,
  88313. planeBody,
  88314. convexBody
  88315. ){
  88316. // Simply return the points behind the plane.
  88317. var worldVertex = planeConvex_v,
  88318. worldNormal = planeConvex_normal;
  88319. worldNormal.set(0,0,1);
  88320. planeQuat.vmult(worldNormal,worldNormal); // Turn normal according to plane orientation
  88321. var numContacts = 0;
  88322. var relpos = planeConvex_relpos;
  88323. for(var i = 0; i !== convexShape.vertices.length; i++){
  88324. // Get world convex vertex
  88325. worldVertex.copy(convexShape.vertices[i]);
  88326. convexQuat.vmult(worldVertex, worldVertex);
  88327. convexPosition.vadd(worldVertex, worldVertex);
  88328. worldVertex.vsub(planePosition, relpos);
  88329. var dot = worldNormal.dot(relpos);
  88330. if(dot <= 0.0){
  88331. var r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape);
  88332. // Get vertex position projected on plane
  88333. var projected = planeConvex_projected;
  88334. worldNormal.mult(worldNormal.dot(relpos),projected);
  88335. worldVertex.vsub(projected, projected);
  88336. projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane
  88337. r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane
  88338. // rj is now just the vector from the convex center to the vertex
  88339. worldVertex.vsub(convexPosition, r.rj);
  88340. // Make it relative to the body
  88341. r.ri.vadd(planePosition, r.ri);
  88342. r.ri.vsub(planeBody.position, r.ri);
  88343. r.rj.vadd(convexPosition, r.rj);
  88344. r.rj.vsub(convexBody.position, r.rj);
  88345. this.result.push(r);
  88346. numContacts++;
  88347. if(!this.enableFrictionReduction){
  88348. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88349. }
  88350. }
  88351. }
  88352. if(this.enableFrictionReduction && numContacts){
  88353. this.createFrictionFromAverage(numContacts);
  88354. }
  88355. };
  88356. var convexConvex_sepAxis = new Vec3();
  88357. var convexConvex_q = new Vec3();
  88358. /**
  88359. * @method convexConvex
  88360. * @param {Shape} si
  88361. * @param {Shape} sj
  88362. * @param {Vec3} xi
  88363. * @param {Vec3} xj
  88364. * @param {Quaternion} qi
  88365. * @param {Quaternion} qj
  88366. * @param {Body} bi
  88367. * @param {Body} bj
  88368. */
  88369. Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON] =
  88370. Narrowphase.prototype.convexConvex = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,faceListA,faceListB){
  88371. var sepAxis = convexConvex_sepAxis;
  88372. if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  88373. return;
  88374. }
  88375. if(si.findSeparatingAxis(sj,xi,qi,xj,qj,sepAxis,faceListA,faceListB)){
  88376. var res = [];
  88377. var q = convexConvex_q;
  88378. si.clipAgainstHull(xi,qi,sj,xj,qj,sepAxis,-100,100,res);
  88379. var numContacts = 0;
  88380. for(var j = 0; j !== res.length; j++){
  88381. var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  88382. ri = r.ri,
  88383. rj = r.rj;
  88384. sepAxis.negate(r.ni);
  88385. res[j].normal.negate(q);
  88386. q.mult(res[j].depth, q);
  88387. res[j].point.vadd(q, ri);
  88388. rj.copy(res[j].point);
  88389. // Contact points are in world coordinates. Transform back to relative
  88390. ri.vsub(xi,ri);
  88391. rj.vsub(xj,rj);
  88392. // Make relative to bodies
  88393. ri.vadd(xi, ri);
  88394. ri.vsub(bi.position, ri);
  88395. rj.vadd(xj, rj);
  88396. rj.vsub(bj.position, rj);
  88397. this.result.push(r);
  88398. numContacts++;
  88399. if(!this.enableFrictionReduction){
  88400. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88401. }
  88402. }
  88403. if(this.enableFrictionReduction && numContacts){
  88404. this.createFrictionFromAverage(numContacts);
  88405. }
  88406. }
  88407. };
  88408. /**
  88409. * @method convexTrimesh
  88410. * @param {Array} result
  88411. * @param {Shape} si
  88412. * @param {Shape} sj
  88413. * @param {Vec3} xi
  88414. * @param {Vec3} xj
  88415. * @param {Quaternion} qi
  88416. * @param {Quaternion} qj
  88417. * @param {Body} bi
  88418. * @param {Body} bj
  88419. */
  88420. // Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON | Shape.types.TRIMESH] =
  88421. // Narrowphase.prototype.convexTrimesh = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,faceListA,faceListB){
  88422. // var sepAxis = convexConvex_sepAxis;
  88423. // if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  88424. // return;
  88425. // }
  88426. // // Construct a temp hull for each triangle
  88427. // var hullB = new ConvexPolyhedron();
  88428. // hullB.faces = [[0,1,2]];
  88429. // var va = new Vec3();
  88430. // var vb = new Vec3();
  88431. // var vc = new Vec3();
  88432. // hullB.vertices = [
  88433. // va,
  88434. // vb,
  88435. // vc
  88436. // ];
  88437. // for (var i = 0; i < sj.indices.length / 3; i++) {
  88438. // var triangleNormal = new Vec3();
  88439. // sj.getNormal(i, triangleNormal);
  88440. // hullB.faceNormals = [triangleNormal];
  88441. // sj.getTriangleVertices(i, va, vb, vc);
  88442. // var d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  88443. // if(!d){
  88444. // triangleNormal.scale(-1, triangleNormal);
  88445. // d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  88446. // if(!d){
  88447. // continue;
  88448. // }
  88449. // }
  88450. // var res = [];
  88451. // var q = convexConvex_q;
  88452. // si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res);
  88453. // for(var j = 0; j !== res.length; j++){
  88454. // var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  88455. // ri = r.ri,
  88456. // rj = r.rj;
  88457. // r.ni.copy(triangleNormal);
  88458. // r.ni.negate(r.ni);
  88459. // res[j].normal.negate(q);
  88460. // q.mult(res[j].depth, q);
  88461. // res[j].point.vadd(q, ri);
  88462. // rj.copy(res[j].point);
  88463. // // Contact points are in world coordinates. Transform back to relative
  88464. // ri.vsub(xi,ri);
  88465. // rj.vsub(xj,rj);
  88466. // // Make relative to bodies
  88467. // ri.vadd(xi, ri);
  88468. // ri.vsub(bi.position, ri);
  88469. // rj.vadd(xj, rj);
  88470. // rj.vsub(bj.position, rj);
  88471. // result.push(r);
  88472. // }
  88473. // }
  88474. // };
  88475. var particlePlane_normal = new Vec3();
  88476. var particlePlane_relpos = new Vec3();
  88477. var particlePlane_projected = new Vec3();
  88478. /**
  88479. * @method particlePlane
  88480. * @param {Array} result
  88481. * @param {Shape} si
  88482. * @param {Shape} sj
  88483. * @param {Vec3} xi
  88484. * @param {Vec3} xj
  88485. * @param {Quaternion} qi
  88486. * @param {Quaternion} qj
  88487. * @param {Body} bi
  88488. * @param {Body} bj
  88489. */
  88490. Narrowphase.prototype[Shape.types.PLANE | Shape.types.PARTICLE] =
  88491. Narrowphase.prototype.planeParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  88492. var normal = particlePlane_normal;
  88493. normal.set(0,0,1);
  88494. bj.quaternion.vmult(normal,normal); // Turn normal according to plane orientation
  88495. var relpos = particlePlane_relpos;
  88496. xi.vsub(bj.position,relpos);
  88497. var dot = normal.dot(relpos);
  88498. if(dot <= 0.0){
  88499. var r = this.createContactEquation(bi,bj,si,sj);
  88500. r.ni.copy(normal); // Contact normal is the plane normal
  88501. r.ni.negate(r.ni);
  88502. r.ri.set(0,0,0); // Center of particle
  88503. // Get particle position projected on plane
  88504. var projected = particlePlane_projected;
  88505. normal.mult(normal.dot(xi),projected);
  88506. xi.vsub(projected,projected);
  88507. //projected.vadd(bj.position,projected);
  88508. // rj is now the projected world position minus plane position
  88509. r.rj.copy(projected);
  88510. this.result.push(r);
  88511. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88512. }
  88513. };
  88514. var particleSphere_normal = new Vec3();
  88515. /**
  88516. * @method particleSphere
  88517. * @param {Array} result
  88518. * @param {Shape} si
  88519. * @param {Shape} sj
  88520. * @param {Vec3} xi
  88521. * @param {Vec3} xj
  88522. * @param {Quaternion} qi
  88523. * @param {Quaternion} qj
  88524. * @param {Body} bi
  88525. * @param {Body} bj
  88526. */
  88527. Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.SPHERE] =
  88528. Narrowphase.prototype.sphereParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  88529. // The normal is the unit vector from sphere center to particle center
  88530. var normal = particleSphere_normal;
  88531. normal.set(0,0,1);
  88532. xi.vsub(xj,normal);
  88533. var lengthSquared = normal.norm2();
  88534. if(lengthSquared <= sj.radius * sj.radius){
  88535. var r = this.createContactEquation(bi,bj,si,sj);
  88536. normal.normalize();
  88537. r.rj.copy(normal);
  88538. r.rj.mult(sj.radius,r.rj);
  88539. r.ni.copy(normal); // Contact normal
  88540. r.ni.negate(r.ni);
  88541. r.ri.set(0,0,0); // Center of particle
  88542. this.result.push(r);
  88543. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88544. }
  88545. };
  88546. // WIP
  88547. var cqj = new Quaternion();
  88548. var convexParticle_local = new Vec3();
  88549. var convexParticle_normal = new Vec3();
  88550. var convexParticle_penetratedFaceNormal = new Vec3();
  88551. var convexParticle_vertexToParticle = new Vec3();
  88552. var convexParticle_worldPenetrationVec = new Vec3();
  88553. /**
  88554. * @method convexParticle
  88555. * @param {Array} result
  88556. * @param {Shape} si
  88557. * @param {Shape} sj
  88558. * @param {Vec3} xi
  88559. * @param {Vec3} xj
  88560. * @param {Quaternion} qi
  88561. * @param {Quaternion} qj
  88562. * @param {Body} bi
  88563. * @param {Body} bj
  88564. */
  88565. Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON] =
  88566. Narrowphase.prototype.convexParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  88567. var penetratedFaceIndex = -1;
  88568. var penetratedFaceNormal = convexParticle_penetratedFaceNormal;
  88569. var worldPenetrationVec = convexParticle_worldPenetrationVec;
  88570. var minPenetration = null;
  88571. var numDetectedFaces = 0;
  88572. // Convert particle position xi to local coords in the convex
  88573. var local = convexParticle_local;
  88574. local.copy(xi);
  88575. local.vsub(xj,local); // Convert position to relative the convex origin
  88576. qj.conjugate(cqj);
  88577. cqj.vmult(local,local);
  88578. if(sj.pointIsInside(local)){
  88579. if(sj.worldVerticesNeedsUpdate){
  88580. sj.computeWorldVertices(xj,qj);
  88581. }
  88582. if(sj.worldFaceNormalsNeedsUpdate){
  88583. sj.computeWorldFaceNormals(qj);
  88584. }
  88585. // For each world polygon in the polyhedra
  88586. for(var i=0,nfaces=sj.faces.length; i!==nfaces; i++){
  88587. // Construct world face vertices
  88588. var verts = [ sj.worldVertices[ sj.faces[i][0] ] ];
  88589. var normal = sj.worldFaceNormals[i];
  88590. // Check how much the particle penetrates the polygon plane.
  88591. xi.vsub(verts[0],convexParticle_vertexToParticle);
  88592. var penetration = -normal.dot(convexParticle_vertexToParticle);
  88593. if(minPenetration===null || Math.abs(penetration)<Math.abs(minPenetration)){
  88594. minPenetration = penetration;
  88595. penetratedFaceIndex = i;
  88596. penetratedFaceNormal.copy(normal);
  88597. numDetectedFaces++;
  88598. }
  88599. }
  88600. if(penetratedFaceIndex!==-1){
  88601. // Setup contact
  88602. var r = this.createContactEquation(bi,bj,si,sj);
  88603. penetratedFaceNormal.mult(minPenetration, worldPenetrationVec);
  88604. // rj is the particle position projected to the face
  88605. worldPenetrationVec.vadd(xi,worldPenetrationVec);
  88606. worldPenetrationVec.vsub(xj,worldPenetrationVec);
  88607. r.rj.copy(worldPenetrationVec);
  88608. //var projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec);
  88609. //projectedToFace.copy(r.rj);
  88610. //qj.vmult(r.rj,r.rj);
  88611. penetratedFaceNormal.negate( r.ni ); // Contact normal
  88612. r.ri.set(0,0,0); // Center of particle
  88613. var ri = r.ri,
  88614. rj = r.rj;
  88615. // Make relative to bodies
  88616. ri.vadd(xi, ri);
  88617. ri.vsub(bi.position, ri);
  88618. rj.vadd(xj, rj);
  88619. rj.vsub(bj.position, rj);
  88620. this.result.push(r);
  88621. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88622. } else {
  88623. console.warn("Point found inside convex, but did not find penetrating face!");
  88624. }
  88625. }
  88626. };
  88627. Narrowphase.prototype[Shape.types.BOX | Shape.types.HEIGHTFIELD] =
  88628. Narrowphase.prototype.boxHeightfield = function (si,sj,xi,xj,qi,qj,bi,bj){
  88629. si.convexPolyhedronRepresentation.material = si.material;
  88630. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  88631. this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj);
  88632. };
  88633. var convexHeightfield_tmp1 = new Vec3();
  88634. var convexHeightfield_tmp2 = new Vec3();
  88635. var convexHeightfield_faceList = [0];
  88636. /**
  88637. * @method convexHeightfield
  88638. */
  88639. Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD] =
  88640. Narrowphase.prototype.convexHeightfield = function (
  88641. convexShape,
  88642. hfShape,
  88643. convexPos,
  88644. hfPos,
  88645. convexQuat,
  88646. hfQuat,
  88647. convexBody,
  88648. hfBody
  88649. ){
  88650. var data = hfShape.data,
  88651. w = hfShape.elementSize,
  88652. radius = convexShape.boundingSphereRadius,
  88653. worldPillarOffset = convexHeightfield_tmp2,
  88654. faceList = convexHeightfield_faceList;
  88655. // Get sphere position to heightfield local!
  88656. var localConvexPos = convexHeightfield_tmp1;
  88657. Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos);
  88658. // Get the index of the data points to test against
  88659. var iMinX = Math.floor((localConvexPos.x - radius) / w) - 1,
  88660. iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1,
  88661. iMinY = Math.floor((localConvexPos.y - radius) / w) - 1,
  88662. iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1;
  88663. // Bail out if we are out of the terrain
  88664. if(iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length){
  88665. return;
  88666. }
  88667. // Clamp index to edges
  88668. if(iMinX < 0){ iMinX = 0; }
  88669. if(iMaxX < 0){ iMaxX = 0; }
  88670. if(iMinY < 0){ iMinY = 0; }
  88671. if(iMaxY < 0){ iMaxY = 0; }
  88672. if(iMinX >= data.length){ iMinX = data.length - 1; }
  88673. if(iMaxX >= data.length){ iMaxX = data.length - 1; }
  88674. if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; }
  88675. if(iMinY >= data[0].length){ iMinY = data[0].length - 1; }
  88676. var minMax = [];
  88677. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  88678. var min = minMax[0];
  88679. var max = minMax[1];
  88680. // Bail out if we're cant touch the bounding height box
  88681. if(localConvexPos.z - radius > max || localConvexPos.z + radius < min){
  88682. return;
  88683. }
  88684. for(var i = iMinX; i < iMaxX; i++){
  88685. for(var j = iMinY; j < iMaxY; j++){
  88686. // Lower triangle
  88687. hfShape.getConvexTrianglePillar(i, j, false);
  88688. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  88689. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  88690. this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, faceList, null);
  88691. }
  88692. // Upper triangle
  88693. hfShape.getConvexTrianglePillar(i, j, true);
  88694. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  88695. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  88696. this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, faceList, null);
  88697. }
  88698. }
  88699. }
  88700. };
  88701. var sphereHeightfield_tmp1 = new Vec3();
  88702. var sphereHeightfield_tmp2 = new Vec3();
  88703. /**
  88704. * @method sphereHeightfield
  88705. */
  88706. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.HEIGHTFIELD] =
  88707. Narrowphase.prototype.sphereHeightfield = function (
  88708. sphereShape,
  88709. hfShape,
  88710. spherePos,
  88711. hfPos,
  88712. sphereQuat,
  88713. hfQuat,
  88714. sphereBody,
  88715. hfBody
  88716. ){
  88717. var data = hfShape.data,
  88718. radius = sphereShape.radius,
  88719. w = hfShape.elementSize,
  88720. worldPillarOffset = sphereHeightfield_tmp2;
  88721. // Get sphere position to heightfield local!
  88722. var localSpherePos = sphereHeightfield_tmp1;
  88723. Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos);
  88724. // Get the index of the data points to test against
  88725. var iMinX = Math.floor((localSpherePos.x - radius) / w) - 1,
  88726. iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1,
  88727. iMinY = Math.floor((localSpherePos.y - radius) / w) - 1,
  88728. iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1;
  88729. // Bail out if we are out of the terrain
  88730. if(iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMaxY > data[0].length){
  88731. return;
  88732. }
  88733. // Clamp index to edges
  88734. if(iMinX < 0){ iMinX = 0; }
  88735. if(iMaxX < 0){ iMaxX = 0; }
  88736. if(iMinY < 0){ iMinY = 0; }
  88737. if(iMaxY < 0){ iMaxY = 0; }
  88738. if(iMinX >= data.length){ iMinX = data.length - 1; }
  88739. if(iMaxX >= data.length){ iMaxX = data.length - 1; }
  88740. if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; }
  88741. if(iMinY >= data[0].length){ iMinY = data[0].length - 1; }
  88742. var minMax = [];
  88743. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  88744. var min = minMax[0];
  88745. var max = minMax[1];
  88746. // Bail out if we're cant touch the bounding height box
  88747. if(localSpherePos.z - radius > max || localSpherePos.z + radius < min){
  88748. return;
  88749. }
  88750. var result = this.result;
  88751. for(var i = iMinX; i < iMaxX; i++){
  88752. for(var j = iMinY; j < iMaxY; j++){
  88753. var numContactsBefore = result.length;
  88754. // Lower triangle
  88755. hfShape.getConvexTrianglePillar(i, j, false);
  88756. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  88757. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  88758. this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody);
  88759. }
  88760. // Upper triangle
  88761. hfShape.getConvexTrianglePillar(i, j, true);
  88762. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  88763. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  88764. this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody);
  88765. }
  88766. var numContacts = result.length - numContactsBefore;
  88767. if(numContacts > 2){
  88768. return;
  88769. }
  88770. /*
  88771. // Skip all but 1
  88772. for (var k = 0; k < numContacts - 1; k++) {
  88773. result.pop();
  88774. }
  88775. */
  88776. }
  88777. }
  88778. };
  88779. },{"../collision/AABB":3,"../collision/Ray":9,"../equations/ContactEquation":19,"../equations/FrictionEquation":21,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../shapes/ConvexPolyhedron":38,"../shapes/Shape":43,"../solver/Solver":47,"../utils/Vec3Pool":54}],56:[function(_dereq_,module,exports){
  88780. /* global performance */
  88781. module.exports = World;
  88782. var Shape = _dereq_('../shapes/Shape');
  88783. var Vec3 = _dereq_('../math/Vec3');
  88784. var Quaternion = _dereq_('../math/Quaternion');
  88785. var GSSolver = _dereq_('../solver/GSSolver');
  88786. var Vec3Pool = _dereq_('../utils/Vec3Pool');
  88787. var ContactEquation = _dereq_('../equations/ContactEquation');
  88788. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  88789. var Narrowphase = _dereq_('./Narrowphase');
  88790. var EventTarget = _dereq_('../utils/EventTarget');
  88791. var ArrayCollisionMatrix = _dereq_('../collision/ArrayCollisionMatrix');
  88792. var Material = _dereq_('../material/Material');
  88793. var ContactMaterial = _dereq_('../material/ContactMaterial');
  88794. var Body = _dereq_('../objects/Body');
  88795. var TupleDictionary = _dereq_('../utils/TupleDictionary');
  88796. var RaycastResult = _dereq_('../collision/RaycastResult');
  88797. var AABB = _dereq_('../collision/AABB');
  88798. var Ray = _dereq_('../collision/Ray');
  88799. var NaiveBroadphase = _dereq_('../collision/NaiveBroadphase');
  88800. /**
  88801. * The physics world
  88802. * @class World
  88803. * @constructor
  88804. * @extends EventTarget
  88805. */
  88806. function World(){
  88807. EventTarget.apply(this);
  88808. /**
  88809. * Currently / last used timestep. Is set to -1 if not available. This value is updated before each internal step, which means that it is "fresh" inside event callbacks.
  88810. * @property {Number} dt
  88811. */
  88812. this.dt = -1;
  88813. /**
  88814. * Makes bodies go to sleep when they've been inactive
  88815. * @property allowSleep
  88816. * @type {Boolean}
  88817. */
  88818. this.allowSleep = false;
  88819. /**
  88820. * All the current contacts (instances of ContactEquation) in the world.
  88821. * @property contacts
  88822. * @type {Array}
  88823. */
  88824. this.contacts = [];
  88825. this.frictionEquations = [];
  88826. /**
  88827. * How often to normalize quaternions. Set to 0 for every step, 1 for every second etc.. A larger value increases performance. If bodies tend to explode, set to a smaller value (zero to be sure nothing can go wrong).
  88828. * @property quatNormalizeSkip
  88829. * @type {Number}
  88830. */
  88831. this.quatNormalizeSkip = 0;
  88832. /**
  88833. * Set to true to use fast quaternion normalization. It is often enough accurate to use. If bodies tend to explode, set to false.
  88834. * @property quatNormalizeFast
  88835. * @type {Boolean}
  88836. * @see Quaternion.normalizeFast
  88837. * @see Quaternion.normalize
  88838. */
  88839. this.quatNormalizeFast = false;
  88840. /**
  88841. * The wall-clock time since simulation start
  88842. * @property time
  88843. * @type {Number}
  88844. */
  88845. this.time = 0.0;
  88846. /**
  88847. * Number of timesteps taken since start
  88848. * @property stepnumber
  88849. * @type {Number}
  88850. */
  88851. this.stepnumber = 0;
  88852. /// Default and last timestep sizes
  88853. this.default_dt = 1/60;
  88854. this.nextId = 0;
  88855. /**
  88856. * @property gravity
  88857. * @type {Vec3}
  88858. */
  88859. this.gravity = new Vec3();
  88860. /**
  88861. * @property broadphase
  88862. * @type {Broadphase}
  88863. */
  88864. this.broadphase = new NaiveBroadphase();
  88865. /**
  88866. * @property bodies
  88867. * @type {Array}
  88868. */
  88869. this.bodies = [];
  88870. /**
  88871. * @property solver
  88872. * @type {Solver}
  88873. */
  88874. this.solver = new GSSolver();
  88875. /**
  88876. * @property constraints
  88877. * @type {Array}
  88878. */
  88879. this.constraints = [];
  88880. /**
  88881. * @property narrowphase
  88882. * @type {Narrowphase}
  88883. */
  88884. this.narrowphase = new Narrowphase(this);
  88885. /**
  88886. * @property {ArrayCollisionMatrix} collisionMatrix
  88887. * @type {ArrayCollisionMatrix}
  88888. */
  88889. this.collisionMatrix = new ArrayCollisionMatrix();
  88890. /**
  88891. * CollisionMatrix from the previous step.
  88892. * @property {ArrayCollisionMatrix} collisionMatrixPrevious
  88893. * @type {ArrayCollisionMatrix}
  88894. */
  88895. this.collisionMatrixPrevious = new ArrayCollisionMatrix();
  88896. /**
  88897. * All added materials
  88898. * @property materials
  88899. * @type {Array}
  88900. */
  88901. this.materials = [];
  88902. /**
  88903. * @property contactmaterials
  88904. * @type {Array}
  88905. */
  88906. this.contactmaterials = [];
  88907. /**
  88908. * Used to look up a ContactMaterial given two instances of Material.
  88909. * @property {TupleDictionary} contactMaterialTable
  88910. */
  88911. this.contactMaterialTable = new TupleDictionary();
  88912. this.defaultMaterial = new Material("default");
  88913. /**
  88914. * This contact material is used if no suitable contactmaterial is found for a contact.
  88915. * @property defaultContactMaterial
  88916. * @type {ContactMaterial}
  88917. */
  88918. this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, { friction: 0.3, restitution: 0.0 });
  88919. /**
  88920. * @property doProfiling
  88921. * @type {Boolean}
  88922. */
  88923. this.doProfiling = false;
  88924. /**
  88925. * @property profile
  88926. * @type {Object}
  88927. */
  88928. this.profile = {
  88929. solve:0,
  88930. makeContactConstraints:0,
  88931. broadphase:0,
  88932. integrate:0,
  88933. narrowphase:0,
  88934. };
  88935. /**
  88936. * @property subsystems
  88937. * @type {Array}
  88938. */
  88939. this.subsystems = [];
  88940. this.addBodyEvent = {
  88941. type:"addBody",
  88942. body : null,
  88943. };
  88944. this.removeBodyEvent = {
  88945. type:"removeBody",
  88946. body : null,
  88947. };
  88948. }
  88949. World.prototype = new EventTarget();
  88950. // Temp stuff
  88951. var tmpAABB1 = new AABB();
  88952. var tmpArray1 = [];
  88953. var tmpRay = new Ray();
  88954. /**
  88955. * Get the contact material between materials m1 and m2
  88956. * @method getContactMaterial
  88957. * @param {Material} m1
  88958. * @param {Material} m2
  88959. * @return {ContactMaterial} The contact material if it was found.
  88960. */
  88961. World.prototype.getContactMaterial = function(m1,m2){
  88962. return this.contactMaterialTable.get(m1.id,m2.id); //this.contactmaterials[this.mats2cmat[i+j*this.materials.length]];
  88963. };
  88964. /**
  88965. * Get number of objects in the world.
  88966. * @method numObjects
  88967. * @return {Number}
  88968. * @deprecated
  88969. */
  88970. World.prototype.numObjects = function(){
  88971. return this.bodies.length;
  88972. };
  88973. /**
  88974. * Store old collision state info
  88975. * @method collisionMatrixTick
  88976. */
  88977. World.prototype.collisionMatrixTick = function(){
  88978. var temp = this.collisionMatrixPrevious;
  88979. this.collisionMatrixPrevious = this.collisionMatrix;
  88980. this.collisionMatrix = temp;
  88981. this.collisionMatrix.reset();
  88982. };
  88983. /**
  88984. * Add a rigid body to the simulation.
  88985. * @method add
  88986. * @param {Body} body
  88987. * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.
  88988. * @todo Adding an array of bodies should be possible. This would save some loops too
  88989. * @deprecated Use .addBody instead
  88990. */
  88991. World.prototype.add = World.prototype.addBody = function(body){
  88992. if(this.bodies.indexOf(body) !== -1){
  88993. return;
  88994. }
  88995. body.index = this.bodies.length;
  88996. this.bodies.push(body);
  88997. body.world = this;
  88998. body.initPosition.copy(body.position);
  88999. body.initVelocity.copy(body.velocity);
  89000. body.timeLastSleepy = this.time;
  89001. if(body instanceof Body){
  89002. body.initAngularVelocity.copy(body.angularVelocity);
  89003. body.initQuaternion.copy(body.quaternion);
  89004. }
  89005. this.collisionMatrix.setNumObjects(this.bodies.length);
  89006. this.addBodyEvent.body = body;
  89007. this.dispatchEvent(this.addBodyEvent);
  89008. };
  89009. /**
  89010. * Add a constraint to the simulation.
  89011. * @method addConstraint
  89012. * @param {Constraint} c
  89013. */
  89014. World.prototype.addConstraint = function(c){
  89015. this.constraints.push(c);
  89016. };
  89017. /**
  89018. * Removes a constraint
  89019. * @method removeConstraint
  89020. * @param {Constraint} c
  89021. */
  89022. World.prototype.removeConstraint = function(c){
  89023. var idx = this.constraints.indexOf(c);
  89024. if(idx!==-1){
  89025. this.constraints.splice(idx,1);
  89026. }
  89027. };
  89028. /**
  89029. * Raycast test
  89030. * @method rayTest
  89031. * @param {Vec3} from
  89032. * @param {Vec3} to
  89033. * @param {Function|RaycastResult} result
  89034. * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.
  89035. */
  89036. World.prototype.rayTest = function(from, to, result){
  89037. if(result instanceof RaycastResult){
  89038. // Do raycastclosest
  89039. this.raycastClosest(from, to, {
  89040. skipBackfaces: true
  89041. }, result);
  89042. } else {
  89043. // Do raycastAll
  89044. this.raycastAll(from, to, {
  89045. skipBackfaces: true
  89046. }, result);
  89047. }
  89048. };
  89049. /**
  89050. * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
  89051. * @method raycastAll
  89052. * @param {Vec3} from
  89053. * @param {Vec3} to
  89054. * @param {Object} options
  89055. * @param {number} [options.collisionFilterMask=-1]
  89056. * @param {number} [options.collisionFilterGroup=-1]
  89057. * @param {boolean} [options.skipBackfaces=false]
  89058. * @param {boolean} [options.checkCollisionResponse=true]
  89059. * @param {Function} callback
  89060. * @return {boolean} True if any body was hit.
  89061. */
  89062. World.prototype.raycastAll = function(from, to, options, callback){
  89063. options.mode = Ray.ALL;
  89064. options.from = from;
  89065. options.to = to;
  89066. options.callback = callback;
  89067. return tmpRay.intersectWorld(this, options);
  89068. };
  89069. /**
  89070. * Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
  89071. * @method raycastAny
  89072. * @param {Vec3} from
  89073. * @param {Vec3} to
  89074. * @param {Object} options
  89075. * @param {number} [options.collisionFilterMask=-1]
  89076. * @param {number} [options.collisionFilterGroup=-1]
  89077. * @param {boolean} [options.skipBackfaces=false]
  89078. * @param {boolean} [options.checkCollisionResponse=true]
  89079. * @param {RaycastResult} result
  89080. * @return {boolean} True if any body was hit.
  89081. */
  89082. World.prototype.raycastAny = function(from, to, options, result){
  89083. options.mode = Ray.ANY;
  89084. options.from = from;
  89085. options.to = to;
  89086. options.result = result;
  89087. return tmpRay.intersectWorld(this, options);
  89088. };
  89089. /**
  89090. * Ray cast, and return information of the closest hit.
  89091. * @method raycastClosest
  89092. * @param {Vec3} from
  89093. * @param {Vec3} to
  89094. * @param {Object} options
  89095. * @param {number} [options.collisionFilterMask=-1]
  89096. * @param {number} [options.collisionFilterGroup=-1]
  89097. * @param {boolean} [options.skipBackfaces=false]
  89098. * @param {boolean} [options.checkCollisionResponse=true]
  89099. * @param {RaycastResult} result
  89100. * @return {boolean} True if any body was hit.
  89101. */
  89102. World.prototype.raycastClosest = function(from, to, options, result){
  89103. options.mode = Ray.CLOSEST;
  89104. options.from = from;
  89105. options.to = to;
  89106. options.result = result;
  89107. return tmpRay.intersectWorld(this, options);
  89108. };
  89109. /**
  89110. * Remove a rigid body from the simulation.
  89111. * @method remove
  89112. * @param {Body} body
  89113. * @deprecated Use .removeBody instead
  89114. */
  89115. World.prototype.remove = function(body){
  89116. body.world = null;
  89117. var n = this.bodies.length-1,
  89118. bodies = this.bodies,
  89119. idx = bodies.indexOf(body);
  89120. if(idx !== -1){
  89121. bodies.splice(idx, 1); // Todo: should use a garbage free method
  89122. // Recompute index
  89123. for(var i=0; i!==bodies.length; i++){
  89124. bodies[i].index = i;
  89125. }
  89126. this.collisionMatrix.setNumObjects(n);
  89127. this.removeBodyEvent.body = body;
  89128. this.dispatchEvent(this.removeBodyEvent);
  89129. }
  89130. };
  89131. /**
  89132. * Remove a rigid body from the simulation.
  89133. * @method removeBody
  89134. * @param {Body} body
  89135. */
  89136. World.prototype.removeBody = World.prototype.remove;
  89137. /**
  89138. * Adds a material to the World.
  89139. * @method addMaterial
  89140. * @param {Material} m
  89141. * @todo Necessary?
  89142. */
  89143. World.prototype.addMaterial = function(m){
  89144. this.materials.push(m);
  89145. };
  89146. /**
  89147. * Adds a contact material to the World
  89148. * @method addContactMaterial
  89149. * @param {ContactMaterial} cmat
  89150. */
  89151. World.prototype.addContactMaterial = function(cmat) {
  89152. // Add contact material
  89153. this.contactmaterials.push(cmat);
  89154. // Add current contact material to the material table
  89155. this.contactMaterialTable.set(cmat.materials[0].id,cmat.materials[1].id,cmat);
  89156. };
  89157. // performance.now()
  89158. if(typeof performance === 'undefined'){
  89159. performance = {};
  89160. }
  89161. if(!performance.now){
  89162. var nowOffset = Date.now();
  89163. if (performance.timing && performance.timing.navigationStart){
  89164. nowOffset = performance.timing.navigationStart;
  89165. }
  89166. performance.now = function(){
  89167. return Date.now() - nowOffset;
  89168. };
  89169. }
  89170. var step_tmp1 = new Vec3();
  89171. /**
  89172. * Step the physics world forward in time.
  89173. *
  89174. * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.
  89175. *
  89176. * @method step
  89177. * @param {Number} dt The fixed time step size to use.
  89178. * @param {Number} [timeSinceLastCalled] The time elapsed since the function was last called.
  89179. * @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call.
  89180. *
  89181. * @example
  89182. * // fixed timestepping without interpolation
  89183. * world.step(1/60);
  89184. *
  89185. * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
  89186. */
  89187. World.prototype.step = function(dt, timeSinceLastCalled, maxSubSteps){
  89188. maxSubSteps = maxSubSteps || 10;
  89189. timeSinceLastCalled = timeSinceLastCalled || 0;
  89190. if(timeSinceLastCalled === 0){ // Fixed, simple stepping
  89191. this.internalStep(dt);
  89192. // Increment time
  89193. this.time += dt;
  89194. } else {
  89195. // Compute the number of fixed steps we should have taken since the last step
  89196. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  89197. internalSteps = Math.min(internalSteps,maxSubSteps);
  89198. // Do some fixed steps to catch up
  89199. var t0 = performance.now();
  89200. for(var i=0; i!==internalSteps; i++){
  89201. this.internalStep(dt);
  89202. if(performance.now() - t0 > dt * 1000){
  89203. // We are slower than real-time. Better bail out.
  89204. break;
  89205. }
  89206. }
  89207. // Increment internal clock
  89208. this.time += timeSinceLastCalled;
  89209. // Compute "Left over" time step
  89210. var h = this.time % dt;
  89211. var h_div_dt = h / dt;
  89212. var interpvelo = step_tmp1;
  89213. var bodies = this.bodies;
  89214. for(var j=0; j !== bodies.length; j++){
  89215. var b = bodies[j];
  89216. if(b.type !== Body.STATIC && b.sleepState !== Body.SLEEPING){
  89217. // Interpolate
  89218. b.position.vsub(b.previousPosition, interpvelo);
  89219. interpvelo.scale(h_div_dt, interpvelo);
  89220. b.position.vadd(interpvelo, b.interpolatedPosition);
  89221. // TODO: interpolate quaternion
  89222. // b.interpolatedAngle = b.angle + (b.angle - b.previousAngle) * h_div_dt;
  89223. } else {
  89224. // For static bodies, just copy. Who else will do it?
  89225. b.interpolatedPosition.copy(b.position);
  89226. b.interpolatedQuaternion.copy(b.quaternion);
  89227. }
  89228. }
  89229. }
  89230. };
  89231. /**
  89232. * Step the simulation
  89233. * @method step
  89234. * @param {Number} dt
  89235. */
  89236. var World_step_postStepEvent = {type:"postStep"}, // Reusable event objects to save memory
  89237. World_step_preStepEvent = {type:"preStep"},
  89238. World_step_collideEvent = {type:"collide", body:null, contact:null },
  89239. World_step_oldContacts = [], // Pools for unused objects
  89240. World_step_frictionEquationPool = [],
  89241. World_step_p1 = [], // Reusable arrays for collision pairs
  89242. World_step_p2 = [],
  89243. World_step_gvec = new Vec3(), // Temporary vectors and quats
  89244. World_step_vi = new Vec3(),
  89245. World_step_vj = new Vec3(),
  89246. World_step_wi = new Vec3(),
  89247. World_step_wj = new Vec3(),
  89248. World_step_t1 = new Vec3(),
  89249. World_step_t2 = new Vec3(),
  89250. World_step_rixn = new Vec3(),
  89251. World_step_rjxn = new Vec3(),
  89252. World_step_step_q = new Quaternion(),
  89253. World_step_step_w = new Quaternion(),
  89254. World_step_step_wq = new Quaternion(),
  89255. invI_tau_dt = new Vec3();
  89256. World.prototype.internalStep = function(dt){
  89257. this.dt = dt;
  89258. var world = this,
  89259. that = this,
  89260. contacts = this.contacts,
  89261. p1 = World_step_p1,
  89262. p2 = World_step_p2,
  89263. N = this.numObjects(),
  89264. bodies = this.bodies,
  89265. solver = this.solver,
  89266. gravity = this.gravity,
  89267. doProfiling = this.doProfiling,
  89268. profile = this.profile,
  89269. DYNAMIC = Body.DYNAMIC,
  89270. profilingStart,
  89271. constraints = this.constraints,
  89272. frictionEquationPool = World_step_frictionEquationPool,
  89273. gnorm = gravity.norm(),
  89274. gx = gravity.x,
  89275. gy = gravity.y,
  89276. gz = gravity.z,
  89277. i=0;
  89278. if(doProfiling){
  89279. profilingStart = performance.now();
  89280. }
  89281. // Add gravity to all objects
  89282. for(i=0; i!==N; i++){
  89283. var bi = bodies[i];
  89284. if(bi.type & DYNAMIC){ // Only for dynamic bodies
  89285. var f = bi.force, m = bi.mass;
  89286. f.x += m*gx;
  89287. f.y += m*gy;
  89288. f.z += m*gz;
  89289. }
  89290. }
  89291. // Update subsystems
  89292. for(var i=0, Nsubsystems=this.subsystems.length; i!==Nsubsystems; i++){
  89293. this.subsystems[i].update();
  89294. }
  89295. // Collision detection
  89296. if(doProfiling){ profilingStart = performance.now(); }
  89297. p1.length = 0; // Clean up pair arrays from last step
  89298. p2.length = 0;
  89299. this.broadphase.collisionPairs(this,p1,p2);
  89300. if(doProfiling){ profile.broadphase = performance.now() - profilingStart; }
  89301. // Remove constrained pairs with collideConnected == false
  89302. var Nconstraints = constraints.length;
  89303. for(i=0; i!==Nconstraints; i++){
  89304. var c = constraints[i];
  89305. if(!c.collideConnected){
  89306. for(var j = p1.length-1; j>=0; j-=1){
  89307. if( (c.bodyA === p1[j] && c.bodyB === p2[j]) ||
  89308. (c.bodyB === p1[j] && c.bodyA === p2[j])){
  89309. p1.splice(j, 1);
  89310. p2.splice(j, 1);
  89311. }
  89312. }
  89313. }
  89314. }
  89315. this.collisionMatrixTick();
  89316. // Generate contacts
  89317. if(doProfiling){ profilingStart = performance.now(); }
  89318. var oldcontacts = World_step_oldContacts;
  89319. var NoldContacts = contacts.length;
  89320. for(i=0; i!==NoldContacts; i++){
  89321. oldcontacts.push(contacts[i]);
  89322. }
  89323. contacts.length = 0;
  89324. // Transfer FrictionEquation from current list to the pool for reuse
  89325. var NoldFrictionEquations = this.frictionEquations.length;
  89326. for(i=0; i!==NoldFrictionEquations; i++){
  89327. frictionEquationPool.push(this.frictionEquations[i]);
  89328. }
  89329. this.frictionEquations.length = 0;
  89330. this.narrowphase.getContacts(
  89331. p1,
  89332. p2,
  89333. this,
  89334. contacts,
  89335. oldcontacts, // To be reused
  89336. this.frictionEquations,
  89337. frictionEquationPool
  89338. );
  89339. if(doProfiling){
  89340. profile.narrowphase = performance.now() - profilingStart;
  89341. }
  89342. // Loop over all collisions
  89343. if(doProfiling){
  89344. profilingStart = performance.now();
  89345. }
  89346. // Add all friction eqs
  89347. for (var i = 0; i < this.frictionEquations.length; i++) {
  89348. solver.addEquation(this.frictionEquations[i]);
  89349. }
  89350. var ncontacts = contacts.length;
  89351. for(var k=0; k!==ncontacts; k++){
  89352. // Current contact
  89353. var c = contacts[k];
  89354. // Get current collision indeces
  89355. var bi = c.bi,
  89356. bj = c.bj,
  89357. si = c.si,
  89358. sj = c.sj;
  89359. // Get collision properties
  89360. var cm;
  89361. if(bi.material && bj.material){
  89362. cm = this.getContactMaterial(bi.material,bj.material) || this.defaultContactMaterial;
  89363. } else {
  89364. cm = this.defaultContactMaterial;
  89365. }
  89366. // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  89367. var mu = cm.friction;
  89368. // c.restitution = cm.restitution;
  89369. // If friction or restitution were specified in the material, use them
  89370. if(bi.material && bj.material){
  89371. if(bi.material.friction >= 0 && bj.material.friction >= 0){
  89372. mu = bi.material.friction * bj.material.friction;
  89373. }
  89374. if(bi.material.restitution >= 0 && bj.material.restitution >= 0){
  89375. c.restitution = bi.material.restitution * bj.material.restitution;
  89376. }
  89377. }
  89378. // c.setSpookParams(
  89379. // cm.contactEquationStiffness,
  89380. // cm.contactEquationRelaxation,
  89381. // dt
  89382. // );
  89383. solver.addEquation(c);
  89384. // // Add friction constraint equation
  89385. // if(mu > 0){
  89386. // // Create 2 tangent equations
  89387. // var mug = mu * gnorm;
  89388. // var reducedMass = (bi.invMass + bj.invMass);
  89389. // if(reducedMass > 0){
  89390. // reducedMass = 1/reducedMass;
  89391. // }
  89392. // var pool = frictionEquationPool;
  89393. // var c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  89394. // var c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  89395. // this.frictionEquations.push(c1, c2);
  89396. // c1.bi = c2.bi = bi;
  89397. // c1.bj = c2.bj = bj;
  89398. // c1.minForce = c2.minForce = -mug*reducedMass;
  89399. // c1.maxForce = c2.maxForce = mug*reducedMass;
  89400. // // Copy over the relative vectors
  89401. // c1.ri.copy(c.ri);
  89402. // c1.rj.copy(c.rj);
  89403. // c2.ri.copy(c.ri);
  89404. // c2.rj.copy(c.rj);
  89405. // // Construct tangents
  89406. // c.ni.tangents(c1.t, c2.t);
  89407. // // Set spook params
  89408. // c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  89409. // c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  89410. // c1.enabled = c2.enabled = c.enabled;
  89411. // // Add equations to solver
  89412. // solver.addEquation(c1);
  89413. // solver.addEquation(c2);
  89414. // }
  89415. if( bi.allowSleep &&
  89416. bi.type === Body.DYNAMIC &&
  89417. bi.sleepState === Body.SLEEPING &&
  89418. bj.sleepState === Body.AWAKE &&
  89419. bj.type !== Body.STATIC
  89420. ){
  89421. var speedSquaredB = bj.velocity.norm2() + bj.angularVelocity.norm2();
  89422. var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2);
  89423. if(speedSquaredB >= speedLimitSquaredB*2){
  89424. bi._wakeUpAfterNarrowphase = true;
  89425. }
  89426. }
  89427. if( bj.allowSleep &&
  89428. bj.type === Body.DYNAMIC &&
  89429. bj.sleepState === Body.SLEEPING &&
  89430. bi.sleepState === Body.AWAKE &&
  89431. bi.type !== Body.STATIC
  89432. ){
  89433. var speedSquaredA = bi.velocity.norm2() + bi.angularVelocity.norm2();
  89434. var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2);
  89435. if(speedSquaredA >= speedLimitSquaredA*2){
  89436. bj._wakeUpAfterNarrowphase = true;
  89437. }
  89438. }
  89439. // Now we know that i and j are in contact. Set collision matrix state
  89440. this.collisionMatrix.set(bi, bj, true);
  89441. if (!this.collisionMatrixPrevious.get(bi, bj)) {
  89442. // First contact!
  89443. // We reuse the collideEvent object, otherwise we will end up creating new objects for each new contact, even if there's no event listener attached.
  89444. World_step_collideEvent.body = bj;
  89445. World_step_collideEvent.contact = c;
  89446. bi.dispatchEvent(World_step_collideEvent);
  89447. World_step_collideEvent.body = bi;
  89448. bj.dispatchEvent(World_step_collideEvent);
  89449. }
  89450. }
  89451. if(doProfiling){
  89452. profile.makeContactConstraints = performance.now() - profilingStart;
  89453. profilingStart = performance.now();
  89454. }
  89455. // Wake up bodies
  89456. for(i=0; i!==N; i++){
  89457. var bi = bodies[i];
  89458. if(bi._wakeUpAfterNarrowphase){
  89459. bi.wakeUp();
  89460. bi._wakeUpAfterNarrowphase = false;
  89461. }
  89462. }
  89463. // Add user-added constraints
  89464. var Nconstraints = constraints.length;
  89465. for(i=0; i!==Nconstraints; i++){
  89466. var c = constraints[i];
  89467. c.update();
  89468. for(var j=0, Neq=c.equations.length; j!==Neq; j++){
  89469. var eq = c.equations[j];
  89470. solver.addEquation(eq);
  89471. }
  89472. }
  89473. // Solve the constrained system
  89474. solver.solve(dt,this);
  89475. if(doProfiling){
  89476. profile.solve = performance.now() - profilingStart;
  89477. }
  89478. // Remove all contacts from solver
  89479. solver.removeAllEquations();
  89480. // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details
  89481. var pow = Math.pow;
  89482. for(i=0; i!==N; i++){
  89483. var bi = bodies[i];
  89484. if(bi.type & DYNAMIC){ // Only for dynamic bodies
  89485. var ld = pow(1.0 - bi.linearDamping,dt);
  89486. var v = bi.velocity;
  89487. v.mult(ld,v);
  89488. var av = bi.angularVelocity;
  89489. if(av){
  89490. var ad = pow(1.0 - bi.angularDamping,dt);
  89491. av.mult(ad,av);
  89492. }
  89493. }
  89494. }
  89495. this.dispatchEvent(World_step_preStepEvent);
  89496. // Invoke pre-step callbacks
  89497. for(i=0; i!==N; i++){
  89498. var bi = bodies[i];
  89499. if(bi.preStep){
  89500. bi.preStep.call(bi);
  89501. }
  89502. }
  89503. // Leap frog
  89504. // vnew = v + h*f/m
  89505. // xnew = x + h*vnew
  89506. if(doProfiling){
  89507. profilingStart = performance.now();
  89508. }
  89509. var q = World_step_step_q;
  89510. var w = World_step_step_w;
  89511. var wq = World_step_step_wq;
  89512. var stepnumber = this.stepnumber;
  89513. var DYNAMIC_OR_KINEMATIC = Body.DYNAMIC | Body.KINEMATIC;
  89514. var quatNormalize = stepnumber % (this.quatNormalizeSkip+1) === 0;
  89515. var quatNormalizeFast = this.quatNormalizeFast;
  89516. var half_dt = dt * 0.5;
  89517. var PLANE = Shape.types.PLANE,
  89518. CONVEX = Shape.types.CONVEXPOLYHEDRON;
  89519. for(i=0; i!==N; i++){
  89520. var b = bodies[i],
  89521. force = b.force,
  89522. tau = b.torque;
  89523. if((b.type & DYNAMIC_OR_KINEMATIC) && b.sleepState !== Body.SLEEPING){ // Only for dynamic
  89524. var velo = b.velocity,
  89525. angularVelo = b.angularVelocity,
  89526. pos = b.position,
  89527. quat = b.quaternion,
  89528. invMass = b.invMass,
  89529. invInertia = b.invInertiaWorld;
  89530. velo.x += force.x * invMass * dt;
  89531. velo.y += force.y * invMass * dt;
  89532. velo.z += force.z * invMass * dt;
  89533. if(b.angularVelocity){
  89534. invInertia.vmult(tau,invI_tau_dt);
  89535. invI_tau_dt.mult(dt,invI_tau_dt);
  89536. invI_tau_dt.vadd(angularVelo,angularVelo);
  89537. }
  89538. // Use new velocity - leap frog
  89539. pos.x += velo.x * dt;
  89540. pos.y += velo.y * dt;
  89541. pos.z += velo.z * dt;
  89542. if(b.angularVelocity){
  89543. w.set(angularVelo.x, angularVelo.y, angularVelo.z, 0);
  89544. w.mult(quat,wq);
  89545. quat.x += half_dt * wq.x;
  89546. quat.y += half_dt * wq.y;
  89547. quat.z += half_dt * wq.z;
  89548. quat.w += half_dt * wq.w;
  89549. if(quatNormalize){
  89550. if(quatNormalizeFast){
  89551. quat.normalizeFast();
  89552. } else {
  89553. quat.normalize();
  89554. }
  89555. }
  89556. }
  89557. if(b.aabb){
  89558. b.aabbNeedsUpdate = true;
  89559. }
  89560. // Update world inertia
  89561. if(b.updateInertiaWorld){
  89562. b.updateInertiaWorld();
  89563. }
  89564. }
  89565. }
  89566. this.clearForces();
  89567. this.broadphase.dirty = true;
  89568. if(doProfiling){
  89569. profile.integrate = performance.now() - profilingStart;
  89570. }
  89571. // Update world time
  89572. this.time += dt;
  89573. this.stepnumber += 1;
  89574. this.dispatchEvent(World_step_postStepEvent);
  89575. // Invoke post-step callbacks
  89576. for(i=0; i!==N; i++){
  89577. var bi = bodies[i];
  89578. var postStep = bi.postStep;
  89579. if(postStep){
  89580. postStep.call(bi);
  89581. }
  89582. }
  89583. // Sleeping update
  89584. if(this.allowSleep){
  89585. for(i=0; i!==N; i++){
  89586. bodies[i].sleepTick(this.time);
  89587. }
  89588. }
  89589. };
  89590. /**
  89591. * Sets all body forces in the world to zero.
  89592. * @method clearForces
  89593. */
  89594. World.prototype.clearForces = function(){
  89595. var bodies = this.bodies;
  89596. var N = bodies.length;
  89597. for(var i=0; i !== N; i++){
  89598. var b = bodies[i],
  89599. force = b.force,
  89600. tau = b.torque;
  89601. b.force.set(0,0,0);
  89602. b.torque.set(0,0,0);
  89603. }
  89604. };
  89605. },{"../collision/AABB":3,"../collision/ArrayCollisionMatrix":4,"../collision/NaiveBroadphase":7,"../collision/Ray":9,"../collision/RaycastResult":10,"../equations/ContactEquation":19,"../equations/FrictionEquation":21,"../material/ContactMaterial":24,"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Shape":43,"../solver/GSSolver":46,"../utils/EventTarget":49,"../utils/TupleDictionary":52,"../utils/Vec3Pool":54,"./Narrowphase":55}]},{},[2])
  89606. (2)
  89607. });
  89608. /***/ }),
  89609. /* 16 */
  89610. /***/ (function(module, exports, __webpack_require__) {
  89611. /**
  89612. * from OimoPhysics DEV 1.1.0a AS3
  89613. * @author Saharan / http://el-ement.com/
  89614. *
  89615. * to Oimo.js 2015 JAVASCRIPT
  89616. * @author LoTh / http://lo-th.github.io/labs/
  89617. */
  89618. var OIMO = {
  89619. REVISION: "1.2",
  89620. // Global identification of next shape.
  89621. // This will be incremented every time a shape is created.
  89622. nextID: 0,
  89623. proxyID: 0,
  89624. // BroadPhase
  89625. BR_NULL: 0,
  89626. BR_BRUTE_FORCE: 1,
  89627. BR_SWEEP_AND_PRUNE: 2,
  89628. BR_BOUNDING_VOLUME_TREE: 3,
  89629. // body type
  89630. BODY_NULL: 0,
  89631. BODY_DYNAMIC: 1,
  89632. BODY_STATIC: 2,
  89633. // shape type
  89634. SHAPE_NULL: 0,
  89635. SHAPE_SPHERE: 1,
  89636. SHAPE_BOX: 2,
  89637. SHAPE_CYLINDER: 3,
  89638. SHAPE_TETRA: 4,
  89639. // joint type
  89640. JOINT_NULL: 0,
  89641. JOINT_DISTANCE: 1,
  89642. JOINT_BALL_AND_SOCKET: 2,
  89643. JOINT_HINGE: 3,
  89644. JOINT_WHEEL: 4,
  89645. JOINT_SLIDER: 5,
  89646. JOINT_PRISMATIC: 6,
  89647. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  89648. // scale all by 100 so object is between 10 to 10000 three unit.
  89649. WORLD_SCALE: 100,
  89650. INV_SCALE: 0.01,
  89651. // AABB aproximation
  89652. AABB_PROX: 0.005,
  89653. // Math function
  89654. sqrt: Math.sqrt,
  89655. abs: Math.abs,
  89656. floor: Math.floor,
  89657. cos: Math.cos,
  89658. sin: Math.sin,
  89659. acos: Math.acos,
  89660. asin: Math.asin,
  89661. atan2: Math.atan2,
  89662. round: Math.round,
  89663. pow: Math.pow,
  89664. max: Math.max,
  89665. min: Math.min,
  89666. random: Math.random,
  89667. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  89668. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  89669. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  89670. int: function (x) { return ~~x; },
  89671. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  89672. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  89673. degtorad: 0.0174532925199432957,
  89674. radtodeg: 57.295779513082320876,
  89675. PI: 3.141592653589793,
  89676. TwoPI: 6.283185307179586,
  89677. PI90: 1.570796326794896,
  89678. PI270: 4.712388980384689,
  89679. CustomError: null,
  89680. Error: function (Class, Msg) {
  89681. if (OIMO.CustomError == null) console.error(Class, Msg);
  89682. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  89683. }
  89684. };
  89685. var OIMO_ARRAY_TYPE;
  89686. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  89687. try {
  89688. (function (w) {
  89689. var perfNow;
  89690. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  89691. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  89692. var n = perfNowNames[i];
  89693. if (!!w['performance'][n]) {
  89694. perfNow = function () { return w['performance'][n]() };
  89695. break;
  89696. }
  89697. }
  89698. if (!perfNow) perfNow = Date.now;
  89699. //w.perfNow = perfNow;
  89700. OIMO.now = perfNow;
  89701. })(window);
  89702. } catch (e) { OIMO.now = function () { return 0; }; }
  89703. /**
  89704. * The class of physical computing world.
  89705. * You must be added to the world physical all computing objects
  89706. * @author saharan
  89707. * @author lo-th
  89708. */
  89709. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  89710. // The time between each step
  89711. this.timeStep = TimeStep || 0.01666; // 1/60;
  89712. // The number of iterations for constraint solvers.
  89713. this.numIterations = Iterations || 8;
  89714. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  89715. switch (BroadPhaseType || 2) {
  89716. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  89717. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  89718. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  89719. }
  89720. // This is the detailed information of the performance.
  89721. this.performance = null;
  89722. this.isNoStat = NoStat || false;
  89723. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  89724. // Whether the constraints randomizer is enabled or not.
  89725. this.enableRandomizer = true;
  89726. // The rigid body list
  89727. this.rigidBodies = null;
  89728. // number of rigid body
  89729. this.numRigidBodies = 0;
  89730. // The contact list
  89731. this.contacts = null;
  89732. this.unusedContacts = null;
  89733. // The number of contact
  89734. this.numContacts = 0;
  89735. // The number of contact points
  89736. this.numContactPoints = 0;
  89737. // The joint list
  89738. this.joints = null;
  89739. // The number of joints.
  89740. this.numJoints = 0;
  89741. // The number of simulation islands.
  89742. this.numIslands = 0;
  89743. // The gravity in the world.
  89744. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  89745. var numShapeTypes = 5;//4;//3;
  89746. this.detectors = [];
  89747. this.detectors.length = numShapeTypes;
  89748. var i = numShapeTypes;
  89749. while (i--) {
  89750. this.detectors[i] = [];
  89751. this.detectors[i].length = numShapeTypes;
  89752. }
  89753. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  89754. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  89755. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  89756. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  89757. // CYLINDER add
  89758. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  89759. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  89760. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  89761. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  89762. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  89763. // TETRA add
  89764. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  89765. this.randX = 65535;
  89766. this.randA = 98765;
  89767. this.randB = 123456789;
  89768. //this.maxIslandRigidBodies = 64;
  89769. this.islandRigidBodies = [];
  89770. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  89771. this.islandStack = [];
  89772. //this.islandStack.length = this.maxIslandRigidBodies;
  89773. //this.maxIslandConstraints = 128;
  89774. this.islandConstraints = [];
  89775. //this.islandConstraints.length = this.maxIslandConstraints;
  89776. };
  89777. OIMO.World.prototype = {
  89778. constructor: OIMO.World,
  89779. /**
  89780. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  89781. */
  89782. clear: function () {
  89783. this.randX = 65535;
  89784. while (this.joints !== null) {
  89785. this.removeJoint(this.joints);
  89786. }
  89787. while (this.contacts !== null) {
  89788. this.removeContact(this.contacts);
  89789. }
  89790. while (this.rigidBodies !== null) {
  89791. this.removeRigidBody(this.rigidBodies);
  89792. }
  89793. OIMO.nextID = 0;
  89794. OIMO.proxyID = 0;
  89795. },
  89796. /**
  89797. * I'll add a rigid body to the world.
  89798. * Rigid body that has been added will be the operands of each step.
  89799. * @param rigidBody Rigid body that you want to add
  89800. */
  89801. addRigidBody: function (rigidBody) {
  89802. if (rigidBody.parent) {
  89803. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  89804. }
  89805. rigidBody.parent = this;
  89806. rigidBody.awake();
  89807. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  89808. this.addShape(shape);
  89809. }
  89810. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  89811. this.rigidBodies = rigidBody;
  89812. this.numRigidBodies++;
  89813. },
  89814. /**
  89815. * I will remove the rigid body from the world.
  89816. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  89817. * @param rigidBody Rigid body to be removed
  89818. */
  89819. removeRigidBody: function (rigidBody) {
  89820. var remove = rigidBody;
  89821. if (remove.parent !== this) return;
  89822. remove.awake();
  89823. var js = remove.jointLink;
  89824. while (js != null) {
  89825. var joint = js.joint;
  89826. js = js.next;
  89827. this.removeJoint(joint);
  89828. }
  89829. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  89830. this.removeShape(shape);
  89831. }
  89832. var prev = remove.prev;
  89833. var next = remove.next;
  89834. if (prev !== null) prev.next = next;
  89835. if (next !== null) next.prev = prev;
  89836. if (this.rigidBodies == remove) this.rigidBodies = next;
  89837. remove.prev = null;
  89838. remove.next = null;
  89839. remove.parent = null;
  89840. this.numRigidBodies--;
  89841. },
  89842. getByName: function (name) {
  89843. var result = null;
  89844. var body = this.rigidBodies;
  89845. while (body !== null) {
  89846. if (body.name !== " " && body.name === name) result = body;
  89847. body = body.next;
  89848. }
  89849. var joint = this.joints;
  89850. while (joint !== null) {
  89851. if (joint.name !== "" && joint.name === name) result = joint;
  89852. joint = joint.next;
  89853. }
  89854. return result;
  89855. },
  89856. /**
  89857. * I'll add a shape to the world..
  89858. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  89859. * Shape will be added to the world automatically, please do not call from outside this method.
  89860. * @param shape Shape you want to add
  89861. */
  89862. addShape: function (shape) {
  89863. if (!shape.parent || !shape.parent.parent) {
  89864. OIMO.Error("World", "It is not possible to be added alone to shape world");
  89865. }
  89866. shape.proxy = this.broadPhase.createProxy(shape);
  89867. shape.updateProxy();
  89868. this.broadPhase.addProxy(shape.proxy);
  89869. },
  89870. /**
  89871. * I will remove the shape from the world.
  89872. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  89873. * Shape will be added to the world automatically, please do not call from outside this method.
  89874. * @param shape Shape you want to delete
  89875. */
  89876. removeShape: function (shape) {
  89877. this.broadPhase.removeProxy(shape.proxy);
  89878. shape.proxy = null;
  89879. },
  89880. /**
  89881. * I'll add a joint to the world.
  89882. * Joint that has been added will be the operands of each step.
  89883. * @param shape Joint to be added
  89884. */
  89885. addJoint: function (joint) {
  89886. if (joint.parent) {
  89887. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  89888. }
  89889. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  89890. this.joints = joint;
  89891. joint.parent = this;
  89892. this.numJoints++;
  89893. joint.awake();
  89894. joint.attach();
  89895. },
  89896. /**
  89897. * I will remove the joint from the world.
  89898. * Joint that has been added will be the operands of each step.
  89899. * @param shape Joint to be deleted
  89900. */
  89901. removeJoint: function (joint) {
  89902. var remove = joint;
  89903. var prev = remove.prev;
  89904. var next = remove.next;
  89905. if (prev !== null) prev.next = next;
  89906. if (next !== null) next.prev = prev;
  89907. if (this.joints == remove) this.joints = next;
  89908. remove.prev = null;
  89909. remove.next = null;
  89910. this.numJoints--;
  89911. remove.awake();
  89912. remove.detach();
  89913. remove.parent = null;
  89914. },
  89915. worldscale: function (scale) {
  89916. OIMO.WORLD_SCALE = scale || 100;
  89917. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  89918. },
  89919. addContact: function (s1, s2) {
  89920. var newContact;
  89921. if (this.unusedContacts !== null) {
  89922. newContact = this.unusedContacts;
  89923. this.unusedContacts = this.unusedContacts.next;
  89924. } else {
  89925. newContact = new OIMO.Contact();
  89926. }
  89927. newContact.attach(s1, s2);
  89928. newContact.detector = this.detectors[s1.type][s2.type];
  89929. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  89930. this.contacts = newContact;
  89931. this.numContacts++;
  89932. },
  89933. removeContact: function (contact) {
  89934. var prev = contact.prev;
  89935. var next = contact.next;
  89936. if (next) next.prev = prev;
  89937. if (prev) prev.next = next;
  89938. if (this.contacts == contact) this.contacts = next;
  89939. contact.prev = null;
  89940. contact.next = null;
  89941. contact.detach();
  89942. contact.next = this.unusedContacts;
  89943. this.unusedContacts = contact;
  89944. this.numContacts--;
  89945. },
  89946. checkContact: function (name1, name2) {
  89947. var n1, n2;
  89948. var contact = this.contacts;
  89949. while (contact !== null) {
  89950. n1 = contact.body1.name || ' ';
  89951. n2 = contact.body2.name || ' ';
  89952. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  89953. else contact = contact.next;
  89954. }
  89955. return false;
  89956. },
  89957. callSleep: function (body) {
  89958. if (!body.allowSleep) return false;
  89959. if (body.linearVelocity.lengthSq() > 0.04) return false;
  89960. if (body.angularVelocity.lengthSq() > 0.25) return false;
  89961. return true;
  89962. },
  89963. /**
  89964. * I will proceed only time step seconds time of World.
  89965. */
  89966. step: function () {
  89967. var time0, time1, time2, time3;
  89968. var stat = !this.isNoStat ? true : false;
  89969. if (stat) time0 = OIMO.now();
  89970. var body = this.rigidBodies;
  89971. while (body !== null) {
  89972. body.addedToIsland = false;
  89973. if (body.sleeping) {
  89974. if (
  89975. body.linearVelocity.testZero() ||
  89976. body.angularVelocity.testZero() ||
  89977. body.position.testDiff(body.sleepPosition) ||
  89978. body.orientation.testDiff(body.sleepOrientation)
  89979. ) body.awake(); // awake the body
  89980. }
  89981. body = body.next;
  89982. }
  89983. //------------------------------------------------------
  89984. // UPDATE CONTACT
  89985. //------------------------------------------------------
  89986. // broad phase
  89987. if (stat) time1 = OIMO.now();
  89988. this.broadPhase.detectPairs();
  89989. var pairs = this.broadPhase.pairs;
  89990. var i = this.broadPhase.numPairs;
  89991. //do{
  89992. while (i--) {
  89993. //for(var i=0, l=numPairs; i<l; i++){
  89994. var pair = pairs[i];
  89995. var s1;
  89996. var s2;
  89997. if (pair.shape1.id < pair.shape2.id) {
  89998. s1 = pair.shape1;
  89999. s2 = pair.shape2;
  90000. } else {
  90001. s1 = pair.shape2;
  90002. s2 = pair.shape1;
  90003. }
  90004. var link;
  90005. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  90006. else link = s2.contactLink;
  90007. var exists = false;
  90008. while (link) {
  90009. var contact = link.contact;
  90010. if (contact.shape1 == s1 && contact.shape2 == s2) {
  90011. contact.persisting = true;
  90012. exists = true;// contact already exists
  90013. break;
  90014. }
  90015. link = link.next;
  90016. }
  90017. if (!exists) {
  90018. this.addContact(s1, s2);
  90019. }
  90020. }// while(i-- >0);
  90021. if (stat) {
  90022. time2 = OIMO.now();
  90023. this.performance.broadPhaseTime = time2 - time1;
  90024. }
  90025. // update & narrow phase
  90026. this.numContactPoints = 0;
  90027. contact = this.contacts;
  90028. while (contact !== null) {
  90029. if (!contact.persisting) {
  90030. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  90031. /*var aabb1=contact.shape1.aabb;
  90032. var aabb2=contact.shape2.aabb;
  90033. if(
  90034. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  90035. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  90036. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  90037. ){*/
  90038. var next = contact.next;
  90039. this.removeContact(contact);
  90040. contact = next;
  90041. continue;
  90042. }
  90043. }
  90044. var b1 = contact.body1;
  90045. var b2 = contact.body2;
  90046. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  90047. contact.updateManifold();
  90048. }
  90049. this.numContactPoints += contact.manifold.numPoints;
  90050. contact.persisting = false;
  90051. contact.constraint.addedToIsland = false;
  90052. contact = contact.next;
  90053. }
  90054. if (stat) {
  90055. time3 = OIMO.now();
  90056. this.performance.narrowPhaseTime = time3 - time2;
  90057. }
  90058. //------------------------------------------------------
  90059. // SOLVE ISLANDS
  90060. //------------------------------------------------------
  90061. var invTimeStep = 1 / this.timeStep;
  90062. //var body;
  90063. var joint;
  90064. var constraint;
  90065. //var num;
  90066. for (joint = this.joints; joint !== null; joint = joint.next) {
  90067. joint.addedToIsland = false;
  90068. }
  90069. // clear old island array
  90070. this.islandRigidBodies = [];
  90071. this.islandConstraints = [];
  90072. this.islandStack = [];
  90073. // expand island buffers
  90074. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  90075. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  90076. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  90077. this.islandRigidBodies=[];
  90078. this.islandStack=[];
  90079. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  90080. this.islandStack.length = this.maxIslandRigidBodies;
  90081. }
  90082. var numConstraints=this.numJoints+this.numContacts;
  90083. if(this.maxIslandConstraints<numConstraints){
  90084. this.maxIslandConstraints=numConstraints<<1;
  90085. //this.maxIslandConstraints=numConstraints*2;
  90086. this.islandConstraints=[];
  90087. this.islandConstraints.length = this.maxIslandConstraints;
  90088. }*/
  90089. time1 = OIMO.now();
  90090. this.numIslands = 0;
  90091. // build and solve simulation islands
  90092. for (var base = this.rigidBodies; base !== null; base = base.next) {
  90093. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  90094. if (base.isLonely()) {// update single body
  90095. if (base.isDynamic) {
  90096. base.linearVelocity.addTime(this.gravity, this.timeStep);
  90097. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  90098. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  90099. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  90100. }
  90101. if (this.callSleep(base)) {
  90102. base.sleepTime += this.timeStep;
  90103. if (base.sleepTime > 0.5) base.sleep();
  90104. else base.updatePosition(this.timeStep);
  90105. } else {
  90106. base.sleepTime = 0;
  90107. base.updatePosition(this.timeStep);
  90108. }
  90109. this.numIslands++;
  90110. continue;
  90111. }
  90112. var islandNumRigidBodies = 0;
  90113. var islandNumConstraints = 0;
  90114. var stackCount = 1;
  90115. // add rigid body to stack
  90116. this.islandStack[0] = base;
  90117. base.addedToIsland = true;
  90118. // build an island
  90119. do {
  90120. // get rigid body from stack
  90121. body = this.islandStack[--stackCount];
  90122. this.islandStack[stackCount] = null;
  90123. body.sleeping = false;
  90124. // add rigid body to the island
  90125. this.islandRigidBodies[islandNumRigidBodies++] = body;
  90126. if (body.isStatic) continue;
  90127. // search connections
  90128. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  90129. var contact = cs.contact;
  90130. constraint = contact.constraint;
  90131. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  90132. // add constraint to the island
  90133. this.islandConstraints[islandNumConstraints++] = constraint;
  90134. constraint.addedToIsland = true;
  90135. var next = cs.body;
  90136. if (next.addedToIsland) continue;
  90137. // add rigid body to stack
  90138. this.islandStack[stackCount++] = next;
  90139. next.addedToIsland = true;
  90140. }
  90141. for (var js = body.jointLink; js !== null; js = js.next) {
  90142. constraint = js.joint;
  90143. if (constraint.addedToIsland) continue;// ignore
  90144. // add constraint to the island
  90145. this.islandConstraints[islandNumConstraints++] = constraint;
  90146. constraint.addedToIsland = true;
  90147. next = js.body;
  90148. if (next.addedToIsland || !next.isDynamic) continue;
  90149. // add rigid body to stack
  90150. this.islandStack[stackCount++] = next;
  90151. next.addedToIsland = true;
  90152. }
  90153. } while (stackCount != 0);
  90154. // update velocities
  90155. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  90156. /*var gx=this.gravity.x*this.timeStep;
  90157. var gy=this.gravity.y*this.timeStep;
  90158. var gz=this.gravity.z*this.timeStep;*/
  90159. var j = islandNumRigidBodies;
  90160. while (j--) {
  90161. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  90162. body = this.islandRigidBodies[j];
  90163. if (body.isDynamic) {
  90164. body.linearVelocity.addEqual(gVel);
  90165. /*body.linearVelocity.x+=gx;
  90166. body.linearVelocity.y+=gy;
  90167. body.linearVelocity.z+=gz;*/
  90168. }
  90169. }
  90170. // randomizing order
  90171. if (this.enableRandomizer) {
  90172. //for(var j=1, l=islandNumConstraints; j<l; j++){
  90173. j = islandNumConstraints;
  90174. while (j--) {
  90175. if (j !== 0) {
  90176. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  90177. constraint = this.islandConstraints[j];
  90178. this.islandConstraints[j] = this.islandConstraints[swap];
  90179. this.islandConstraints[swap] = constraint;
  90180. }
  90181. }
  90182. }
  90183. // solve contraints
  90184. j = islandNumConstraints;
  90185. while (j--) {
  90186. //for(j=0, l=islandNumConstraints; j<l; j++){
  90187. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  90188. }
  90189. var k = this.numIterations;
  90190. while (k--) {
  90191. //for(var k=0, l=this.numIterations; k<l; k++){
  90192. j = islandNumConstraints;
  90193. while (j--) {
  90194. //for(j=0, m=islandNumConstraints; j<m; j++){
  90195. this.islandConstraints[j].solve();// main-solve
  90196. }
  90197. }
  90198. j = islandNumConstraints;
  90199. while (j--) {
  90200. //for(j=0, l=islandNumConstraints; j<l; j++){
  90201. this.islandConstraints[j].postSolve();// post-solve
  90202. this.islandConstraints[j] = null;// gc
  90203. }
  90204. // sleeping check
  90205. var sleepTime = 10;
  90206. j = islandNumRigidBodies;
  90207. while (j--) {
  90208. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  90209. body = this.islandRigidBodies[j];
  90210. if (this.callSleep(body)) {
  90211. body.sleepTime += this.timeStep;
  90212. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  90213. } else {
  90214. body.sleepTime = 0;
  90215. sleepTime = 0;
  90216. continue;
  90217. }
  90218. }
  90219. if (sleepTime > 0.5) {
  90220. // sleep the island
  90221. j = islandNumRigidBodies;
  90222. while (j--) {
  90223. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  90224. this.islandRigidBodies[j].sleep();
  90225. this.islandRigidBodies[j] = null;// gc
  90226. }
  90227. } else {
  90228. // update positions
  90229. j = islandNumRigidBodies;
  90230. while (j--) {
  90231. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  90232. this.islandRigidBodies[j].updatePosition(this.timeStep);
  90233. this.islandRigidBodies[j] = null;// gc
  90234. }
  90235. }
  90236. this.numIslands++;
  90237. }
  90238. if (stat) {
  90239. time2 = OIMO.now();
  90240. this.performance.solvingTime = time2 - time1;
  90241. //------------------------------------------------------
  90242. // END SIMULATION
  90243. //------------------------------------------------------
  90244. time2 = OIMO.now();
  90245. // fps update
  90246. this.performance.upfps();
  90247. this.performance.totalTime = time2 - time0;
  90248. }
  90249. }
  90250. }
  90251. /**
  90252. * The class of rigid body.
  90253. * Rigid body has the shape of a single or multiple collision processing,
  90254. * I can set the parameters individually.
  90255. * @author saharan
  90256. */
  90257. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  90258. this.name = " ";
  90259. // The maximum number of shapes that can be added to a one rigid.
  90260. this.MAX_SHAPES = 64;//64;
  90261. this.prev = null;
  90262. this.next = null;
  90263. // I represent the kind of rigid body.
  90264. // Please do not change from the outside this variable.
  90265. // If you want to change the type of rigid body, always
  90266. // Please specify the type you want to set the arguments of setupMass method.
  90267. this.type = OIMO.BODY_NULL;
  90268. this.massInfo = new OIMO.MassInfo();
  90269. // It is the world coordinate of the center of gravity.
  90270. this.position = new OIMO.Vec3(x, y, z);
  90271. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  90272. this.newPosition = new OIMO.Vec3();
  90273. this.controlPos = false;
  90274. this.newOrientation = new OIMO.Quat();
  90275. this.newRotation = new OIMO.Vec3();
  90276. this.currentRotation = new OIMO.Vec3();
  90277. this.controlRot = false;
  90278. this.controlRotInTime = false;
  90279. // Is the translational velocity.
  90280. this.linearVelocity = new OIMO.Vec3();
  90281. // Is the angular velocity.
  90282. this.angularVelocity = new OIMO.Vec3();
  90283. // return matrix for three.js
  90284. this.matrix = new OIMO.Mat44();
  90285. //--------------------------------------------
  90286. // Please do not change from the outside this variables.
  90287. //--------------------------------------------
  90288. // It is a world that rigid body has been added.
  90289. this.parent = null;
  90290. this.contactLink = null;
  90291. this.numContacts = 0;
  90292. // An array of shapes that are included in the rigid body.
  90293. this.shapes = null;
  90294. // The number of shapes that are included in the rigid body.
  90295. this.numShapes = 0;
  90296. // It is the link array of joint that is connected to the rigid body.
  90297. this.jointLink = null;
  90298. // The number of joints that are connected to the rigid body.
  90299. this.numJoints = 0;
  90300. // It is the world coordinate of the center of gravity in the sleep just before.
  90301. this.sleepPosition = new OIMO.Vec3();
  90302. // It is a quaternion that represents the attitude of sleep just before.
  90303. this.sleepOrientation = new OIMO.Quat();
  90304. // I will show this rigid body to determine whether it is a rigid body static.
  90305. this.isStatic = false;
  90306. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  90307. this.isDynamic = false;
  90308. // It is a rotation matrix representing the orientation.
  90309. this.rotation = new OIMO.Mat33();
  90310. //--------------------------------------------
  90311. // It will be recalculated automatically from the shape, which is included.
  90312. //--------------------------------------------
  90313. // This is the weight.
  90314. this.mass = NaN;
  90315. // It is the reciprocal of the mass.
  90316. this.inverseMass = NaN;
  90317. // It is the inverse of the inertia tensor in the world system.
  90318. this.inverseInertia = new OIMO.Mat33();
  90319. // It is the inertia tensor in the initial state.
  90320. this.localInertia = new OIMO.Mat33();
  90321. // It is the inverse of the inertia tensor in the initial state.
  90322. this.inverseLocalInertia = new OIMO.Mat33();
  90323. // I indicates rigid body whether it has been added to the simulation Island.
  90324. this.addedToIsland = false;
  90325. // It shows how to sleep rigid body.
  90326. this.allowSleep = true;
  90327. // This is the time from when the rigid body at rest.
  90328. this.sleepTime = 0;
  90329. // I shows rigid body to determine whether it is a sleep state.
  90330. this.sleeping = false;
  90331. };
  90332. OIMO.RigidBody.prototype = {
  90333. constructor: OIMO.RigidBody,
  90334. /**
  90335. * I'll add a shape to rigid body.
  90336. * If you add a shape, please call the setupMass method to step up to the start of the next.
  90337. * @param shape shape to Add
  90338. */
  90339. addShape: function (shape) {
  90340. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  90341. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  90342. this.shapes = shape;
  90343. shape.parent = this;
  90344. if (this.parent) this.parent.addShape(shape);
  90345. this.numShapes++;
  90346. },
  90347. /**
  90348. * I will delete the shape from the rigid body.
  90349. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  90350. * @param shape shape to Delete
  90351. */
  90352. removeShape: function (shape) {
  90353. var remove = shape;
  90354. if (remove.parent != this) return;
  90355. var prev = remove.prev;
  90356. var next = remove.next;
  90357. if (prev != null) prev.next = next;
  90358. if (next != null) next.prev = prev;
  90359. if (this.shapes == remove) this.shapes = next;
  90360. remove.prev = null;
  90361. remove.next = null;
  90362. remove.parent = null;
  90363. if (this.parent) this.parent.removeShape(remove);
  90364. this.numShapes--;
  90365. },
  90366. remove: function () {
  90367. this.dispose();
  90368. },
  90369. dispose: function () {
  90370. this.parent.removeRigidBody(this);
  90371. },
  90372. checkContact: function (name) {
  90373. this.parent.checkContact(this.name, name);
  90374. },
  90375. /**
  90376. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  90377. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  90378. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  90379. * the rigid body's position will be adjusted to the center of gravity.
  90380. * @param type
  90381. * @param adjustPosition
  90382. */
  90383. setupMass: function (type, AdjustPosition) {
  90384. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  90385. this.type = type || OIMO.BODY_DYNAMIC;
  90386. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  90387. this.isStatic = this.type == OIMO.BODY_STATIC;
  90388. this.mass = 0;
  90389. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  90390. var te = this.localInertia.elements;
  90391. //
  90392. var tmpM = new OIMO.Mat33();
  90393. var tmpV = new OIMO.Vec3();
  90394. for (var shape = this.shapes; shape != null; shape = shape.next) {
  90395. shape.calculateMassInfo(this.massInfo);
  90396. var shapeMass = this.massInfo.mass;
  90397. var relX = shape.relativePosition.x;
  90398. var relY = shape.relativePosition.y;
  90399. var relZ = shape.relativePosition.z;
  90400. /*tmpV.x+=relX*shapeMass;
  90401. tmpV.y+=relY*shapeMass;
  90402. tmpV.z+=relZ*shapeMass;*/
  90403. tmpV.addScale(shape.relativePosition, shapeMass);
  90404. this.mass += shapeMass;
  90405. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  90406. this.localInertia.addEqual(tmpM);
  90407. // add offset inertia
  90408. te[0] += shapeMass * (relY * relY + relZ * relZ);
  90409. te[4] += shapeMass * (relX * relX + relZ * relZ);
  90410. te[8] += shapeMass * (relX * relX + relY * relY);
  90411. var xy = shapeMass * relX * relY;
  90412. var yz = shapeMass * relY * relZ;
  90413. var zx = shapeMass * relZ * relX;
  90414. te[1] -= xy;
  90415. te[3] -= xy;
  90416. te[2] -= yz;
  90417. te[6] -= yz;
  90418. te[5] -= zx;
  90419. te[7] -= zx;
  90420. }
  90421. this.inverseMass = 1 / this.mass;
  90422. tmpV.scaleEqual(this.inverseMass);
  90423. if (adjustPosition) {
  90424. this.position.addEqual(tmpV);
  90425. for (shape = this.shapes; shape != null; shape = shape.next) {
  90426. shape.relativePosition.subEqual(tmpV);
  90427. }
  90428. // subtract offset inertia
  90429. relX = tmpV.x;
  90430. relY = tmpV.y;
  90431. relZ = tmpV.z;
  90432. //var te = this.localInertia.elements;
  90433. te[0] -= this.mass * (relY * relY + relZ * relZ);
  90434. te[4] -= this.mass * (relX * relX + relZ * relZ);
  90435. te[8] -= this.mass * (relX * relX + relY * relY);
  90436. xy = this.mass * relX * relY;
  90437. yz = this.mass * relY * relZ;
  90438. zx = this.mass * relZ * relX;
  90439. te[1] += xy;
  90440. te[3] += xy;
  90441. te[2] += yz;
  90442. te[6] += yz;
  90443. te[5] += zx;
  90444. te[7] += zx;
  90445. }
  90446. this.inverseLocalInertia.invert(this.localInertia);
  90447. if (this.type == OIMO.BODY_STATIC) {
  90448. this.inverseMass = 0;
  90449. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  90450. }
  90451. this.syncShapes();
  90452. this.awake();
  90453. },
  90454. /**
  90455. * Awake the rigid body.
  90456. */
  90457. awake: function () {
  90458. if (!this.allowSleep || !this.sleeping) return;
  90459. this.sleeping = false;
  90460. this.sleepTime = 0;
  90461. // awake connected constraints
  90462. var cs = this.contactLink;
  90463. while (cs != null) {
  90464. cs.body.sleepTime = 0;
  90465. cs.body.sleeping = false;
  90466. cs = cs.next;
  90467. }
  90468. var js = this.jointLink;
  90469. while (js != null) {
  90470. js.body.sleepTime = 0;
  90471. js.body.sleeping = false;
  90472. js = js.next;
  90473. }
  90474. for (var shape = this.shapes; shape != null; shape = shape.next) {
  90475. shape.updateProxy();
  90476. }
  90477. },
  90478. /**
  90479. * Sleep the rigid body.
  90480. */
  90481. sleep: function () {
  90482. if (!this.allowSleep || this.sleeping) return;
  90483. this.linearVelocity.set(0, 0, 0);
  90484. this.angularVelocity.set(0, 0, 0);
  90485. this.sleepPosition.copy(this.position);
  90486. this.sleepOrientation.copy(this.orientation);
  90487. /*this.linearVelocity.x=0;
  90488. this.linearVelocity.y=0;
  90489. this.linearVelocity.z=0;
  90490. this.angularVelocity.x=0;
  90491. this.angularVelocity.y=0;
  90492. this.angularVelocity.z=0;
  90493. this.sleepPosition.x=this.position.x;
  90494. this.sleepPosition.y=this.position.y;
  90495. this.sleepPosition.z=this.position.z;*/
  90496. /*this.sleepOrientation.s=this.orientation.s;
  90497. this.sleepOrientation.x=this.orientation.x;
  90498. this.sleepOrientation.y=this.orientation.y;
  90499. this.sleepOrientation.z=this.orientation.z;*/
  90500. this.sleepTime = 0;
  90501. this.sleeping = true;
  90502. for (var shape = this.shapes; shape != null; shape = shape.next) {
  90503. shape.updateProxy();
  90504. }
  90505. },
  90506. /**
  90507. * Get whether the rigid body has not any connection with others.
  90508. * @return
  90509. */
  90510. isLonely: function () {
  90511. return this.numJoints == 0 && this.numContacts == 0;
  90512. },
  90513. /**
  90514. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  90515. * This method is invoked automatically when calling the step of the World,
  90516. * There is no need to call from outside usually.
  90517. * @param timeStep time
  90518. */
  90519. updatePosition: function (timeStep) {
  90520. switch (this.type) {
  90521. case OIMO.BODY_STATIC:
  90522. this.linearVelocity.set(0, 0, 0);
  90523. this.angularVelocity.set(0, 0, 0);
  90524. // ONLY FOR TEST
  90525. if (this.controlPos) {
  90526. this.position.copy(this.newPosition);
  90527. this.controlPos = false;
  90528. }
  90529. if (this.controlRot) {
  90530. this.orientation.copy(this.newOrientation);
  90531. this.controlRot = false;
  90532. }
  90533. /*this.linearVelocity.x=0;
  90534. this.linearVelocity.y=0;
  90535. this.linearVelocity.z=0;
  90536. this.angularVelocity.x=0;
  90537. this.angularVelocity.y=0;
  90538. this.angularVelocity.z=0;*/
  90539. break;
  90540. case OIMO.BODY_DYNAMIC:
  90541. if (this.controlPos) {
  90542. this.angularVelocity.set(0, 0, 0);
  90543. this.linearVelocity.set(0, 0, 0);
  90544. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  90545. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  90546. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  90547. this.controlPos = false;
  90548. }
  90549. if (this.controlRot) {
  90550. this.angularVelocity.set(0, 0, 0);
  90551. this.orientation.copy(this.newOrientation);
  90552. //var t=timeStep//*0.5;
  90553. //var q = new OIMO.Quat();
  90554. //q.sub(this.newOrientation, this.orientation);
  90555. //q.normalize(q);
  90556. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  90557. q.x = (this.newOrientation.x - this.orientation.x)/t;
  90558. q.y = (this.newOrientation.y - this.orientation.y)/t;
  90559. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  90560. //this.angularVelocity.applyQuaternion(q);
  90561. //this.angularVelocity.x = this.angularVelocity.x/t;
  90562. //this.angularVelocity.y = this.angularVelocity.y/t;
  90563. //this.angularVelocity.z = this.angularVelocity.z/t;
  90564. this.controlRot = false;
  90565. }
  90566. this.position.addTime(this.linearVelocity, timeStep);
  90567. this.orientation.addTime(this.angularVelocity, timeStep);
  90568. break;
  90569. default: OIMO.Error("RigidBody", "Invalid type.");
  90570. }
  90571. this.syncShapes();
  90572. },
  90573. rotateInertia: function (rot, inertia, out) {
  90574. var tm1 = rot.elements;
  90575. var tm2 = inertia.elements;
  90576. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  90577. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  90578. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  90579. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  90580. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  90581. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  90582. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  90583. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  90584. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  90585. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  90586. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  90587. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  90588. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  90589. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  90590. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  90591. var oe = out.elements;
  90592. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  90593. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  90594. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  90595. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  90596. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  90597. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  90598. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  90599. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  90600. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  90601. },
  90602. syncShapes: function () {
  90603. var s = this.orientation.s;
  90604. var x = this.orientation.x;
  90605. var y = this.orientation.y;
  90606. var z = this.orientation.z;
  90607. var x2 = 2 * x;
  90608. var y2 = 2 * y;
  90609. var z2 = 2 * z;
  90610. var xx = x * x2;
  90611. var yy = y * y2;
  90612. var zz = z * z2;
  90613. var xy = x * y2;
  90614. var yz = y * z2;
  90615. var xz = x * z2;
  90616. var sx = s * x2;
  90617. var sy = s * y2;
  90618. var sz = s * z2;
  90619. var tr = this.rotation.elements;
  90620. tr[0] = 1 - yy - zz;
  90621. tr[1] = xy - sz;
  90622. tr[2] = xz + sy;
  90623. tr[3] = xy + sz;
  90624. tr[4] = 1 - xx - zz;
  90625. tr[5] = yz - sx;
  90626. tr[6] = xz - sy;
  90627. tr[7] = yz + sx;
  90628. tr[8] = 1 - xx - yy;
  90629. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  90630. for (var shape = this.shapes; shape != null; shape = shape.next) {
  90631. //var relPos=shape.relativePosition;
  90632. //var relRot=shape.relativeRotation;
  90633. //var rot=shape.rotation;
  90634. /*var lx=relPos.x;
  90635. var ly=relPos.y;
  90636. var lz=relPos.z;
  90637. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  90638. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  90639. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  90640. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  90641. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  90642. // add by QuaziKb
  90643. shape.rotation.mul(this.rotation, shape.relativeRotation);
  90644. shape.updateProxy();
  90645. }
  90646. },
  90647. applyImpulse: function (position, force) {
  90648. this.linearVelocity.addScale(force, this.inverseMass);
  90649. /*this.linearVelocity.x+=force.x*this.inverseMass;
  90650. this.linearVelocity.y+=force.y*this.inverseMass;
  90651. this.linearVelocity.z+=force.z*this.inverseMass;*/
  90652. var rel = new OIMO.Vec3();
  90653. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  90654. this.angularVelocity.addEqual(rel);
  90655. /*this.angularVelocity.x+=rel.x;
  90656. this.angularVelocity.y+=rel.y;
  90657. this.angularVelocity.z+=rel.z;*/
  90658. },
  90659. //---------------------------------------------
  90660. //
  90661. // FOR THREE JS
  90662. //
  90663. //---------------------------------------------
  90664. rotationVectToQuad: function (rot) {
  90665. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  90666. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  90667. },
  90668. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  90669. var len = ax * ax + ay * ay + az * az;
  90670. if (len > 0) {
  90671. len = 1 / OIMO.sqrt(len);
  90672. ax *= len;
  90673. ay *= len;
  90674. az *= len;
  90675. }
  90676. var sin = OIMO.sin(rad * 0.5);
  90677. var cos = OIMO.cos(rad * 0.5);
  90678. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  90679. },
  90680. //---------------------------------------------
  90681. // SET DYNAMIQUE POSITION AND ROTATION
  90682. //---------------------------------------------
  90683. setPosition: function (pos) {
  90684. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  90685. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  90686. this.controlPos = true;
  90687. },
  90688. setQuaternion: function (q) {
  90689. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  90690. this.newOrientation.set(q.x, q.y, q.z, q.w);
  90691. this.controlRot = true;
  90692. },
  90693. setRotation: function (rot) {
  90694. this.newOrientation = this.rotationVectToQuad(rot);
  90695. this.controlRot = true;
  90696. },
  90697. //---------------------------------------------
  90698. // RESET DYNAMIQUE POSITION AND ROTATION
  90699. //---------------------------------------------
  90700. resetPosition: function (x, y, z) {
  90701. this.linearVelocity.set(0, 0, 0);
  90702. this.angularVelocity.set(0, 0, 0);
  90703. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  90704. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  90705. this.awake();
  90706. },
  90707. resetQuaternion: function (q) {
  90708. this.angularVelocity.set(0, 0, 0);
  90709. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  90710. this.awake();
  90711. },
  90712. resetRotation: function (x, y, z) {
  90713. this.angularVelocity.set(0, 0, 0);
  90714. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  90715. this.awake();
  90716. },
  90717. //---------------------------------------------
  90718. // GET POSITION AND ROTATION
  90719. //---------------------------------------------
  90720. getPosition: function () {
  90721. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  90722. },
  90723. getRotation: function () {
  90724. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  90725. },
  90726. getQuaternion: function () {
  90727. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  90728. },
  90729. getMatrix: function () {
  90730. var m = this.matrix.elements;
  90731. var r, p;
  90732. if (!this.sleeping) {
  90733. // rotation matrix
  90734. r = this.rotation.elements;
  90735. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  90736. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  90737. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  90738. // position matrix
  90739. p = this.position;
  90740. m[12] = p.x * OIMO.WORLD_SCALE;
  90741. m[13] = p.y * OIMO.WORLD_SCALE;
  90742. m[14] = p.z * OIMO.WORLD_SCALE;
  90743. // sleep or not ?
  90744. m[15] = 0;
  90745. } else {
  90746. m[15] = 1;
  90747. }
  90748. return m;
  90749. }
  90750. };
  90751. /**
  90752. * The main class of body.
  90753. * is for simplify creation process and data access of rigidRody
  90754. * Rigid body has the shape of a single or multiple collision processing,
  90755. * all setting in object
  90756. *
  90757. * @author loth
  90758. */
  90759. OIMO.Body = function (Obj) {
  90760. var obj = Obj || {};
  90761. if (!obj.world) return;
  90762. if (obj.type === undefined) obj.type = "box";
  90763. this.name = obj.name || '';
  90764. // obsolete use world.add(obj)
  90765. this.body = obj.world.add(obj);
  90766. /*
  90767. // the world where i am
  90768. this.parent = obj.world;
  90769. // Yep my name
  90770. this.name = obj.name || '';
  90771. // I'm dynamique or not
  90772. var move = obj.move || false;
  90773. // I can sleep or not
  90774. var noSleep = obj.noSleep || false;
  90775. // My start position
  90776. var p = obj.pos || [0,0,0];
  90777. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  90778. // My size
  90779. var s = obj.size || [1,1,1];
  90780. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  90781. // My rotation in degre
  90782. var rot = obj.rot || [0,0,0];
  90783. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  90784. var r = [];
  90785. for (var i=0; i<rot.length/3; i++){
  90786. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  90787. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  90788. }
  90789. // My physics setting
  90790. var sc = obj.sc || new OIMO.ShapeConfig();
  90791. if(obj.config){
  90792. // The density of the shape.
  90793. sc.density = obj.config[0] || 1;
  90794. // The coefficient of friction of the shape.
  90795. sc.friction = obj.config[1] || 0.4;
  90796. // The coefficient of restitution of the shape.
  90797. sc.restitution = obj.config[2] || 0.2;
  90798. // The bits of the collision groups to which the shape belongs.
  90799. sc.belongsTo = obj.config[3] || 1;
  90800. // The bits of the collision groups with which the shape collides.
  90801. sc.collidesWith = obj.config[4] || 0xffffffff;
  90802. }
  90803. if(obj.massPos){
  90804. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  90805. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  90806. }
  90807. if(obj.massRot){
  90808. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  90809. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  90810. }
  90811. // My rigidbody
  90812. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  90813. // My shapes
  90814. var shapes = [];
  90815. var type = obj.type || "box";
  90816. if( typeof type === 'string' ) type = [type];// single shape
  90817. var n, n2;
  90818. for(var i=0; i<type.length; i++){
  90819. n = i*3;
  90820. n2 = i*4;
  90821. switch(type[i]){
  90822. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  90823. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  90824. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  90825. }
  90826. this.body.addShape(shapes[i]);
  90827. if(i>0){
  90828. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  90829. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  90830. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  90831. }
  90832. }
  90833. // I'm static or i move
  90834. if(move){
  90835. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  90836. else this.body.setupMass(0x1, true);
  90837. if(noSleep) this.body.allowSleep = false;
  90838. else this.body.allowSleep = true;
  90839. } else {
  90840. this.body.setupMass(0x2);
  90841. }
  90842. this.body.name = this.name;
  90843. this.sleeping = this.body.sleeping;
  90844. // finaly add to physics world
  90845. this.parent.addRigidBody(this.body);*/
  90846. }
  90847. OIMO.Body.prototype = {
  90848. constructor: OIMO.Body,
  90849. // SET
  90850. setPosition: function (pos) {
  90851. this.body.setPosition(pos);
  90852. },
  90853. setQuaternion: function (q) {
  90854. this.body.setQuaternion(q);
  90855. },
  90856. setRotation: function (rot) {
  90857. this.body.setRotation(rot);
  90858. },
  90859. // GET
  90860. getPosition: function () {
  90861. return this.body.getPosition();
  90862. },
  90863. getRotation: function () {
  90864. return this.body.getRotation();
  90865. },
  90866. getQuaternion: function () {
  90867. return this.body.getQuaternion();
  90868. },
  90869. getMatrix: function () {
  90870. return this.body.getMatrix();
  90871. },
  90872. getSleep: function () {
  90873. return this.body.sleeping;
  90874. },
  90875. // RESET
  90876. resetPosition: function (x, y, z) {
  90877. this.body.resetPosition(x, y, z);
  90878. },
  90879. resetRotation: function (x, y, z) {
  90880. this.body.resetRotation(x, y, z);
  90881. },
  90882. // force wakeup
  90883. awake: function () {
  90884. this.body.awake();
  90885. },
  90886. // remove rigidbody
  90887. remove: function () {
  90888. this.body.dispose();
  90889. //this.parent.removeRigidBody(this.body);
  90890. },
  90891. // test if this object hit another
  90892. checkContact: function (name) {
  90893. this.body.checkContact(name);
  90894. //this.parent.checkContact(this.name, name);
  90895. }
  90896. }
  90897. /**
  90898. * The main class of link.
  90899. * is for simplify creation process and data access of Joint
  90900. * all setting in object
  90901. *
  90902. * @author loth
  90903. */
  90904. OIMO.Link = function (Obj) {
  90905. var obj = Obj || {};
  90906. if (!obj.world) return;
  90907. if (obj.type === undefined) obj.type = "jointHinge";
  90908. this.name = obj.name || '';
  90909. // obsolete use world.add(obj)
  90910. this.joint = obj.world.add(obj);
  90911. // the world where i am
  90912. /*this.parent = obj.world;
  90913. this.name = obj.name || '';
  90914. var type = obj.type || "jointHinge";
  90915. var axe1 = obj.axe1 || [1,0,0];
  90916. var axe2 = obj.axe2 || [1,0,0];
  90917. var pos1 = obj.pos1 || [0,0,0];
  90918. var pos2 = obj.pos2 || [0,0,0];
  90919. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  90920. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  90921. var min, max;
  90922. if(type==="jointDistance"){
  90923. min = obj.min || 0;
  90924. max = obj.max || 10;
  90925. min = min*OIMO.INV_SCALE;
  90926. max = max*OIMO.INV_SCALE;
  90927. }else{
  90928. min = obj.min || 57.29578;
  90929. max = obj.max || 0;
  90930. min = min*OIMO.TO_RAD;
  90931. max = max*OIMO.TO_RAD;
  90932. }
  90933. var limit = obj.limit || null;
  90934. var spring = obj.spring || null;
  90935. var motor = obj.motor || null;
  90936. // joint setting
  90937. var jc = new OIMO.JointConfig();
  90938. jc.allowCollision = obj.collision || false;;
  90939. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  90940. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  90941. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  90942. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  90943. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  90944. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  90945. jc.body1 = obj.body1;
  90946. jc.body2 = obj.body2;
  90947. switch(type){
  90948. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  90949. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  90950. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  90951. break;
  90952. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  90953. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  90954. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  90955. break;
  90956. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  90957. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  90958. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  90959. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  90960. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  90961. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  90962. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  90963. break;
  90964. }
  90965. this.joint.name = this.name;
  90966. // finaly add to physics world
  90967. this.parent.addJoint(this.joint);*/
  90968. }
  90969. OIMO.Link.prototype = {
  90970. constructor: OIMO.Link,
  90971. getPosition: function () {
  90972. // array of two vect3 [point1, point2]
  90973. return this.joint.getPosition();
  90974. },
  90975. getMatrix: function () {
  90976. return this.joint.getMatrix();
  90977. },
  90978. // remove joint
  90979. remove: function () {
  90980. this.joint.dispose();
  90981. //this.parent.removeJoint(this.joint);
  90982. },
  90983. // force wakeup linked body
  90984. awake: function () {
  90985. this.joint.awake();
  90986. }
  90987. }
  90988. /**
  90989. * The Dictionary class for testing
  90990. * @author lo-th
  90991. */
  90992. OIMO.Dictionary = function () {
  90993. this.data = {};
  90994. this.keys = [];
  90995. };
  90996. OIMO.Dictionary.prototype = {
  90997. constructor: OIMO.Dictionary,
  90998. set: function (value) {
  90999. var key = value.id;
  91000. if (!this.get[key]) this.keys.push(key);
  91001. this.data[key] = value;
  91002. },
  91003. get: function (id) {
  91004. return this.data[id];
  91005. },
  91006. del: function (value) {
  91007. var k = this.keys;
  91008. var n = k.indexOf(value.id);
  91009. if (n > -1) {
  91010. delete this.data[k[n]];
  91011. k.splice(n, 1);
  91012. }
  91013. },
  91014. reset: function () {
  91015. var data = this.data, keys = this.keys, key;
  91016. while (keys.length > 0) {
  91017. key = keys.pop();
  91018. delete data[key];
  91019. }
  91020. }
  91021. };
  91022. OIMO.Performance = function (world) {
  91023. this.parent = world;
  91024. this.infos = new OIMO_ARRAY_TYPE(13);
  91025. this.f = [0, 0, 0];
  91026. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  91027. this.broadPhase = this.types[this.parent.broadPhase.types];
  91028. this.version = OIMO.REVISION;
  91029. this.fps = 0;
  91030. this.broadPhaseTime = 0;
  91031. this.narrowPhaseTime = 0;
  91032. this.solvingTime = 0;
  91033. //this.updatingTime = 0;
  91034. this.totalTime = 0;
  91035. };
  91036. OIMO.Performance.prototype = {
  91037. upfps: function () {
  91038. this.f[1] = Date.now();
  91039. 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]++;
  91040. },
  91041. updatingTime: function () {
  91042. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  91043. },
  91044. show: function () {
  91045. var info = [
  91046. "Oimo.js " + this.version + "<br>",
  91047. this.broadPhase + "<br><br>",
  91048. "FPS: " + this.fps + " fps<br><br>",
  91049. "rigidbody " + this.parent.numRigidBodies + "<br>",
  91050. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  91051. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  91052. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  91053. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  91054. "Time in milliseconde<br><br>",
  91055. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  91056. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  91057. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  91058. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  91059. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  91060. ].join("\n");
  91061. return info;
  91062. },
  91063. toArray: function () {
  91064. this.infos[0] = this.parent.broadPhase.types;
  91065. this.infos[1] = this.parent.numRigidBodies;
  91066. this.infos[2] = this.parent.numContacts;
  91067. this.infos[3] = this.parent.broadPhase.numPairChecks;
  91068. this.infos[4] = this.parent.numContactPoints;
  91069. this.infos[5] = this.parent.numIslands;
  91070. this.infos[6] = this.broadPhaseTime;
  91071. this.infos[7] = this.narrowPhaseTime;
  91072. this.infos[8] = this.solvingTime;
  91073. this.infos[9] = this.updatingTime();
  91074. this.infos[10] = this.totalTime;
  91075. this.infos[11] = this.fps;
  91076. return this.infos;
  91077. }
  91078. };
  91079. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  91080. this.elements = new OIMO_ARRAY_TYPE(16);
  91081. var te = this.elements;
  91082. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  91083. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  91084. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  91085. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  91086. };
  91087. OIMO.Mat44.prototype = {
  91088. constructor: OIMO.Mat44,
  91089. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  91090. var te = this.elements;
  91091. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  91092. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  91093. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  91094. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  91095. return this;
  91096. }/*,
  91097. extractRotation: function () {
  91098. var v1 = new THREE.Vector3();
  91099. return function ( m ) {
  91100. var te = this.elements;
  91101. var me = m.elements;
  91102. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  91103. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  91104. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  91105. te[ 0 ] = me[ 0 ] * scaleX;
  91106. te[ 1 ] = me[ 1 ] * scaleX;
  91107. te[ 2 ] = me[ 2 ] * scaleX;
  91108. te[ 4 ] = me[ 4 ] * scaleY;
  91109. te[ 5 ] = me[ 5 ] * scaleY;
  91110. te[ 6 ] = me[ 6 ] * scaleY;
  91111. te[ 8 ] = me[ 8 ] * scaleZ;
  91112. te[ 9 ] = me[ 9 ] * scaleZ;
  91113. te[ 10 ] = me[ 10 ] * scaleZ;
  91114. return this;
  91115. };
  91116. }() */
  91117. }
  91118. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  91119. this.elements = new OIMO_ARRAY_TYPE(9);
  91120. var te = this.elements;
  91121. this.init(
  91122. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  91123. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  91124. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  91125. );
  91126. };
  91127. OIMO.Mat33.prototype = {
  91128. constructor: OIMO.Mat33,
  91129. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  91130. var te = this.elements;
  91131. te[0] = e00; te[1] = e01; te[2] = e02;
  91132. te[3] = e10; te[4] = e11; te[5] = e12;
  91133. te[6] = e20; te[7] = e21; te[8] = e22;
  91134. return this;
  91135. },
  91136. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  91137. var te = this.elements;
  91138. te[0] = e00; te[1] = e01; te[2] = e02;
  91139. te[3] = e10; te[4] = e11; te[5] = e12;
  91140. te[6] = e20; te[7] = e21; te[8] = e22;
  91141. return this;
  91142. },
  91143. multiply: function (s) {
  91144. var te = this.elements;
  91145. te[0] *= s; te[1] *= s; te[2] *= s;
  91146. te[3] *= s; te[4] *= s; te[5] *= s;
  91147. te[6] *= s; te[7] *= s; te[8] *= s;
  91148. return this;
  91149. },
  91150. add: function (m1, m2) {
  91151. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  91152. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  91153. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  91154. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  91155. return this;
  91156. },
  91157. addEqual: function (m) {
  91158. var te = this.elements, tem = m.elements;
  91159. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  91160. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  91161. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  91162. return this;
  91163. },
  91164. sub: function (m1, m2) {
  91165. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  91166. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  91167. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  91168. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  91169. return this;
  91170. },
  91171. subEqual: function (m) {
  91172. var te = this.elements, tem = m.elements;
  91173. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  91174. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  91175. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  91176. return this;
  91177. },
  91178. scale: function (m, s) {
  91179. var te = this.elements, tm = m.elements;
  91180. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  91181. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  91182. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  91183. return this;
  91184. },
  91185. scaleEqual: function (s) {
  91186. var te = this.elements;
  91187. te[0] *= s; te[1] *= s; te[2] *= s;
  91188. te[3] *= s; te[4] *= s; te[5] *= s;
  91189. te[6] *= s; te[7] *= s; te[8] *= s;
  91190. return this;
  91191. },
  91192. mul: function (m1, m2) {
  91193. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  91194. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  91195. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  91196. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  91197. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  91198. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  91199. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  91200. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  91201. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  91202. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  91203. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  91204. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  91205. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  91206. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  91207. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  91208. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  91209. return this;
  91210. },
  91211. mulScale: function (m, sx, sy, sz, Prepend) {
  91212. var prepend = Prepend || false;
  91213. var te = this.elements, tm = m.elements;
  91214. if (prepend) {
  91215. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  91216. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  91217. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  91218. } else {
  91219. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  91220. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  91221. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  91222. }
  91223. return this;
  91224. },
  91225. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  91226. var prepend = Prepend || false;
  91227. var s = OIMO.sin(rad);
  91228. var c = OIMO.cos(rad);
  91229. var c1 = 1 - c;
  91230. var r00 = ax * ax * c1 + c;
  91231. var r01 = ax * ay * c1 - az * s;
  91232. var r02 = ax * az * c1 + ay * s;
  91233. var r10 = ay * ax * c1 + az * s;
  91234. var r11 = ay * ay * c1 + c;
  91235. var r12 = ay * az * c1 - ax * s;
  91236. var r20 = az * ax * c1 - ay * s;
  91237. var r21 = az * ay * c1 + ax * s;
  91238. var r22 = az * az * c1 + c;
  91239. var tm = m.elements;
  91240. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  91241. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  91242. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  91243. var te = this.elements;
  91244. if (prepend) {
  91245. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  91246. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  91247. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  91248. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  91249. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  91250. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  91251. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  91252. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  91253. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  91254. } else {
  91255. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  91256. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  91257. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  91258. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  91259. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  91260. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  91261. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  91262. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  91263. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  91264. }
  91265. return this;
  91266. },
  91267. transpose: function (m) {
  91268. var te = this.elements, tm = m.elements;
  91269. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  91270. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  91271. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  91272. return this;
  91273. },
  91274. setQuat: function (q) {
  91275. var te = this.elements,
  91276. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  91277. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  91278. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  91279. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  91280. te[0] = 1 - yy - zz;
  91281. te[1] = xy - sz;
  91282. te[2] = xz + sy;
  91283. te[3] = xy + sz;
  91284. te[4] = 1 - xx - zz;
  91285. te[5] = yz - sx;
  91286. te[6] = xz - sy;
  91287. te[7] = yz + sx;
  91288. te[8] = 1 - xx - yy;
  91289. return this;
  91290. },
  91291. invert: function (m) {
  91292. var te = this.elements, tm = m.elements,
  91293. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  91294. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  91295. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  91296. b01 = a4 * a8 - a7 * a5,
  91297. b11 = a7 * a2 - a1 * a8,
  91298. b21 = a1 * a5 - a4 * a2,
  91299. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  91300. if (dt != 0) { dt = 1.0 / dt; }
  91301. te[0] = dt * b01;//(a4*a8 - a5*a7);
  91302. te[1] = dt * b11;//(a2*a7 - a1*a8);
  91303. te[2] = dt * b21;//(a1*a5 - a2*a4);
  91304. te[3] = dt * (a5 * a6 - a3 * a8);
  91305. te[4] = dt * (a0 * a8 - a2 * a6);
  91306. te[5] = dt * (a2 * a3 - a0 * a5);
  91307. te[6] = dt * (a3 * a7 - a4 * a6);
  91308. te[7] = dt * (a1 * a6 - a0 * a7);
  91309. te[8] = dt * (a0 * a4 - a1 * a3);
  91310. return this;
  91311. },
  91312. /*copy: function(m){
  91313. var te = this.elements, tem = m.elements;
  91314. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  91315. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  91316. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  91317. return this;
  91318. },*/
  91319. toEuler: function () { // not work !!
  91320. function clamp(x) {
  91321. return OIMO.min(OIMO.max(x, -1), 1);
  91322. }
  91323. var te = this.elements;
  91324. var m11 = te[0], m12 = te[3], m13 = te[6];
  91325. var m21 = te[1], m22 = te[4], m23 = te[7];
  91326. var m31 = te[2], m32 = te[5], m33 = te[8];
  91327. var p = new OIMO.Vec3();
  91328. var d = new OIMO.Quat();
  91329. var s;
  91330. p.y = OIMO.asin(clamp(m13));
  91331. if (OIMO.abs(m13) < 0.99999) {
  91332. p.x = OIMO.atan2(-m23, m33);
  91333. p.z = OIMO.atan2(-m12, m11);
  91334. } else {
  91335. p.x = OIMO.atan2(m32, m22);
  91336. p.z = 0;
  91337. }
  91338. return p;
  91339. },
  91340. /*clone: function(){
  91341. var te = this.elements;
  91342. return new OIMO.Mat33(
  91343. te[0], te[1], te[2],
  91344. te[3], te[4], te[5],
  91345. te[6], te[7], te[8]
  91346. );
  91347. },*/
  91348. toString: function () {
  91349. var te = this.elements;
  91350. var text =
  91351. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  91352. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  91353. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  91354. return text;
  91355. },
  91356. // OK
  91357. multiplyScalar: function (s) {
  91358. var te = this.elements;
  91359. te[0] *= s; te[3] *= s; te[6] *= s;
  91360. te[1] *= s; te[4] *= s; te[7] *= s;
  91361. te[2] *= s; te[5] *= s; te[8] *= s;
  91362. return this;
  91363. },
  91364. identity: function () {
  91365. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  91366. return this;
  91367. },
  91368. clone: function () {
  91369. return new this.constructor().fromArray(this.elements);
  91370. },
  91371. copy: function (m) {
  91372. var me = m.elements;
  91373. this.set(
  91374. me[0], me[3], me[6],
  91375. me[1], me[4], me[7],
  91376. me[2], me[5], me[8]
  91377. );
  91378. return this;
  91379. },
  91380. fromArray: function (array) {
  91381. this.elements.set(array);
  91382. return this;
  91383. },
  91384. toArray: function () {
  91385. var te = this.elements;
  91386. return [
  91387. te[0], te[1], te[2],
  91388. te[3], te[4], te[5],
  91389. te[6], te[7], te[8]
  91390. ];
  91391. }
  91392. };
  91393. OIMO.Quat = function (s, x, y, z) {
  91394. this.s = (s !== undefined) ? s : 1;
  91395. this.x = x || 0;
  91396. this.y = y || 0;
  91397. this.z = z || 0;
  91398. };
  91399. OIMO.Quat.prototype = {
  91400. constructor: OIMO.Quat,
  91401. set: function (x, y, z, w) {
  91402. this.x = x;
  91403. this.y = y;
  91404. this.z = z;
  91405. this.s = w;
  91406. return this;
  91407. },
  91408. init: function (s, x, y, z) {
  91409. this.s = (s !== undefined) ? s : 1;
  91410. this.x = x || 0;
  91411. this.y = y || 0;
  91412. this.z = z || 0;
  91413. return this;
  91414. },
  91415. add: function (q1, q2) {
  91416. this.s = q1.s + q2.s;
  91417. this.x = q1.x + q2.x;
  91418. this.y = q1.y + q2.y;
  91419. this.z = q1.z + q2.z;
  91420. return this;
  91421. },
  91422. addTime: function (v, t) {
  91423. var x = v.x;
  91424. var y = v.y;
  91425. var z = v.z;
  91426. var qs = this.s;
  91427. var qx = this.x;
  91428. var qy = this.y;
  91429. var qz = this.z;
  91430. t *= 0.5;
  91431. var ns = (-x * qx - y * qy - z * qz) * t;
  91432. var nx = (x * qs + y * qz - z * qy) * t;
  91433. var ny = (-x * qz + y * qs + z * qx) * t;
  91434. var nz = (x * qy - y * qx + z * qs) * t;
  91435. qs += ns;
  91436. qx += nx;
  91437. qy += ny;
  91438. qz += nz;
  91439. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  91440. this.s = qs * s;
  91441. this.x = qx * s;
  91442. this.y = qy * s;
  91443. this.z = qz * s;
  91444. return this;
  91445. },
  91446. sub: function (q1, q2) {
  91447. this.s = q1.s - q2.s;
  91448. this.x = q1.x - q2.x;
  91449. this.y = q1.y - q2.y;
  91450. this.z = q1.z - q2.z;
  91451. return this;
  91452. },
  91453. scale: function (q, s) {
  91454. this.s = q.s * s;
  91455. this.x = q.x * s;
  91456. this.y = q.y * s;
  91457. this.z = q.z * s;
  91458. return this;
  91459. },
  91460. mul: function (q1, q2) {
  91461. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  91462. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  91463. this.x = ax * bs + as * bx + ay * bz - az * by;
  91464. this.y = ay * bs + as * by + az * bx - ax * bz;
  91465. this.z = az * bs + as * bz + ax * by - ay * bx;
  91466. this.s = as * bs - ax * bx - ay * by - az * bz;
  91467. return this;
  91468. },
  91469. arc: function (v1, v2) {
  91470. var x1 = v1.x;
  91471. var y1 = v1.y;
  91472. var z1 = v1.z;
  91473. var x2 = v2.x;
  91474. var y2 = v2.y;
  91475. var z2 = v2.z;
  91476. var d = x1 * x2 + y1 * y2 + z1 * z2;
  91477. if (d == -1) {
  91478. x2 = y1 * x1 - z1 * z1;
  91479. y2 = -z1 * y1 - x1 * x1;
  91480. z2 = x1 * z1 + y1 * y1;
  91481. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  91482. this.s = 0;
  91483. this.x = x2 * d;
  91484. this.y = y2 * d;
  91485. this.z = z2 * d;
  91486. return this;
  91487. }
  91488. var cx = y1 * z2 - z1 * y2;
  91489. var cy = z1 * x2 - x1 * z2;
  91490. var cz = x1 * y2 - y1 * x2;
  91491. this.s = OIMO.sqrt((1 + d) * 0.5);
  91492. d = 0.5 / this.s;
  91493. this.x = cx * d;
  91494. this.y = cy * d;
  91495. this.z = cz * d;
  91496. return this;
  91497. },
  91498. normalize: function (q) {
  91499. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  91500. if (len > 0) { len = 1 / len; }
  91501. this.s = q.s * len;
  91502. this.x = q.x * len;
  91503. this.y = q.y * len;
  91504. this.z = q.z * len;
  91505. return this;
  91506. },
  91507. invert: function (q) {
  91508. this.s = q.s;
  91509. this.x = -q.x;
  91510. this.y = -q.y;
  91511. this.z = -q.z;
  91512. return this;
  91513. },
  91514. length: function () {
  91515. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  91516. },
  91517. copy: function (q) {
  91518. this.s = q.s;
  91519. this.x = q.x;
  91520. this.y = q.y;
  91521. this.z = q.z;
  91522. return this;
  91523. },
  91524. testDiff: function (q) {
  91525. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  91526. else return false;
  91527. },
  91528. clone: function (q) {
  91529. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  91530. },
  91531. toString: function () {
  91532. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  91533. }
  91534. }
  91535. // for three easy export
  91536. OIMO.Quaternion = function (x, y, z, w) {
  91537. this.x = x || 0;
  91538. this.y = y || 0;
  91539. this.z = z || 0;
  91540. this.w = (w !== undefined) ? w : 1;
  91541. };
  91542. OIMO.Quaternion.prototype = {
  91543. constructor: OIMO.Quaternion,
  91544. setFromRotationMatrix: function (m) {
  91545. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  91546. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  91547. var te = m.elements,
  91548. m11 = te[0], m12 = te[1], m13 = te[2],
  91549. m21 = te[3], m22 = te[4], m23 = te[5],
  91550. m31 = te[6], m32 = te[7], m33 = te[8],
  91551. trace = m11 + m22 + m33,
  91552. s;
  91553. if (trace > 0) {
  91554. s = 0.5 / OIMO.sqrt(trace + 1.0);
  91555. this.w = 0.25 / s;
  91556. this.x = (m32 - m23) * s;
  91557. this.y = (m13 - m31) * s;
  91558. this.z = (m21 - m12) * s;
  91559. } else if (m11 > m22 && m11 > m33) {
  91560. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  91561. this.w = (m32 - m23) / s;
  91562. this.x = 0.25 * s;
  91563. this.y = (m12 + m21) / s;
  91564. this.z = (m13 + m31) / s;
  91565. } else if (m22 > m33) {
  91566. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  91567. this.w = (m13 - m31) / s;
  91568. this.x = (m12 + m21) / s;
  91569. this.y = 0.25 * s;
  91570. this.z = (m23 + m32) / s;
  91571. } else {
  91572. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  91573. this.w = (m21 - m12) / s;
  91574. this.x = (m13 + m31) / s;
  91575. this.y = (m23 + m32) / s;
  91576. this.z = 0.25 * s;
  91577. }
  91578. //this.onChangeCallback();
  91579. return this;
  91580. }
  91581. }
  91582. OIMO.Vec3 = function (x, y, z) {
  91583. this.x = x || 0;
  91584. this.y = y || 0;
  91585. this.z = z || 0;
  91586. };
  91587. OIMO.Vec3.prototype = {
  91588. constructor: OIMO.Vec3,
  91589. init: function (x, y, z) {
  91590. this.x = x || 0;
  91591. this.y = y || 0;
  91592. this.z = z || 0;
  91593. return this;
  91594. },
  91595. set: function (x, y, z) {
  91596. this.x = x;
  91597. this.y = y;
  91598. this.z = z;
  91599. return this;
  91600. },
  91601. add: function (v1, v2) {
  91602. this.x = v1.x + v2.x;
  91603. this.y = v1.y + v2.y;
  91604. this.z = v1.z + v2.z;
  91605. return this;
  91606. },
  91607. addEqual: function (v) {
  91608. this.x += v.x;
  91609. this.y += v.y;
  91610. this.z += v.z;
  91611. return this;
  91612. },
  91613. addTime: function (v, t) {
  91614. this.x += v.x * t;
  91615. this.y += v.y * t;
  91616. this.z += v.z * t;
  91617. return this;
  91618. },
  91619. sub: function (v1, v2) {
  91620. this.x = v1.x - v2.x;
  91621. this.y = v1.y - v2.y;
  91622. this.z = v1.z - v2.z;
  91623. return this;
  91624. },
  91625. subEqual: function (v) {
  91626. this.x -= v.x;
  91627. this.y -= v.y;
  91628. this.z -= v.z;
  91629. return this;
  91630. },
  91631. addScale: function (v, s) {
  91632. this.x += v.x * s;
  91633. this.y += v.y * s;
  91634. this.z += v.z * s;
  91635. return this;
  91636. },
  91637. scale: function (v, s) {
  91638. this.x = v.x * s;
  91639. this.y = v.y * s;
  91640. this.z = v.z * s;
  91641. return this;
  91642. },
  91643. scaleEqual: function (s) {
  91644. this.x *= s;
  91645. this.y *= s;
  91646. this.z *= s;
  91647. return this;
  91648. },
  91649. /*dot: function(v){
  91650. return this.x*v.x+this.y*v.y+this.z*v.z;
  91651. },*/
  91652. cross: function (v1, v2) {
  91653. var ax = v1.x, ay = v1.y, az = v1.z,
  91654. bx = v2.x, by = v2.y, bz = v2.z;
  91655. this.x = ay * bz - az * by;
  91656. this.y = az * bx - ax * bz;
  91657. this.z = ax * by - ay * bx;
  91658. return this;
  91659. },
  91660. mul: function (o, v, m) {
  91661. var te = m.elements;
  91662. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  91663. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  91664. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  91665. return this;
  91666. },
  91667. mulMat: function (m, v) {
  91668. var te = m.elements;
  91669. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  91670. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  91671. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  91672. return this;
  91673. },
  91674. normalize: function (v) {
  91675. var x = v.x, y = v.y, z = v.z;
  91676. var l = x * x + y * y + z * z;
  91677. if (l > 0) {
  91678. l = 1 / OIMO.sqrt(l);
  91679. this.x = x * l;
  91680. this.y = y * l;
  91681. this.z = z * l;
  91682. }
  91683. return this;
  91684. },
  91685. /*norm: function(){
  91686. var x = this.x, y = this.y, z = this.z;
  91687. var l = x*x + y*y + z*z;
  91688. if (l > 0) {
  91689. l = 1 / OIMO.sqrt(l);
  91690. this.x = x*l;
  91691. this.y = y*l;
  91692. this.z = z*l;
  91693. }
  91694. return this;
  91695. },*/
  91696. invert: function (v) {
  91697. this.x = -v.x;
  91698. this.y = -v.y;
  91699. this.z = -v.z;
  91700. return this;
  91701. },
  91702. /*length: function(){
  91703. var x = this.x, y = this.y, z = this.z;
  91704. return OIMO.sqrt(x*x + y*y + z*z);
  91705. },*/
  91706. negate: function () {
  91707. this.x = -this.x;
  91708. this.y = -this.y;
  91709. this.z = -this.z;
  91710. return this;
  91711. },
  91712. dot: function (v) {
  91713. return this.x * v.x + this.y * v.y + this.z * v.z;
  91714. },
  91715. lengthSq: function () {
  91716. return this.x * this.x + this.y * this.y + this.z * this.z;
  91717. },
  91718. length: function () {
  91719. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  91720. },
  91721. /*len: function(){
  91722. var x = this.x, y = this.y, z = this.z;
  91723. return x*x + y*y + z*z;
  91724. },*/
  91725. copy: function (v) {
  91726. this.x = v.x;
  91727. this.y = v.y;
  91728. this.z = v.z;
  91729. return this;
  91730. },
  91731. applyQuaternion: function (q) {
  91732. var x = this.x;
  91733. var y = this.y;
  91734. var z = this.z;
  91735. var qx = q.x;
  91736. var qy = q.y;
  91737. var qz = q.z;
  91738. var qs = q.s;
  91739. // calculate quat * vector
  91740. var ix = qs * x + qy * z - qz * y;
  91741. var iy = qs * y + qz * x - qx * z;
  91742. var iz = qs * z + qx * y - qy * x;
  91743. var iw = -qx * x - qy * y - qz * z;
  91744. // calculate result * inverse quat
  91745. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  91746. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  91747. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  91748. return this;
  91749. },
  91750. testZero: function () {
  91751. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  91752. else return false;
  91753. },
  91754. testDiff: function (v) {
  91755. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  91756. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  91757. //else return false;
  91758. },
  91759. equals: function (v) {
  91760. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  91761. },
  91762. clone: function () {
  91763. return new this.constructor(this.x, this.y, this.z);
  91764. },
  91765. toString: function () {
  91766. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  91767. },
  91768. multiplyScalar: function (scalar) {
  91769. if (isFinite(scalar)) {
  91770. this.x *= scalar;
  91771. this.y *= scalar;
  91772. this.z *= scalar;
  91773. } else {
  91774. this.x = 0;
  91775. this.y = 0;
  91776. this.z = 0;
  91777. }
  91778. return this;
  91779. },
  91780. divideScalar: function (scalar) {
  91781. return this.multiplyScalar(1 / scalar);
  91782. },
  91783. // TODO rename to normalize
  91784. norm: function () {
  91785. return this.divideScalar(this.length());
  91786. },
  91787. }
  91788. OIMO.Euler = function (x, y, z, order) {
  91789. this._x = x || 0;
  91790. this._y = y || 0;
  91791. this._z = z || 0;
  91792. this._order = order || OIMO.Euler.DefaultOrder;
  91793. };
  91794. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  91795. OIMO.Euler.DefaultOrder = 'XYZ';
  91796. OIMO.clamp = function (x, a, b) {
  91797. return (x < a) ? a : ((x > b) ? b : x);
  91798. }
  91799. OIMO.Euler.prototype = {
  91800. constructor: OIMO.Euler,
  91801. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  91802. get x() {
  91803. return this._x;
  91804. },
  91805. set x(value) {
  91806. this._x = value;
  91807. this.onChangeCallback();
  91808. },
  91809. get y() {
  91810. return this._y;
  91811. },
  91812. set y(value) {
  91813. this._y = value;
  91814. this.onChangeCallback();
  91815. },
  91816. get z() {
  91817. return this._z;
  91818. },
  91819. set z(value) {
  91820. this._z = value;
  91821. this.onChangeCallback();
  91822. },
  91823. get order() {
  91824. return this._order;
  91825. },
  91826. set order(value) {
  91827. this._order = value;
  91828. this.onChangeCallback();
  91829. },
  91830. set: function (x, y, z, order) {
  91831. this._x = x;
  91832. this._y = y;
  91833. this._z = z;
  91834. this._order = order || this._order;
  91835. this.onChangeCallback();
  91836. return this;
  91837. },
  91838. copy: function (euler) {
  91839. this._x = euler._x;
  91840. this._y = euler._y;
  91841. this._z = euler._z;
  91842. this._order = euler._order;
  91843. this.onChangeCallback();
  91844. return this;
  91845. },
  91846. setFromRotationMatrix: function (m, order) {
  91847. var clamp = OIMO.clamp;
  91848. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  91849. var te = m.elements;
  91850. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  91851. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  91852. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  91853. var m11 = te[0], m12 = te[1], m13 = te[2],
  91854. m21 = te[3], m22 = te[4], m23 = te[5],
  91855. m31 = te[6], m32 = te[7], m33 = te[8];
  91856. order = order || this._order;
  91857. if (order === 'XYZ') {
  91858. this._y = OIMO.asin(clamp(m13, -1, 1));
  91859. if (OIMO.abs(m13) < 0.99999) {
  91860. this._x = OIMO.atan2(-m23, m33);
  91861. this._z = OIMO.atan2(-m12, m11);
  91862. } else {
  91863. this._x = OIMO.atan2(m32, m22);
  91864. this._z = 0;
  91865. }
  91866. } else if (order === 'YXZ') {
  91867. this._x = OIMO.asin(-clamp(m23, -1, 1));
  91868. if (OIMO.abs(m23) < 0.99999) {
  91869. this._y = OIMO.atan2(m13, m33);
  91870. this._z = OIMO.atan2(m21, m22);
  91871. } else {
  91872. this._y = OIMO.atan2(-m31, m11);
  91873. this._z = 0;
  91874. }
  91875. } else if (order === 'ZXY') {
  91876. this._x = OIMO.asin(clamp(m32, -1, 1));
  91877. if (OIMO.abs(m32) < 0.99999) {
  91878. this._y = OIMO.atan2(-m31, m33);
  91879. this._z = OIMO.atan2(-m12, m22);
  91880. } else {
  91881. this._y = 0;
  91882. this._z = OIMO.atan2(m21, m11);
  91883. }
  91884. } else if (order === 'ZYX') {
  91885. this._y = OIMO.asin(-clamp(m31, -1, 1));
  91886. if (OIMO.abs(m31) < 0.99999) {
  91887. this._x = OIMO.atan2(m32, m33);
  91888. this._z = OIMO.atan2(m21, m11);
  91889. } else {
  91890. this._x = 0;
  91891. this._z = OIMO.atan2(-m12, m22);
  91892. }
  91893. } else if (order === 'YZX') {
  91894. this._z = OIMO.asin(clamp(m21, -1, 1));
  91895. if (OIMO.abs(m21) < 0.99999) {
  91896. this._x = OIMO.atan2(-m23, m22);
  91897. this._y = OIMO.atan2(-m31, m11);
  91898. } else {
  91899. this._x = 0;
  91900. this._y = OIMO.atan2(m13, m33);
  91901. }
  91902. } else if (order === 'XZY') {
  91903. this._z = OIMO.asin(-clamp(m12, -1, 1));
  91904. if (OIMO.abs(m12) < 0.99999) {
  91905. this._x = OIMO.atan2(m32, m22);
  91906. this._y = OIMO.atan2(m13, m11);
  91907. } else {
  91908. this._x = OIMO.atan2(-m23, m33);
  91909. this._y = 0;
  91910. }
  91911. } else {
  91912. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  91913. }
  91914. this._order = order;
  91915. this.onChangeCallback();
  91916. return this;
  91917. },
  91918. setFromQuaternion: function (q, order, update) {
  91919. var clamp = OIMO.clamp;
  91920. // q is assumed to be normalized
  91921. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  91922. var sqx = q.x * q.x;
  91923. var sqy = q.y * q.y;
  91924. var sqz = q.z * q.z;
  91925. var sqw = q.s * q.s;
  91926. order = order || this._order;
  91927. if (order === 'XYZ') {
  91928. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  91929. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  91930. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  91931. } else if (order === 'YXZ') {
  91932. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  91933. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  91934. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  91935. } else if (order === 'ZXY') {
  91936. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  91937. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  91938. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  91939. } else if (order === 'ZYX') {
  91940. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  91941. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  91942. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  91943. } else if (order === 'YZX') {
  91944. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  91945. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  91946. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  91947. } else if (order === 'XZY') {
  91948. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  91949. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  91950. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  91951. } else {
  91952. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  91953. }
  91954. this._order = order;
  91955. if (update !== false) this.onChangeCallback();
  91956. return this;
  91957. },
  91958. reorder: function () {
  91959. // WARNING: this discards revolution information -bhouston
  91960. var q = new OIMO.Quat();
  91961. return function (newOrder) {
  91962. q.setFromEuler(this);
  91963. this.setFromQuaternion(q, newOrder);
  91964. };
  91965. }(),
  91966. equals: function (euler) {
  91967. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  91968. },
  91969. fromArray: function (array) {
  91970. this._x = array[0];
  91971. this._y = array[1];
  91972. this._z = array[2];
  91973. if (array[3] !== undefined) this._order = array[3];
  91974. this.onChangeCallback();
  91975. return this;
  91976. },
  91977. toArray: function () {
  91978. return [this._x, this._y, this._z, this._order];
  91979. },
  91980. onChange: function (callback) {
  91981. this.onChangeCallback = callback;
  91982. return this;
  91983. },
  91984. onChangeCallback: function () { },
  91985. clone: function () {
  91986. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  91987. }
  91988. };
  91989. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  91990. var c1 = OIMO.cos(oy * 0.5);//heading
  91991. var s1 = OIMO.sin(oy * 0.5);
  91992. var c2 = OIMO.cos(oz * 0.5);//altitude
  91993. var s2 = OIMO.sin(oz * 0.5);
  91994. var c3 = OIMO.cos(ox * 0.5);//bank
  91995. var s3 = OIMO.sin(ox * 0.5);
  91996. var c1c2 = c1 * c2;
  91997. var s1s2 = s1 * s2;
  91998. var w = c1c2 * c3 - s1s2 * s3;
  91999. var x = c1c2 * s3 + s1s2 * c3;
  92000. var y = s1 * c2 * c3 + c1 * s2 * s3;
  92001. var z = c1 * s2 * c3 - s1 * c2 * s3;
  92002. var angle = 2 * OIMO.acos(w);
  92003. var norm = x * x + y * y + z * z;
  92004. if (norm < 0.001) {
  92005. x = 1;
  92006. y = z = 0;
  92007. } else {
  92008. norm = OIMO.sqrt(norm);
  92009. x /= norm;
  92010. y /= norm;
  92011. z /= norm;
  92012. }
  92013. return [angle, x, y, z];
  92014. }
  92015. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  92016. var ch = OIMO.cos(oy);//heading
  92017. var sh = OIMO.sin(oy);
  92018. var ca = OIMO.cos(oz);//altitude
  92019. var sa = OIMO.sin(oz);
  92020. var cb = OIMO.cos(ox);//bank
  92021. var sb = OIMO.sin(ox);
  92022. var mtx = new OIMO.Mat33();
  92023. var te = mtx.elements;
  92024. te[0] = ch * ca;
  92025. te[1] = sh * sb - ch * sa * cb;
  92026. te[2] = ch * sa * sb + sh * cb;
  92027. te[3] = sa;
  92028. te[4] = ca * cb;
  92029. te[5] = -ca * sb;
  92030. te[6] = -sh * ca;
  92031. te[7] = sh * sa * cb + ch * sb;
  92032. te[8] = -sh * sa * sb + ch * cb;
  92033. return mtx;
  92034. }
  92035. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  92036. var te = mtx.elements;
  92037. var x, y, z;
  92038. if (te[3] > 0.998) { // singularity at north pole
  92039. y = OIMO.atan2(te[2], te[8]);
  92040. z = OIMO.PI / 2;
  92041. x = 0;
  92042. } else if (te[3] < -0.998) { // singularity at south pole
  92043. y = OIMO.atan2(te[2], te[8]);
  92044. z = -OIMO.PI / 2;
  92045. x = 0;
  92046. } else {
  92047. y = OIMO.atan2(-te[6], te[0]);
  92048. x = OIMO.atan2(-te[5], te[4]);
  92049. z = OIMO.asin(te[3]);
  92050. }
  92051. return [x, y, z];
  92052. }
  92053. OIMO.unwrapDegrees = function (r) {
  92054. r = r % 360;
  92055. if (r > 180) r -= 360;
  92056. if (r < -180) r += 360;
  92057. return r;
  92058. }
  92059. OIMO.unwrapRadian = function (r) {
  92060. r = r % OIMO.TwoPI;
  92061. if (r > OIMO.PI) r -= OIMO.TwoPI;
  92062. if (r < -OIMO.PI) r += OIMO.TwoPI;
  92063. return r;
  92064. }
  92065. OIMO.Distance3d = function (p1, p2) {
  92066. var xd = p2[0] - p1[0];
  92067. var yd = p2[1] - p1[1];
  92068. var zd = p2[2] - p1[2];
  92069. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  92070. }
  92071. /**
  92072. * The base class of all type of the constraints.
  92073. * @author saharan
  92074. */
  92075. OIMO.Constraint = function () {
  92076. // The parent world of the constraint.
  92077. this.parent = null;
  92078. // The first body of the constraint.
  92079. this.body1 = null;
  92080. // The second body of the constraint.
  92081. this.body2 = null;
  92082. // Internal
  92083. this.addedToIsland = false;
  92084. }
  92085. OIMO.Constraint.prototype = {
  92086. constructor: OIMO.Constraint,
  92087. /**
  92088. * Prepare for solving the constraint.
  92089. * @param timeStep
  92090. * @param invTimeStep
  92091. */
  92092. preSolve: function (timeStep, invTimeStep) {
  92093. OIMO.Error("Constraint", "Inheritance error.");
  92094. },
  92095. /**
  92096. * Solve the constraint.
  92097. * This is usually called iteratively.
  92098. */
  92099. solve: function () {
  92100. OIMO.Error("Constraint", "Inheritance error.");
  92101. },
  92102. /**
  92103. * Do the post-processing.
  92104. */
  92105. postSolve: function () {
  92106. OIMO.Error("Constraint", "Inheritance error.");
  92107. }
  92108. }
  92109. /**
  92110. * Joints are used to constrain the motion between two rigid bodies.
  92111. * @author saharan
  92112. * @author lo-th
  92113. */
  92114. OIMO.Joint = function (config) {
  92115. OIMO.Constraint.call(this);
  92116. // joint name
  92117. this.name = "";
  92118. // The type of the joint.
  92119. this.type = OIMO.JOINT_NULL;
  92120. // The previous joint in the world.
  92121. this.prev = null;
  92122. // The next joint in the world.
  92123. this.next = null;
  92124. this.body1 = config.body1;
  92125. this.body2 = config.body2;
  92126. // The anchor point on the first rigid body in local coordinate system.
  92127. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  92128. // The anchor point on the second rigid body in local coordinate system.
  92129. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  92130. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  92131. this.relativeAnchorPoint1 = new OIMO.Vec3();
  92132. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  92133. this.relativeAnchorPoint2 = new OIMO.Vec3();
  92134. // The anchor point on the first rigid body in world coordinate system.
  92135. this.anchorPoint1 = new OIMO.Vec3();
  92136. // The anchor point on the second rigid body in world coordinate system.
  92137. this.anchorPoint2 = new OIMO.Vec3();
  92138. // Whether allow collision between connected rigid bodies or not.
  92139. this.allowCollision = config.allowCollision;
  92140. this.b1Link = new OIMO.JointLink(this);
  92141. this.b2Link = new OIMO.JointLink(this);
  92142. this.matrix = new OIMO.Mat44();
  92143. };
  92144. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  92145. OIMO.Joint.prototype.constructor = OIMO.Joint;
  92146. // Update all the anchor points.
  92147. OIMO.Joint.prototype.updateAnchorPoints = function () {
  92148. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  92149. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  92150. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  92151. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  92152. };
  92153. // Attach the joint from the bodies.
  92154. OIMO.Joint.prototype.attach = function () {
  92155. this.b1Link.body = this.body2;
  92156. this.b2Link.body = this.body1;
  92157. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  92158. else this.b1Link.next = null;
  92159. this.body1.jointLink = this.b1Link;
  92160. this.body1.numJoints++;
  92161. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  92162. else this.b2Link.next = null;
  92163. this.body2.jointLink = this.b2Link;
  92164. this.body2.numJoints++;
  92165. };
  92166. // Detach the joint from the bodies.
  92167. OIMO.Joint.prototype.detach = function () {
  92168. var prev = this.b1Link.prev;
  92169. var next = this.b1Link.next;
  92170. if (prev != null) prev.next = next;
  92171. if (next != null) next.prev = prev;
  92172. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  92173. this.b1Link.prev = null;
  92174. this.b1Link.next = null;
  92175. this.b1Link.body = null;
  92176. this.body1.numJoints--;
  92177. prev = this.b2Link.prev;
  92178. next = this.b2Link.next;
  92179. if (prev != null) prev.next = next;
  92180. if (next != null) next.prev = prev;
  92181. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  92182. this.b2Link.prev = null;
  92183. this.b2Link.next = null;
  92184. this.b2Link.body = null;
  92185. this.body2.numJoints--;
  92186. this.b1Link.body = null;
  92187. this.b2Link.body = null;
  92188. };
  92189. // Awake the bodies.
  92190. OIMO.Joint.prototype.awake = function () {
  92191. this.body1.awake();
  92192. this.body2.awake();
  92193. };
  92194. // calculation function
  92195. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  92196. };
  92197. OIMO.Joint.prototype.solve = function () {
  92198. };
  92199. OIMO.Joint.prototype.postSolve = function () {
  92200. };
  92201. // Delete process
  92202. OIMO.Joint.prototype.remove = function () {
  92203. this.dispose();
  92204. };
  92205. OIMO.Joint.prototype.dispose = function () {
  92206. this.parent.removeJoint(this);
  92207. };
  92208. // Three js add
  92209. OIMO.Joint.prototype.getPosition = function () {
  92210. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  92211. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  92212. return [p1, p2];
  92213. };
  92214. OIMO.Joint.prototype.getMatrix = function () {
  92215. var m = this.matrix.elements;
  92216. var p1 = this.anchorPoint1;
  92217. var p2 = this.anchorPoint2;
  92218. m[0] = p1.x * OIMO.WORLD_SCALE;
  92219. m[1] = p1.y * OIMO.WORLD_SCALE;
  92220. m[2] = p1.z * OIMO.WORLD_SCALE;
  92221. m[3] = 0;
  92222. m[4] = p2.x * OIMO.WORLD_SCALE;
  92223. m[5] = p2.y * OIMO.WORLD_SCALE;
  92224. m[6] = p2.z * OIMO.WORLD_SCALE;
  92225. m[7] = 0;
  92226. return m;
  92227. };
  92228. /**
  92229. * A joint configuration holds all configuration data for constructing a joint.
  92230. * Joint configurations can be reused safely.
  92231. * @author saharan
  92232. */
  92233. OIMO.JointConfig = function () {
  92234. // The first rigid body of the joint.
  92235. this.body1 = null;
  92236. // The second rigid body of the joint.
  92237. this.body2 = null;
  92238. // The anchor point on the first rigid body in local coordinate system.
  92239. this.localAnchorPoint1 = new OIMO.Vec3();
  92240. // The anchor point on the second rigid body in local coordinate system.
  92241. this.localAnchorPoint2 = new OIMO.Vec3();
  92242. // The axis in the first body's coordinate system.
  92243. // his property is available in some joints.
  92244. this.localAxis1 = new OIMO.Vec3();
  92245. // The axis in the second body's coordinate system.
  92246. // This property is available in some joints.
  92247. this.localAxis2 = new OIMO.Vec3();
  92248. // Whether allow collision between connected rigid bodies or not.
  92249. this.allowCollision = false;
  92250. };
  92251. /**
  92252. * A link list of joints.
  92253. * @author saharan
  92254. */
  92255. OIMO.JointLink = function (joint) {
  92256. // The previous joint link.
  92257. this.prev = null;
  92258. // The next joint link.
  92259. this.next = null;
  92260. // The other rigid body connected to the joint.
  92261. this.body = null;
  92262. // The joint of the link.
  92263. this.joint = joint;
  92264. };
  92265. /**
  92266. * An information of limit and motor.
  92267. * @author saharan
  92268. */
  92269. OIMO.LimitMotor = function (axis, fixed) {
  92270. fixed = fixed || false;
  92271. // The axis of the constraint.
  92272. this.axis = axis;
  92273. // The current angle for rotational constraints.
  92274. this.angle = 0;
  92275. // The lower limit. Set lower > upper to disable
  92276. this.lowerLimit = fixed ? 0 : 1;
  92277. //if(fixed)this.lowerLimit = 0;
  92278. //else this.lowerLimit = 1;
  92279. // The upper limit. Set lower > upper to disable.
  92280. this.upperLimit = 0;
  92281. // The target motor speed.
  92282. this.motorSpeed = 0;
  92283. // The maximum motor force or torque. Set 0 to disable.
  92284. this.maxMotorForce = 0;
  92285. // The frequency of the spring. Set 0 to disable.
  92286. this.frequency = 0;
  92287. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  92288. this.dampingRatio = 0;
  92289. };
  92290. OIMO.LimitMotor.prototype = {
  92291. constructor: OIMO.LimitMotor,
  92292. /**
  92293. * Set limit data into this constraint.
  92294. * @param lowerLimit
  92295. * @param upperLimit
  92296. */
  92297. setLimit: function (lowerLimit, upperLimit) {
  92298. this.lowerLimit = lowerLimit;
  92299. this.upperLimit = upperLimit;
  92300. },
  92301. /**
  92302. * Set motor data into this constraint.
  92303. * @param motorSpeed
  92304. * @param maxMotorForce
  92305. */
  92306. setMotor: function (motorSpeed, maxMotorForce) {
  92307. this.motorSpeed = motorSpeed;
  92308. this.maxMotorForce = maxMotorForce;
  92309. },
  92310. /**
  92311. * Set spring data into this constraint.
  92312. * @param frequency
  92313. * @param dampingRatio
  92314. */
  92315. setSpring: function (frequency, dampingRatio) {
  92316. this.frequency = frequency;
  92317. this.dampingRatio = dampingRatio;
  92318. }
  92319. };
  92320. /**
  92321. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  92322. * @author saharan
  92323. * @author lo-th
  92324. */
  92325. OIMO.BallAndSocketJoint = function (config) {
  92326. OIMO.Joint.call(this, config);
  92327. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  92328. this.lc = new OIMO.LinearConstraint(this);
  92329. };
  92330. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  92331. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  92332. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  92333. this.updateAnchorPoints();
  92334. this.lc.preSolve(timeStep, invTimeStep);
  92335. };
  92336. OIMO.BallAndSocketJoint.prototype.solve = function () {
  92337. this.lc.solve();
  92338. };
  92339. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  92340. };
  92341. /**
  92342. * A distance joint limits the distance between two anchor points on rigid bodies.
  92343. * @author saharan
  92344. * @author lo-th
  92345. */
  92346. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  92347. OIMO.Joint.call(this, config);
  92348. this.type = OIMO.JOINT_DISTANCE;
  92349. this.normal = new OIMO.Vec3();
  92350. this.nr = new OIMO.Vec3();
  92351. // The limit and motor information of the joint.
  92352. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  92353. this.limitMotor.lowerLimit = minDistance;
  92354. this.limitMotor.upperLimit = maxDistance;
  92355. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  92356. };
  92357. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  92358. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  92359. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  92360. this.updateAnchorPoints();
  92361. //var nr = this.nr;
  92362. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  92363. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  92364. //if(len>0) len = 1/len;
  92365. //this.normal.scale( nr, len );
  92366. this.normal.normalize(this.nr);
  92367. this.t.preSolve(timeStep, invTimeStep);
  92368. };
  92369. OIMO.DistanceJoint.prototype.solve = function () {
  92370. this.t.solve();
  92371. };
  92372. OIMO.DistanceJoint.prototype.postSolve = function () {
  92373. };
  92374. /**
  92375. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  92376. * @author saharan
  92377. * @author lo-th
  92378. */
  92379. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  92380. OIMO.Joint.call(this, config);
  92381. this.type = OIMO.JOINT_HINGE;
  92382. // The axis in the first body's coordinate system.
  92383. this.localAxis1 = config.localAxis1.clone().norm();
  92384. // The axis in the second body's coordinate system.
  92385. this.localAxis2 = config.localAxis2.clone().norm();
  92386. // make angle axis 1
  92387. this.localAngle1 = new OIMO.Vec3(
  92388. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  92389. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  92390. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  92391. ).norm();
  92392. // make angle axis 2
  92393. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  92394. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  92395. this.nor = new OIMO.Vec3();
  92396. this.tan = new OIMO.Vec3();
  92397. this.bin = new OIMO.Vec3();
  92398. this.ax1 = new OIMO.Vec3();
  92399. this.ax2 = new OIMO.Vec3();
  92400. this.an1 = new OIMO.Vec3();
  92401. this.an2 = new OIMO.Vec3();
  92402. // The rotational limit and motor information of the joint.
  92403. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  92404. this.limitMotor.lowerLimit = lowerAngleLimit;
  92405. this.limitMotor.upperLimit = upperAngleLimit;
  92406. this.lc = new OIMO.LinearConstraint(this);
  92407. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  92408. };
  92409. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  92410. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  92411. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  92412. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  92413. this.updateAnchorPoints();
  92414. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  92415. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  92416. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  92417. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  92418. this.nor.set(
  92419. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  92420. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  92421. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  92422. ).norm();
  92423. this.tan.set(
  92424. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  92425. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  92426. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  92427. ).norm();
  92428. this.bin.set(
  92429. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  92430. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  92431. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  92432. );
  92433. // calculate hinge angle
  92434. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  92435. if (
  92436. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  92437. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  92438. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  92439. ) {
  92440. this.limitMotor.angle = -limite;
  92441. } else {
  92442. this.limitMotor.angle = limite;
  92443. }
  92444. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  92445. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  92446. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  92447. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  92448. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  92449. this.r3.preSolve(timeStep, invTimeStep);
  92450. this.lc.preSolve(timeStep, invTimeStep);
  92451. };
  92452. OIMO.HingeJoint.prototype.solve = function () {
  92453. this.r3.solve();
  92454. this.lc.solve();
  92455. };
  92456. OIMO.HingeJoint.prototype.postSolve = function () {
  92457. };
  92458. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  92459. if (cos > 1) return 0;
  92460. else if (cos < -1) return OIMO.PI;
  92461. else return OIMO.acos(cos);
  92462. };
  92463. /**
  92464. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  92465. * @author saharan
  92466. * @author lo-th
  92467. */
  92468. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  92469. OIMO.Joint.call(this, config);
  92470. this.type = OIMO.JOINT_PRISMATIC;
  92471. // The axis in the first body's coordinate system.
  92472. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  92473. // The axis in the second body's coordinate system.
  92474. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  92475. this.localAxis1X = this.localAxis1.x;
  92476. this.localAxis1Y = this.localAxis1.y;
  92477. this.localAxis1Z = this.localAxis1.z;
  92478. this.localAxis2X = this.localAxis2.x;
  92479. this.localAxis2Y = this.localAxis2.y;
  92480. this.localAxis2Z = this.localAxis2.z;
  92481. this.nor = new OIMO.Vec3();
  92482. this.tan = new OIMO.Vec3();
  92483. this.bin = new OIMO.Vec3();
  92484. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  92485. // The translational limit and motor information of the joint.
  92486. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  92487. this.limitMotor.lowerLimit = lowerTranslation;
  92488. this.limitMotor.upperLimit = upperTranslation;
  92489. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  92490. };
  92491. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  92492. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  92493. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  92494. var tmpM;
  92495. var tmp1X;
  92496. var tmp1Y;
  92497. var tmp1Z;
  92498. this.updateAnchorPoints();
  92499. tmpM = this.body1.rotation.elements;
  92500. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  92501. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  92502. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  92503. tmpM = this.body2.rotation.elements;
  92504. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  92505. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  92506. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  92507. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  92508. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  92509. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  92510. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  92511. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  92512. nx *= tmp1X;
  92513. ny *= tmp1X;
  92514. nz *= tmp1X;
  92515. var tx = ny * nx - nz * nz;
  92516. var ty = -nz * ny - nx * nx;
  92517. var tz = nx * nz + ny * ny;
  92518. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  92519. tx *= tmp1X;
  92520. ty *= tmp1X;
  92521. tz *= tmp1X;
  92522. var bx = ny * tz - nz * ty;
  92523. var by = nz * tx - nx * tz;
  92524. var bz = nx * ty - ny * tx;
  92525. this.nor.init(nx, ny, nz);
  92526. this.tan.init(tx, ty, tz);
  92527. this.bin.init(bx, by, bz);
  92528. this.ac.preSolve(timeStep, invTimeStep);
  92529. this.t3.preSolve(timeStep, invTimeStep);
  92530. };
  92531. OIMO.PrismaticJoint.prototype.solve = function () {
  92532. this.ac.solve();
  92533. this.t3.solve();
  92534. };
  92535. OIMO.PrismaticJoint.prototype.postSolve = function () {
  92536. };
  92537. /**
  92538. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  92539. * @author saharan
  92540. * @author lo-th
  92541. */
  92542. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  92543. OIMO.Joint.call(this, config);
  92544. this.type = OIMO.JOINT_SLIDER;
  92545. // The first axis in local coordinate system.
  92546. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  92547. // The second axis in local coordinate system.
  92548. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  92549. var len;
  92550. this.localAxis1X = this.localAxis1.x;
  92551. this.localAxis1Y = this.localAxis1.y;
  92552. this.localAxis1Z = this.localAxis1.z;
  92553. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  92554. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  92555. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  92556. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  92557. this.localAngAxis1X *= len;
  92558. this.localAngAxis1Y *= len;
  92559. this.localAngAxis1Z *= len;
  92560. this.localAxis2X = this.localAxis2.x;
  92561. this.localAxis2Y = this.localAxis2.y;
  92562. this.localAxis2Z = this.localAxis2.z;
  92563. // make angle axis 2
  92564. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  92565. var tarc = arc.elements;
  92566. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  92567. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  92568. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  92569. this.nor = new OIMO.Vec3();
  92570. this.tan = new OIMO.Vec3();
  92571. this.bin = new OIMO.Vec3();
  92572. // The limit and motor for the rotation
  92573. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  92574. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  92575. // The limit and motor for the translation.
  92576. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  92577. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  92578. this.translationalLimitMotor.upperLimit = upperTranslation;
  92579. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  92580. };
  92581. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  92582. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  92583. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  92584. var tmpM;
  92585. var tmp1X;
  92586. var tmp1Y;
  92587. var tmp1Z;
  92588. this.updateAnchorPoints();
  92589. tmpM = this.body1.rotation.elements;
  92590. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  92591. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  92592. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  92593. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  92594. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  92595. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  92596. tmpM = this.body2.rotation.elements;
  92597. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  92598. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  92599. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  92600. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  92601. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  92602. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  92603. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  92604. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  92605. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  92606. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  92607. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  92608. nx *= tmp1X;
  92609. ny *= tmp1X;
  92610. nz *= tmp1X;
  92611. var tx = ny * nx - nz * nz;
  92612. var ty = -nz * ny - nx * nx;
  92613. var tz = nx * nz + ny * ny;
  92614. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  92615. tx *= tmp1X;
  92616. ty *= tmp1X;
  92617. tz *= tmp1X;
  92618. var bx = ny * tz - nz * ty;
  92619. var by = nz * tx - nx * tz;
  92620. var bz = nx * ty - ny * tx;
  92621. this.nor.init(nx, ny, nz);
  92622. this.tan.init(tx, ty, tz);
  92623. this.bin.init(bx, by, bz);
  92624. // ----------------------------------------------
  92625. // calculate hinge angle
  92626. // ----------------------------------------------
  92627. if (
  92628. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  92629. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  92630. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  92631. ) {
  92632. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  92633. } else {
  92634. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  92635. }
  92636. // angular error
  92637. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  92638. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  92639. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  92640. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  92641. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  92642. this.r3.preSolve(timeStep, invTimeStep);
  92643. this.t3.preSolve(timeStep, invTimeStep);
  92644. };
  92645. OIMO.SliderJoint.prototype.solve = function () {
  92646. this.r3.solve();
  92647. this.t3.solve();
  92648. };
  92649. OIMO.SliderJoint.prototype.postSolve = function () {
  92650. };
  92651. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  92652. if (cos > 1) return 0;
  92653. else if (cos < -1) return OIMO.PI;
  92654. else return OIMO.acos(cos);
  92655. };
  92656. /**
  92657. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  92658. * The wheel joint also allows for relative translation for the suspension.
  92659. * @author saharan
  92660. * @author lo-th
  92661. */
  92662. OIMO.WheelJoint = function (config) {
  92663. OIMO.Joint.call(this, config);
  92664. this.type = OIMO.JOINT_WHEEL;
  92665. // The first axis in local coordinate system.
  92666. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  92667. // The second axis in local coordinate system.
  92668. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  92669. var len;
  92670. this.localAxis1X = this.localAxis1.x;
  92671. this.localAxis1Y = this.localAxis1.y;
  92672. this.localAxis1Z = this.localAxis1.z;
  92673. this.localAxis2X = this.localAxis2.x;
  92674. this.localAxis2Y = this.localAxis2.y;
  92675. this.localAxis2Z = this.localAxis2.z;
  92676. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  92677. if (dot > -1 && dot < 1) {
  92678. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  92679. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  92680. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  92681. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  92682. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  92683. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  92684. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  92685. this.localAngAxis1X *= len;
  92686. this.localAngAxis1Y *= len;
  92687. this.localAngAxis1Z *= len;
  92688. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  92689. this.localAngAxis2X *= len;
  92690. this.localAngAxis2Y *= len;
  92691. this.localAngAxis2Z *= len;
  92692. } else {
  92693. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  92694. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  92695. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  92696. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  92697. this.localAngAxis1X *= len;
  92698. this.localAngAxis1Y *= len;
  92699. this.localAngAxis1Z *= len;
  92700. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  92701. var tarc = arc.elements;
  92702. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  92703. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  92704. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  92705. }
  92706. this.nor = new OIMO.Vec3();
  92707. this.tan = new OIMO.Vec3();
  92708. this.bin = new OIMO.Vec3();
  92709. // The translational limit and motor information of the joint.
  92710. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  92711. this.translationalLimitMotor.frequency = 8;
  92712. this.translationalLimitMotor.dampingRatio = 1;
  92713. // The first rotational limit and motor information of the joint.
  92714. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  92715. // The second rotational limit and motor information of the joint.
  92716. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  92717. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  92718. this.t3.weight = 1;
  92719. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  92720. };
  92721. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  92722. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  92723. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  92724. var tmpM;
  92725. var tmp1X;
  92726. var tmp1Y;
  92727. var tmp1Z;
  92728. this.updateAnchorPoints();
  92729. tmpM = this.body1.rotation.elements;
  92730. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  92731. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  92732. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  92733. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  92734. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  92735. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  92736. tmpM = this.body2.rotation.elements;
  92737. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  92738. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  92739. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  92740. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  92741. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  92742. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  92743. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  92744. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  92745. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  92746. } else {
  92747. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  92748. }
  92749. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  92750. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  92751. } else {
  92752. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  92753. }
  92754. var nx = y2 * z1 - z2 * y1;
  92755. var ny = z2 * x1 - x2 * z1;
  92756. var nz = x2 * y1 - y2 * x1;
  92757. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  92758. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  92759. nx *= tmp1X;
  92760. ny *= tmp1X;
  92761. nz *= tmp1X;
  92762. var tx = ny * z2 - nz * y2;
  92763. var ty = nz * x2 - nx * z2;
  92764. var tz = nx * y2 - ny * x2;
  92765. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  92766. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  92767. tx *= tmp1X;
  92768. ty *= tmp1X;
  92769. tz *= tmp1X;
  92770. var bx = y1 * nz - z1 * ny;
  92771. var by = z1 * nx - x1 * nz;
  92772. var bz = x1 * ny - y1 * nx;
  92773. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  92774. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  92775. bx *= tmp1X;
  92776. by *= tmp1X;
  92777. bz *= tmp1X;
  92778. this.nor.init(nx, ny, nz);
  92779. this.tan.init(tx, ty, tz);
  92780. this.bin.init(bx, by, bz);
  92781. this.r3.preSolve(timeStep, invTimeStep);
  92782. this.t3.preSolve(timeStep, invTimeStep);
  92783. };
  92784. OIMO.WheelJoint.prototype.solve = function () {
  92785. this.r3.solve();
  92786. this.t3.solve();
  92787. };
  92788. OIMO.WheelJoint.prototype.postSolve = function () {
  92789. };
  92790. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  92791. if (cos > 1) return 0;
  92792. else if (cos < -1) return OIMO.PI;
  92793. else return OIMO.acos(cos);
  92794. };
  92795. /**
  92796. * An angular constraint for all axes for various joints.
  92797. * @author saharan
  92798. */
  92799. OIMO.AngularConstraint = function (joint, targetOrientation) {
  92800. this.joint = joint;
  92801. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  92802. this.relativeOrientation = new OIMO.Quat();
  92803. this.ii1 = null;
  92804. this.ii2 = null;
  92805. this.dd = null;
  92806. this.vel = new OIMO.Vec3();
  92807. this.imp = new OIMO.Vec3();
  92808. this.rn0 = new OIMO.Vec3();
  92809. this.rn1 = new OIMO.Vec3();
  92810. this.rn2 = new OIMO.Vec3();
  92811. this.b1 = joint.body1;
  92812. this.b2 = joint.body2;
  92813. this.a1 = this.b1.angularVelocity;
  92814. this.a2 = this.b2.angularVelocity;
  92815. this.i1 = this.b1.inverseInertia;
  92816. this.i2 = this.b2.inverseInertia;
  92817. };
  92818. OIMO.AngularConstraint.prototype = {
  92819. constructor: OIMO.AngularConstraint,
  92820. preSolve: function (timeStep, invTimeStep) {
  92821. var inv, len, v, vv;
  92822. this.ii1 = this.i1.clone();
  92823. this.ii2 = this.i2.clone();
  92824. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  92825. 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]));
  92826. this.dd = new OIMO.Mat33(
  92827. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  92828. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  92829. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  92830. ).multiply(inv);
  92831. this.relativeOrientation.invert(this.b1.orientation);
  92832. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  92833. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  92834. inv = this.relativeOrientation.s * 2;
  92835. this.vel.scale(this.relativeOrientation, inv);
  92836. len = this.vel.length();
  92837. if (len > 0.02) {
  92838. len = (0.02 - len) / len * invTimeStep * 0.05;
  92839. this.vel.scaleEqual(len);
  92840. } else {
  92841. this.vel.init();
  92842. }
  92843. this.rn1.mulMat(this.ii1, this.imp);
  92844. this.rn2.mulMat(this.ii2, this.imp);
  92845. this.a1.addEqual(this.rn1);
  92846. this.a2.subEqual(this.rn2);
  92847. },
  92848. solve: function () {
  92849. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  92850. this.rn0.mulMat(this.dd, r);
  92851. this.rn1.mulMat(this.ii1, this.rn0);
  92852. this.rn2.mulMat(this.ii2, this.rn0);
  92853. this.imp.addEqual(this.rn0);
  92854. this.a1.addEqual(this.rn1);
  92855. this.a2.subEqual(this.rn2);
  92856. }
  92857. };
  92858. /**
  92859. * A linear constraint for all axes for various joints.
  92860. * @author saharan
  92861. */
  92862. OIMO.LinearConstraint = function (joint) {
  92863. this.m1 = NaN;
  92864. this.m2 = NaN;
  92865. this.ii1 = null;
  92866. this.ii2 = null;
  92867. this.dd = null;
  92868. this.r1x = NaN;
  92869. this.r1y = NaN;
  92870. this.r1z = NaN;
  92871. this.r2x = NaN;
  92872. this.r2y = NaN;
  92873. this.r2z = NaN;
  92874. this.ax1x = NaN;
  92875. this.ax1y = NaN;
  92876. this.ax1z = NaN;
  92877. this.ay1x = NaN;
  92878. this.ay1y = NaN;
  92879. this.ay1z = NaN;
  92880. this.az1x = NaN;
  92881. this.az1y = NaN;
  92882. this.az1z = NaN;
  92883. this.ax2x = NaN;
  92884. this.ax2y = NaN;
  92885. this.ax2z = NaN;
  92886. this.ay2x = NaN;
  92887. this.ay2y = NaN;
  92888. this.ay2z = NaN;
  92889. this.az2x = NaN;
  92890. this.az2y = NaN;
  92891. this.az2z = NaN;
  92892. this.vel = NaN;
  92893. this.velx = NaN;
  92894. this.vely = NaN;
  92895. this.velz = NaN;
  92896. this.joint = joint;
  92897. this.r1 = joint.relativeAnchorPoint1;
  92898. this.r2 = joint.relativeAnchorPoint2;
  92899. this.p1 = joint.anchorPoint1;
  92900. this.p2 = joint.anchorPoint2;
  92901. this.b1 = joint.body1;
  92902. this.b2 = joint.body2;
  92903. this.l1 = this.b1.linearVelocity;
  92904. this.l2 = this.b2.linearVelocity;
  92905. this.a1 = this.b1.angularVelocity;
  92906. this.a2 = this.b2.angularVelocity;
  92907. this.i1 = this.b1.inverseInertia;
  92908. this.i2 = this.b2.inverseInertia;
  92909. this.impx = 0;
  92910. this.impy = 0;
  92911. this.impz = 0;
  92912. }
  92913. OIMO.LinearConstraint.prototype = {
  92914. constructor: OIMO.LinearConstraint,
  92915. preSolve: function (timeStep, invTimeStep) {
  92916. this.r1x = this.r1.x;
  92917. this.r1y = this.r1.y;
  92918. this.r1z = this.r1.z;
  92919. this.r2x = this.r2.x;
  92920. this.r2y = this.r2.y;
  92921. this.r2z = this.r2.z;
  92922. this.m1 = this.b1.inverseMass;
  92923. this.m2 = this.b2.inverseMass;
  92924. this.ii1 = this.i1.clone();
  92925. this.ii2 = this.i2.clone();
  92926. var ii1 = this.ii1.elements;
  92927. var ii2 = this.ii2.elements;
  92928. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  92929. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  92930. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  92931. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  92932. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  92933. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  92934. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  92935. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  92936. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  92937. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  92938. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  92939. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  92940. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  92941. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  92942. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  92943. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  92944. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  92945. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  92946. // calculate point-to-point mass matrix
  92947. // from impulse equation
  92948. //
  92949. // M = ([/m] - [r^][/I][r^]) ^ -1
  92950. //
  92951. // where
  92952. //
  92953. // [/m] = |1/m, 0, 0|
  92954. // |0, 1/m, 0|
  92955. // |0, 0, 1/m|
  92956. //
  92957. // [r^] = |0, -rz, ry|
  92958. // |rz, 0, -rx|
  92959. // |-ry, rx, 0|
  92960. //
  92961. // [/I] = Inverted moment inertia
  92962. var rxx = this.m1 + this.m2;
  92963. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  92964. var k = kk.elements;
  92965. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  92966. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  92967. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  92968. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  92969. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  92970. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  92971. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  92972. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  92973. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  92974. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  92975. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  92976. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  92977. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  92978. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  92979. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  92980. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  92981. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  92982. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  92983. 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]));
  92984. this.dd = new OIMO.Mat33(
  92985. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  92986. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  92987. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  92988. ).multiply(inv);
  92989. this.velx = this.p2.x - this.p1.x;
  92990. this.vely = this.p2.y - this.p1.y;
  92991. this.velz = this.p2.z - this.p1.z;
  92992. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  92993. if (len > 0.005) {
  92994. len = (0.005 - len) / len * invTimeStep * 0.05;
  92995. this.velx *= len;
  92996. this.vely *= len;
  92997. this.velz *= len;
  92998. } else {
  92999. this.velx = 0;
  93000. this.vely = 0;
  93001. this.velz = 0;
  93002. }
  93003. this.impx *= 0.95;
  93004. this.impy *= 0.95;
  93005. this.impz *= 0.95;
  93006. this.l1.x += this.impx * this.m1;
  93007. this.l1.y += this.impy * this.m1;
  93008. this.l1.z += this.impz * this.m1;
  93009. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  93010. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  93011. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  93012. this.l2.x -= this.impx * this.m2;
  93013. this.l2.y -= this.impy * this.m2;
  93014. this.l2.z -= this.impz * this.m2;
  93015. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  93016. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  93017. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  93018. },
  93019. solve: function () {
  93020. var d = this.dd.elements;
  93021. 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;
  93022. 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;
  93023. 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;
  93024. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  93025. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  93026. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  93027. this.impx += nimpx;
  93028. this.impy += nimpy;
  93029. this.impz += nimpz;
  93030. this.l1.x += nimpx * this.m1;
  93031. this.l1.y += nimpy * this.m1;
  93032. this.l1.z += nimpz * this.m1;
  93033. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  93034. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  93035. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  93036. this.l2.x -= nimpx * this.m2;
  93037. this.l2.y -= nimpy * this.m2;
  93038. this.l2.z -= nimpz * this.m2;
  93039. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  93040. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  93041. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  93042. }
  93043. }
  93044. /**
  93045. * A three-axis rotational constraint for various joints.
  93046. * @author saharan
  93047. */
  93048. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  93049. this.cfm1 = NaN;
  93050. this.cfm2 = NaN;
  93051. this.cfm3 = NaN;
  93052. this.i1e00 = NaN;
  93053. this.i1e01 = NaN;
  93054. this.i1e02 = NaN;
  93055. this.i1e10 = NaN;
  93056. this.i1e11 = NaN;
  93057. this.i1e12 = NaN;
  93058. this.i1e20 = NaN;
  93059. this.i1e21 = NaN;
  93060. this.i1e22 = NaN;
  93061. this.i2e00 = NaN;
  93062. this.i2e01 = NaN;
  93063. this.i2e02 = NaN;
  93064. this.i2e10 = NaN;
  93065. this.i2e11 = NaN;
  93066. this.i2e12 = NaN;
  93067. this.i2e20 = NaN;
  93068. this.i2e21 = NaN;
  93069. this.i2e22 = NaN;
  93070. this.ax1 = NaN;
  93071. this.ay1 = NaN;
  93072. this.az1 = NaN;
  93073. this.ax2 = NaN;
  93074. this.ay2 = NaN;
  93075. this.az2 = NaN;
  93076. this.ax3 = NaN;
  93077. this.ay3 = NaN;
  93078. this.az3 = NaN;
  93079. this.a1x1 = NaN; // jacoians
  93080. this.a1y1 = NaN;
  93081. this.a1z1 = NaN;
  93082. this.a2x1 = NaN;
  93083. this.a2y1 = NaN;
  93084. this.a2z1 = NaN;
  93085. this.a1x2 = NaN;
  93086. this.a1y2 = NaN;
  93087. this.a1z2 = NaN;
  93088. this.a2x2 = NaN;
  93089. this.a2y2 = NaN;
  93090. this.a2z2 = NaN;
  93091. this.a1x3 = NaN;
  93092. this.a1y3 = NaN;
  93093. this.a1z3 = NaN;
  93094. this.a2x3 = NaN;
  93095. this.a2y3 = NaN;
  93096. this.a2z3 = NaN;
  93097. this.lowerLimit1 = NaN;
  93098. this.upperLimit1 = NaN;
  93099. this.limitVelocity1 = NaN;
  93100. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  93101. this.enableMotor1 = false;
  93102. this.motorSpeed1 = NaN;
  93103. this.maxMotorForce1 = NaN;
  93104. this.maxMotorImpulse1 = NaN;
  93105. this.lowerLimit2 = NaN;
  93106. this.upperLimit2 = NaN;
  93107. this.limitVelocity2 = NaN;
  93108. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  93109. this.enableMotor2 = false;
  93110. this.motorSpeed2 = NaN;
  93111. this.maxMotorForce2 = NaN;
  93112. this.maxMotorImpulse2 = NaN;
  93113. this.lowerLimit3 = NaN;
  93114. this.upperLimit3 = NaN;
  93115. this.limitVelocity3 = NaN;
  93116. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  93117. this.enableMotor3 = false;
  93118. this.motorSpeed3 = NaN;
  93119. this.maxMotorForce3 = NaN;
  93120. this.maxMotorImpulse3 = NaN;
  93121. this.k00 = NaN; // K = J*M*JT
  93122. this.k01 = NaN;
  93123. this.k02 = NaN;
  93124. this.k10 = NaN;
  93125. this.k11 = NaN;
  93126. this.k12 = NaN;
  93127. this.k20 = NaN;
  93128. this.k21 = NaN;
  93129. this.k22 = NaN;
  93130. this.kv00 = NaN; // diagonals without CFMs
  93131. this.kv11 = NaN;
  93132. this.kv22 = NaN;
  93133. this.dv00 = NaN; // ...inverted
  93134. this.dv11 = NaN;
  93135. this.dv22 = NaN;
  93136. this.d00 = NaN; // K^-1
  93137. this.d01 = NaN;
  93138. this.d02 = NaN;
  93139. this.d10 = NaN;
  93140. this.d11 = NaN;
  93141. this.d12 = NaN;
  93142. this.d20 = NaN;
  93143. this.d21 = NaN;
  93144. this.d22 = NaN;
  93145. this.limitMotor1 = limitMotor1;
  93146. this.limitMotor2 = limitMotor2;
  93147. this.limitMotor3 = limitMotor3;
  93148. this.b1 = joint.body1;
  93149. this.b2 = joint.body2;
  93150. this.a1 = this.b1.angularVelocity;
  93151. this.a2 = this.b2.angularVelocity;
  93152. this.i1 = this.b1.inverseInertia;
  93153. this.i2 = this.b2.inverseInertia;
  93154. this.limitImpulse1 = 0;
  93155. this.motorImpulse1 = 0;
  93156. this.limitImpulse2 = 0;
  93157. this.motorImpulse2 = 0;
  93158. this.limitImpulse3 = 0;
  93159. this.motorImpulse3 = 0;
  93160. }
  93161. OIMO.Rotational3Constraint.prototype = {
  93162. constructor: OIMO.Rotational3Constraint,
  93163. preSolve: function (timeStep, invTimeStep) {
  93164. this.ax1 = this.limitMotor1.axis.x;
  93165. this.ay1 = this.limitMotor1.axis.y;
  93166. this.az1 = this.limitMotor1.axis.z;
  93167. this.ax2 = this.limitMotor2.axis.x;
  93168. this.ay2 = this.limitMotor2.axis.y;
  93169. this.az2 = this.limitMotor2.axis.z;
  93170. this.ax3 = this.limitMotor3.axis.x;
  93171. this.ay3 = this.limitMotor3.axis.y;
  93172. this.az3 = this.limitMotor3.axis.z;
  93173. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  93174. this.upperLimit1 = this.limitMotor1.upperLimit;
  93175. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  93176. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  93177. this.enableMotor1 = this.maxMotorForce1 > 0;
  93178. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  93179. this.upperLimit2 = this.limitMotor2.upperLimit;
  93180. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  93181. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  93182. this.enableMotor2 = this.maxMotorForce2 > 0;
  93183. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  93184. this.upperLimit3 = this.limitMotor3.upperLimit;
  93185. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  93186. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  93187. this.enableMotor3 = this.maxMotorForce3 > 0;
  93188. var ti1 = this.i1.elements;
  93189. var ti2 = this.i2.elements;
  93190. this.i1e00 = ti1[0];
  93191. this.i1e01 = ti1[1];
  93192. this.i1e02 = ti1[2];
  93193. this.i1e10 = ti1[3];
  93194. this.i1e11 = ti1[4];
  93195. this.i1e12 = ti1[5];
  93196. this.i1e20 = ti1[6];
  93197. this.i1e21 = ti1[7];
  93198. this.i1e22 = ti1[8];
  93199. this.i2e00 = ti2[0];
  93200. this.i2e01 = ti2[1];
  93201. this.i2e02 = ti2[2];
  93202. this.i2e10 = ti2[3];
  93203. this.i2e11 = ti2[4];
  93204. this.i2e12 = ti2[5];
  93205. this.i2e20 = ti2[6];
  93206. this.i2e21 = ti2[7];
  93207. this.i2e22 = ti2[8];
  93208. var frequency1 = this.limitMotor1.frequency;
  93209. var frequency2 = this.limitMotor2.frequency;
  93210. var frequency3 = this.limitMotor3.frequency;
  93211. var enableSpring1 = frequency1 > 0;
  93212. var enableSpring2 = frequency2 > 0;
  93213. var enableSpring3 = frequency3 > 0;
  93214. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  93215. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  93216. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  93217. var angle1 = this.limitMotor1.angle;
  93218. if (enableLimit1) {
  93219. if (this.lowerLimit1 == this.upperLimit1) {
  93220. if (this.limitState1 != 0) {
  93221. this.limitState1 = 0;
  93222. this.limitImpulse1 = 0;
  93223. }
  93224. this.limitVelocity1 = this.lowerLimit1 - angle1;
  93225. } else if (angle1 < this.lowerLimit1) {
  93226. if (this.limitState1 != -1) {
  93227. this.limitState1 = -1;
  93228. this.limitImpulse1 = 0;
  93229. }
  93230. this.limitVelocity1 = this.lowerLimit1 - angle1;
  93231. } else if (angle1 > this.upperLimit1) {
  93232. if (this.limitState1 != 1) {
  93233. this.limitState1 = 1;
  93234. this.limitImpulse1 = 0;
  93235. }
  93236. this.limitVelocity1 = this.upperLimit1 - angle1;
  93237. } else {
  93238. this.limitState1 = 2;
  93239. this.limitImpulse1 = 0;
  93240. this.limitVelocity1 = 0;
  93241. }
  93242. if (!enableSpring1) {
  93243. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  93244. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  93245. else this.limitVelocity1 = 0;
  93246. }
  93247. } else {
  93248. this.limitState1 = 2;
  93249. this.limitImpulse1 = 0;
  93250. }
  93251. var angle2 = this.limitMotor2.angle;
  93252. if (enableLimit2) {
  93253. if (this.lowerLimit2 == this.upperLimit2) {
  93254. if (this.limitState2 != 0) {
  93255. this.limitState2 = 0;
  93256. this.limitImpulse2 = 0;
  93257. }
  93258. this.limitVelocity2 = this.lowerLimit2 - angle2;
  93259. } else if (angle2 < this.lowerLimit2) {
  93260. if (this.limitState2 != -1) {
  93261. this.limitState2 = -1;
  93262. this.limitImpulse2 = 0;
  93263. }
  93264. this.limitVelocity2 = this.lowerLimit2 - angle2;
  93265. } else if (angle2 > this.upperLimit2) {
  93266. if (this.limitState2 != 1) {
  93267. this.limitState2 = 1;
  93268. this.limitImpulse2 = 0;
  93269. }
  93270. this.limitVelocity2 = this.upperLimit2 - angle2;
  93271. } else {
  93272. this.limitState2 = 2;
  93273. this.limitImpulse2 = 0;
  93274. this.limitVelocity2 = 0;
  93275. }
  93276. if (!enableSpring2) {
  93277. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  93278. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  93279. else this.limitVelocity2 = 0;
  93280. }
  93281. } else {
  93282. this.limitState2 = 2;
  93283. this.limitImpulse2 = 0;
  93284. }
  93285. var angle3 = this.limitMotor3.angle;
  93286. if (enableLimit3) {
  93287. if (this.lowerLimit3 == this.upperLimit3) {
  93288. if (this.limitState3 != 0) {
  93289. this.limitState3 = 0;
  93290. this.limitImpulse3 = 0;
  93291. }
  93292. this.limitVelocity3 = this.lowerLimit3 - angle3;
  93293. } else if (angle3 < this.lowerLimit3) {
  93294. if (this.limitState3 != -1) {
  93295. this.limitState3 = -1;
  93296. this.limitImpulse3 = 0;
  93297. }
  93298. this.limitVelocity3 = this.lowerLimit3 - angle3;
  93299. } else if (angle3 > this.upperLimit3) {
  93300. if (this.limitState3 != 1) {
  93301. this.limitState3 = 1;
  93302. this.limitImpulse3 = 0;
  93303. }
  93304. this.limitVelocity3 = this.upperLimit3 - angle3;
  93305. } else {
  93306. this.limitState3 = 2;
  93307. this.limitImpulse3 = 0;
  93308. this.limitVelocity3 = 0;
  93309. }
  93310. if (!enableSpring3) {
  93311. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  93312. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  93313. else this.limitVelocity3 = 0;
  93314. }
  93315. } else {
  93316. this.limitState3 = 2;
  93317. this.limitImpulse3 = 0;
  93318. }
  93319. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  93320. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  93321. } else {
  93322. this.motorImpulse1 = 0;
  93323. this.maxMotorImpulse1 = 0;
  93324. }
  93325. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  93326. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  93327. } else {
  93328. this.motorImpulse2 = 0;
  93329. this.maxMotorImpulse2 = 0;
  93330. }
  93331. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  93332. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  93333. } else {
  93334. this.motorImpulse3 = 0;
  93335. this.maxMotorImpulse3 = 0;
  93336. }
  93337. // build jacobians
  93338. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  93339. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  93340. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  93341. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  93342. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  93343. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  93344. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  93345. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  93346. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  93347. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  93348. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  93349. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  93350. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  93351. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  93352. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  93353. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  93354. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  93355. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  93356. // build an impulse matrix
  93357. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  93358. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  93359. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  93360. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  93361. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  93362. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  93363. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  93364. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  93365. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  93366. this.kv00 = this.k00;
  93367. this.kv11 = this.k11;
  93368. this.kv22 = this.k22;
  93369. this.dv00 = 1 / this.kv00;
  93370. this.dv11 = 1 / this.kv11;
  93371. this.dv22 = 1 / this.kv22;
  93372. if (enableSpring1 && this.limitState1 != 2) {
  93373. var omega = 6.2831853 * frequency1;
  93374. var k = omega * omega * timeStep;
  93375. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  93376. this.cfm1 = this.kv00 * dmp;
  93377. this.limitVelocity1 *= k * dmp;
  93378. } else {
  93379. this.cfm1 = 0;
  93380. this.limitVelocity1 *= invTimeStep * 0.05;
  93381. }
  93382. if (enableSpring2 && this.limitState2 != 2) {
  93383. omega = 6.2831853 * frequency2;
  93384. k = omega * omega * timeStep;
  93385. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  93386. this.cfm2 = this.kv11 * dmp;
  93387. this.limitVelocity2 *= k * dmp;
  93388. } else {
  93389. this.cfm2 = 0;
  93390. this.limitVelocity2 *= invTimeStep * 0.05;
  93391. }
  93392. if (enableSpring3 && this.limitState3 != 2) {
  93393. omega = 6.2831853 * frequency3;
  93394. k = omega * omega * timeStep;
  93395. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  93396. this.cfm3 = this.kv22 * dmp;
  93397. this.limitVelocity3 *= k * dmp;
  93398. } else {
  93399. this.cfm3 = 0;
  93400. this.limitVelocity3 *= invTimeStep * 0.05;
  93401. }
  93402. this.k00 += this.cfm1;
  93403. this.k11 += this.cfm2;
  93404. this.k22 += this.cfm3;
  93405. var inv = 1 / (
  93406. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  93407. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  93408. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  93409. );
  93410. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  93411. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  93412. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  93413. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  93414. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  93415. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  93416. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  93417. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  93418. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  93419. this.limitImpulse1 *= 0.95;
  93420. this.motorImpulse1 *= 0.95;
  93421. this.limitImpulse2 *= 0.95;
  93422. this.motorImpulse2 *= 0.95;
  93423. this.limitImpulse3 *= 0.95;
  93424. this.motorImpulse3 *= 0.95;
  93425. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  93426. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  93427. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  93428. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  93429. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  93430. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  93431. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  93432. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  93433. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  93434. },
  93435. solve_: function () {
  93436. var rvx = this.a2.x - this.a1.x;
  93437. var rvy = this.a2.y - this.a1.y;
  93438. var rvz = this.a2.z - this.a1.z;
  93439. this.limitVelocity3 = 30;
  93440. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  93441. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  93442. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  93443. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  93444. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  93445. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  93446. this.limitImpulse1 += dLimitImpulse1;
  93447. this.limitImpulse2 += dLimitImpulse2;
  93448. this.limitImpulse3 += dLimitImpulse3;
  93449. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  93450. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  93451. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  93452. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  93453. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  93454. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  93455. },
  93456. solve: function () {
  93457. var rvx = this.a2.x - this.a1.x;
  93458. var rvy = this.a2.y - this.a1.y;
  93459. var rvz = this.a2.z - this.a1.z;
  93460. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  93461. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  93462. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  93463. var oldMotorImpulse1 = this.motorImpulse1;
  93464. var oldMotorImpulse2 = this.motorImpulse2;
  93465. var oldMotorImpulse3 = this.motorImpulse3;
  93466. var dMotorImpulse1 = 0;
  93467. var dMotorImpulse2 = 0;
  93468. var dMotorImpulse3 = 0;
  93469. if (this.enableMotor1) {
  93470. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  93471. this.motorImpulse1 += dMotorImpulse1;
  93472. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  93473. this.motorImpulse1 = this.maxMotorImpulse1;
  93474. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  93475. this.motorImpulse1 = -this.maxMotorImpulse1;
  93476. }
  93477. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  93478. }
  93479. if (this.enableMotor2) {
  93480. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  93481. this.motorImpulse2 += dMotorImpulse2;
  93482. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  93483. this.motorImpulse2 = this.maxMotorImpulse2;
  93484. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  93485. this.motorImpulse2 = -this.maxMotorImpulse2;
  93486. }
  93487. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  93488. }
  93489. if (this.enableMotor3) {
  93490. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  93491. this.motorImpulse3 += dMotorImpulse3;
  93492. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  93493. this.motorImpulse3 = this.maxMotorImpulse3;
  93494. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  93495. this.motorImpulse3 = -this.maxMotorImpulse3;
  93496. }
  93497. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  93498. }
  93499. // apply motor impulse to relative velocity
  93500. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  93501. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  93502. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  93503. // subtract target velocity and applied impulse
  93504. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  93505. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  93506. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  93507. var oldLimitImpulse1 = this.limitImpulse1;
  93508. var oldLimitImpulse2 = this.limitImpulse2;
  93509. var oldLimitImpulse3 = this.limitImpulse3;
  93510. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  93511. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  93512. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  93513. this.limitImpulse1 += dLimitImpulse1;
  93514. this.limitImpulse2 += dLimitImpulse2;
  93515. this.limitImpulse3 += dLimitImpulse3;
  93516. // clamp
  93517. var clampState = 0;
  93518. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  93519. dLimitImpulse1 = -oldLimitImpulse1;
  93520. rvn2 += dLimitImpulse1 * this.k10;
  93521. rvn3 += dLimitImpulse1 * this.k20;
  93522. clampState |= 1;
  93523. }
  93524. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  93525. dLimitImpulse2 = -oldLimitImpulse2;
  93526. rvn1 += dLimitImpulse2 * this.k01;
  93527. rvn3 += dLimitImpulse2 * this.k21;
  93528. clampState |= 2;
  93529. }
  93530. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  93531. dLimitImpulse3 = -oldLimitImpulse3;
  93532. rvn1 += dLimitImpulse3 * this.k02;
  93533. rvn2 += dLimitImpulse3 * this.k12;
  93534. clampState |= 4;
  93535. }
  93536. // update un-clamped impulse
  93537. // TODO: isolate division
  93538. var det;
  93539. switch (clampState) {
  93540. case 1: // update 2 3
  93541. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  93542. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  93543. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  93544. break;
  93545. case 2: // update 1 3
  93546. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  93547. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  93548. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  93549. break;
  93550. case 3: // update 3
  93551. dLimitImpulse3 = rvn3 / this.k22;
  93552. break;
  93553. case 4: // update 1 2
  93554. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  93555. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  93556. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  93557. break;
  93558. case 5: // update 2
  93559. dLimitImpulse2 = rvn2 / this.k11;
  93560. break;
  93561. case 6: // update 1
  93562. dLimitImpulse1 = rvn1 / this.k00;
  93563. break;
  93564. }
  93565. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  93566. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  93567. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  93568. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  93569. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  93570. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  93571. // apply impulse
  93572. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  93573. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  93574. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  93575. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  93576. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  93577. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  93578. rvx = this.a2.x - this.a1.x;
  93579. rvy = this.a2.y - this.a1.y;
  93580. rvz = this.a2.z - this.a1.z;
  93581. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  93582. }
  93583. }
  93584. /**
  93585. * A rotational constraint for various joints.
  93586. * @author saharan
  93587. */
  93588. OIMO.RotationalConstraint = function (joint, limitMotor) {
  93589. this.cfm = NaN;
  93590. this.i1e00 = NaN;
  93591. this.i1e01 = NaN;
  93592. this.i1e02 = NaN;
  93593. this.i1e10 = NaN;
  93594. this.i1e11 = NaN;
  93595. this.i1e12 = NaN;
  93596. this.i1e20 = NaN;
  93597. this.i1e21 = NaN;
  93598. this.i1e22 = NaN;
  93599. this.i2e00 = NaN;
  93600. this.i2e01 = NaN;
  93601. this.i2e02 = NaN;
  93602. this.i2e10 = NaN;
  93603. this.i2e11 = NaN;
  93604. this.i2e12 = NaN;
  93605. this.i2e20 = NaN;
  93606. this.i2e21 = NaN;
  93607. this.i2e22 = NaN;
  93608. this.motorDenom = NaN;
  93609. this.invMotorDenom = NaN;
  93610. this.invDenom = NaN;
  93611. this.ax = NaN;
  93612. this.ay = NaN;
  93613. this.az = NaN;
  93614. this.a1x = NaN;
  93615. this.a1y = NaN;
  93616. this.a1z = NaN;
  93617. this.a2x = NaN;
  93618. this.a2y = NaN;
  93619. this.a2z = NaN;
  93620. this.enableLimit = false;
  93621. this.lowerLimit = NaN;
  93622. this.upperLimit = NaN;
  93623. this.limitVelocity = NaN;
  93624. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  93625. this.enableMotor = false;
  93626. this.motorSpeed = NaN;
  93627. this.maxMotorForce = NaN;
  93628. this.maxMotorImpulse = NaN;
  93629. this.limitMotor = limitMotor;
  93630. this.b1 = joint.body1;
  93631. this.b2 = joint.body2;
  93632. this.a1 = this.b1.angularVelocity;
  93633. this.a2 = this.b2.angularVelocity;
  93634. this.i1 = this.b1.inverseInertia;
  93635. this.i2 = this.b2.inverseInertia;
  93636. this.limitImpulse = 0;
  93637. this.motorImpulse = 0;
  93638. }
  93639. OIMO.RotationalConstraint.prototype = {
  93640. constructor: OIMO.RotationalConstraint,
  93641. preSolve: function (timeStep, invTimeStep) {
  93642. this.ax = this.limitMotor.axis.x;
  93643. this.ay = this.limitMotor.axis.y;
  93644. this.az = this.limitMotor.axis.z;
  93645. this.lowerLimit = this.limitMotor.lowerLimit;
  93646. this.upperLimit = this.limitMotor.upperLimit;
  93647. this.motorSpeed = this.limitMotor.motorSpeed;
  93648. this.maxMotorForce = this.limitMotor.maxMotorForce;
  93649. this.enableMotor = this.maxMotorForce > 0;
  93650. var ti1 = this.i1.elements;
  93651. var ti2 = this.i2.elements;
  93652. this.i1e00 = ti1[0];
  93653. this.i1e01 = ti1[1];
  93654. this.i1e02 = ti1[2];
  93655. this.i1e10 = ti1[3];
  93656. this.i1e11 = ti1[4];
  93657. this.i1e12 = ti1[5];
  93658. this.i1e20 = ti1[6];
  93659. this.i1e21 = ti1[7];
  93660. this.i1e22 = ti1[8];
  93661. this.i2e00 = ti2[0];
  93662. this.i2e01 = ti2[1];
  93663. this.i2e02 = ti2[2];
  93664. this.i2e10 = ti2[3];
  93665. this.i2e11 = ti2[4];
  93666. this.i2e12 = ti2[5];
  93667. this.i2e20 = ti2[6];
  93668. this.i2e21 = ti2[7];
  93669. this.i2e22 = ti2[8];
  93670. var frequency = this.limitMotor.frequency;
  93671. var enableSpring = frequency > 0;
  93672. var enableLimit = this.lowerLimit <= this.upperLimit;
  93673. var angle = this.limitMotor.angle;
  93674. if (enableLimit) {
  93675. if (this.lowerLimit == this.upperLimit) {
  93676. if (this.limitState != 0) {
  93677. this.limitState = 0;
  93678. this.limitImpulse = 0;
  93679. }
  93680. this.limitVelocity = this.lowerLimit - angle;
  93681. } else if (angle < this.lowerLimit) {
  93682. if (this.limitState != -1) {
  93683. this.limitState = -1;
  93684. this.limitImpulse = 0;
  93685. }
  93686. this.limitVelocity = this.lowerLimit - angle;
  93687. } else if (angle > this.upperLimit) {
  93688. if (this.limitState != 1) {
  93689. this.limitState = 1;
  93690. this.limitImpulse = 0;
  93691. }
  93692. this.limitVelocity = this.upperLimit - angle;
  93693. } else {
  93694. this.limitState = 2;
  93695. this.limitImpulse = 0;
  93696. this.limitVelocity = 0;
  93697. }
  93698. if (!enableSpring) {
  93699. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  93700. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  93701. else this.limitVelocity = 0;
  93702. }
  93703. } else {
  93704. this.limitState = 2;
  93705. this.limitImpulse = 0;
  93706. }
  93707. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  93708. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  93709. } else {
  93710. this.motorImpulse = 0;
  93711. this.maxMotorImpulse = 0;
  93712. }
  93713. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  93714. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  93715. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  93716. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  93717. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  93718. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  93719. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  93720. this.invMotorDenom = 1 / this.motorDenom;
  93721. if (enableSpring && this.limitState != 2) {
  93722. var omega = 6.2831853 * frequency;
  93723. var k = omega * omega * timeStep;
  93724. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  93725. this.cfm = this.motorDenom * dmp;
  93726. this.limitVelocity *= k * dmp;
  93727. } else {
  93728. this.cfm = 0;
  93729. this.limitVelocity *= invTimeStep * 0.05;
  93730. }
  93731. this.invDenom = 1 / (this.motorDenom + this.cfm);
  93732. this.limitImpulse *= 0.95;
  93733. this.motorImpulse *= 0.95;
  93734. var totalImpulse = this.limitImpulse + this.motorImpulse;
  93735. this.a1.x += totalImpulse * this.a1x;
  93736. this.a1.y += totalImpulse * this.a1y;
  93737. this.a1.z += totalImpulse * this.a1z;
  93738. this.a2.x -= totalImpulse * this.a2x;
  93739. this.a2.y -= totalImpulse * this.a2y;
  93740. this.a2.z -= totalImpulse * this.a2z;
  93741. },
  93742. solve: function () {
  93743. 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);
  93744. // motor part
  93745. var newMotorImpulse;
  93746. if (this.enableMotor) {
  93747. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  93748. var oldMotorImpulse = this.motorImpulse;
  93749. this.motorImpulse += newMotorImpulse;
  93750. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  93751. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  93752. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  93753. rvn -= newMotorImpulse * this.motorDenom;
  93754. } else newMotorImpulse = 0;
  93755. // limit part
  93756. var newLimitImpulse;
  93757. if (this.limitState != 2) {
  93758. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  93759. var oldLimitImpulse = this.limitImpulse;
  93760. this.limitImpulse += newLimitImpulse;
  93761. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  93762. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  93763. } else newLimitImpulse = 0;
  93764. var totalImpulse = newLimitImpulse + newMotorImpulse;
  93765. this.a1.x += totalImpulse * this.a1x;
  93766. this.a1.y += totalImpulse * this.a1y;
  93767. this.a1.z += totalImpulse * this.a1z;
  93768. this.a2.x -= totalImpulse * this.a2x;
  93769. this.a2.y -= totalImpulse * this.a2y;
  93770. this.a2.z -= totalImpulse * this.a2z;
  93771. }
  93772. }
  93773. /**
  93774. * A three-axis translational constraint for various joints.
  93775. * @author saharan
  93776. */
  93777. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  93778. this.m1 = NaN;
  93779. this.m2 = NaN;
  93780. this.i1e00 = NaN;
  93781. this.i1e01 = NaN;
  93782. this.i1e02 = NaN;
  93783. this.i1e10 = NaN;
  93784. this.i1e11 = NaN;
  93785. this.i1e12 = NaN;
  93786. this.i1e20 = NaN;
  93787. this.i1e21 = NaN;
  93788. this.i1e22 = NaN;
  93789. this.i2e00 = NaN;
  93790. this.i2e01 = NaN;
  93791. this.i2e02 = NaN;
  93792. this.i2e10 = NaN;
  93793. this.i2e11 = NaN;
  93794. this.i2e12 = NaN;
  93795. this.i2e20 = NaN;
  93796. this.i2e21 = NaN;
  93797. this.i2e22 = NaN;
  93798. this.ax1 = NaN;
  93799. this.ay1 = NaN;
  93800. this.az1 = NaN;
  93801. this.ax2 = NaN;
  93802. this.ay2 = NaN;
  93803. this.az2 = NaN;
  93804. this.ax3 = NaN;
  93805. this.ay3 = NaN;
  93806. this.az3 = NaN;
  93807. this.r1x = NaN;
  93808. this.r1y = NaN;
  93809. this.r1z = NaN;
  93810. this.r2x = NaN;
  93811. this.r2y = NaN;
  93812. this.r2z = NaN;
  93813. this.t1x1 = NaN;// jacobians
  93814. this.t1y1 = NaN;
  93815. this.t1z1 = NaN;
  93816. this.t2x1 = NaN;
  93817. this.t2y1 = NaN;
  93818. this.t2z1 = NaN;
  93819. this.l1x1 = NaN;
  93820. this.l1y1 = NaN;
  93821. this.l1z1 = NaN;
  93822. this.l2x1 = NaN;
  93823. this.l2y1 = NaN;
  93824. this.l2z1 = NaN;
  93825. this.a1x1 = NaN;
  93826. this.a1y1 = NaN;
  93827. this.a1z1 = NaN;
  93828. this.a2x1 = NaN;
  93829. this.a2y1 = NaN;
  93830. this.a2z1 = NaN;
  93831. this.t1x2 = NaN;
  93832. this.t1y2 = NaN;
  93833. this.t1z2 = NaN;
  93834. this.t2x2 = NaN;
  93835. this.t2y2 = NaN;
  93836. this.t2z2 = NaN;
  93837. this.l1x2 = NaN;
  93838. this.l1y2 = NaN;
  93839. this.l1z2 = NaN;
  93840. this.l2x2 = NaN;
  93841. this.l2y2 = NaN;
  93842. this.l2z2 = NaN;
  93843. this.a1x2 = NaN;
  93844. this.a1y2 = NaN;
  93845. this.a1z2 = NaN;
  93846. this.a2x2 = NaN;
  93847. this.a2y2 = NaN;
  93848. this.a2z2 = NaN;
  93849. this.t1x3 = NaN;
  93850. this.t1y3 = NaN;
  93851. this.t1z3 = NaN;
  93852. this.t2x3 = NaN;
  93853. this.t2y3 = NaN;
  93854. this.t2z3 = NaN;
  93855. this.l1x3 = NaN;
  93856. this.l1y3 = NaN;
  93857. this.l1z3 = NaN;
  93858. this.l2x3 = NaN;
  93859. this.l2y3 = NaN;
  93860. this.l2z3 = NaN;
  93861. this.a1x3 = NaN;
  93862. this.a1y3 = NaN;
  93863. this.a1z3 = NaN;
  93864. this.a2x3 = NaN;
  93865. this.a2y3 = NaN;
  93866. this.a2z3 = NaN;
  93867. this.lowerLimit1 = NaN;
  93868. this.upperLimit1 = NaN;
  93869. this.limitVelocity1 = NaN;
  93870. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  93871. this.enableMotor1 = false;
  93872. this.motorSpeed1 = NaN;
  93873. this.maxMotorForce1 = NaN;
  93874. this.maxMotorImpulse1 = NaN;
  93875. this.lowerLimit2 = NaN;
  93876. this.upperLimit2 = NaN;
  93877. this.limitVelocity2 = NaN;
  93878. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  93879. this.enableMotor2 = false;
  93880. this.motorSpeed2 = NaN;
  93881. this.maxMotorForce2 = NaN;
  93882. this.maxMotorImpulse2 = NaN;
  93883. this.lowerLimit3 = NaN;
  93884. this.upperLimit3 = NaN;
  93885. this.limitVelocity3 = NaN;
  93886. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  93887. this.enableMotor3 = false;
  93888. this.motorSpeed3 = NaN;
  93889. this.maxMotorForce3 = NaN;
  93890. this.maxMotorImpulse3 = NaN;
  93891. this.k00 = NaN; // K = J*M*JT
  93892. this.k01 = NaN;
  93893. this.k02 = NaN;
  93894. this.k10 = NaN;
  93895. this.k11 = NaN;
  93896. this.k12 = NaN;
  93897. this.k20 = NaN;
  93898. this.k21 = NaN;
  93899. this.k22 = NaN;
  93900. this.kv00 = NaN; // diagonals without CFMs
  93901. this.kv11 = NaN;
  93902. this.kv22 = NaN;
  93903. this.dv00 = NaN; // ...inverted
  93904. this.dv11 = NaN;
  93905. this.dv22 = NaN;
  93906. this.d00 = NaN; // K^-1
  93907. this.d01 = NaN;
  93908. this.d02 = NaN;
  93909. this.d10 = NaN;
  93910. this.d11 = NaN;
  93911. this.d12 = NaN;
  93912. this.d20 = NaN;
  93913. this.d21 = NaN;
  93914. this.d22 = NaN;
  93915. this.limitMotor1 = limitMotor1;
  93916. this.limitMotor2 = limitMotor2;
  93917. this.limitMotor3 = limitMotor3;
  93918. this.b1 = joint.body1;
  93919. this.b2 = joint.body2;
  93920. this.p1 = joint.anchorPoint1;
  93921. this.p2 = joint.anchorPoint2;
  93922. this.r1 = joint.relativeAnchorPoint1;
  93923. this.r2 = joint.relativeAnchorPoint2;
  93924. this.l1 = this.b1.linearVelocity;
  93925. this.l2 = this.b2.linearVelocity;
  93926. this.a1 = this.b1.angularVelocity;
  93927. this.a2 = this.b2.angularVelocity;
  93928. this.i1 = this.b1.inverseInertia;
  93929. this.i2 = this.b2.inverseInertia;
  93930. this.limitImpulse1 = 0;
  93931. this.motorImpulse1 = 0;
  93932. this.limitImpulse2 = 0;
  93933. this.motorImpulse2 = 0;
  93934. this.limitImpulse3 = 0;
  93935. this.motorImpulse3 = 0;
  93936. this.cfm1 = 0;// Constraint Force Mixing
  93937. this.cfm2 = 0;
  93938. this.cfm3 = 0;
  93939. this.weight = -1;
  93940. }
  93941. OIMO.Translational3Constraint.prototype = {
  93942. constructor: OIMO.Translational3Constraint,
  93943. preSolve: function (timeStep, invTimeStep) {
  93944. this.ax1 = this.limitMotor1.axis.x;
  93945. this.ay1 = this.limitMotor1.axis.y;
  93946. this.az1 = this.limitMotor1.axis.z;
  93947. this.ax2 = this.limitMotor2.axis.x;
  93948. this.ay2 = this.limitMotor2.axis.y;
  93949. this.az2 = this.limitMotor2.axis.z;
  93950. this.ax3 = this.limitMotor3.axis.x;
  93951. this.ay3 = this.limitMotor3.axis.y;
  93952. this.az3 = this.limitMotor3.axis.z;
  93953. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  93954. this.upperLimit1 = this.limitMotor1.upperLimit;
  93955. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  93956. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  93957. this.enableMotor1 = this.maxMotorForce1 > 0;
  93958. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  93959. this.upperLimit2 = this.limitMotor2.upperLimit;
  93960. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  93961. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  93962. this.enableMotor2 = this.maxMotorForce2 > 0;
  93963. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  93964. this.upperLimit3 = this.limitMotor3.upperLimit;
  93965. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  93966. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  93967. this.enableMotor3 = this.maxMotorForce3 > 0;
  93968. this.m1 = this.b1.inverseMass;
  93969. this.m2 = this.b2.inverseMass;
  93970. var ti1 = this.i1.elements;
  93971. var ti2 = this.i2.elements;
  93972. this.i1e00 = ti1[0];
  93973. this.i1e01 = ti1[1];
  93974. this.i1e02 = ti1[2];
  93975. this.i1e10 = ti1[3];
  93976. this.i1e11 = ti1[4];
  93977. this.i1e12 = ti1[5];
  93978. this.i1e20 = ti1[6];
  93979. this.i1e21 = ti1[7];
  93980. this.i1e22 = ti1[8];
  93981. this.i2e00 = ti2[0];
  93982. this.i2e01 = ti2[1];
  93983. this.i2e02 = ti2[2];
  93984. this.i2e10 = ti2[3];
  93985. this.i2e11 = ti2[4];
  93986. this.i2e12 = ti2[5];
  93987. this.i2e20 = ti2[6];
  93988. this.i2e21 = ti2[7];
  93989. this.i2e22 = ti2[8];
  93990. var dx = this.p2.x - this.p1.x;
  93991. var dy = this.p2.y - this.p1.y;
  93992. var dz = this.p2.z - this.p1.z;
  93993. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  93994. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  93995. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  93996. var frequency1 = this.limitMotor1.frequency;
  93997. var frequency2 = this.limitMotor2.frequency;
  93998. var frequency3 = this.limitMotor3.frequency;
  93999. var enableSpring1 = frequency1 > 0;
  94000. var enableSpring2 = frequency2 > 0;
  94001. var enableSpring3 = frequency3 > 0;
  94002. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  94003. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  94004. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  94005. // for stability
  94006. if (enableSpring1 && d1 > 20 || d1 < -20) {
  94007. enableSpring1 = false;
  94008. }
  94009. if (enableSpring2 && d2 > 20 || d2 < -20) {
  94010. enableSpring2 = false;
  94011. }
  94012. if (enableSpring3 && d3 > 20 || d3 < -20) {
  94013. enableSpring3 = false;
  94014. }
  94015. if (enableLimit1) {
  94016. if (this.lowerLimit1 == this.upperLimit1) {
  94017. if (this.limitState1 != 0) {
  94018. this.limitState1 = 0;
  94019. this.limitImpulse1 = 0;
  94020. }
  94021. this.limitVelocity1 = this.lowerLimit1 - d1;
  94022. if (!enableSpring1) d1 = this.lowerLimit1;
  94023. } else if (d1 < this.lowerLimit1) {
  94024. if (this.limitState1 != -1) {
  94025. this.limitState1 = -1;
  94026. this.limitImpulse1 = 0;
  94027. }
  94028. this.limitVelocity1 = this.lowerLimit1 - d1;
  94029. if (!enableSpring1) d1 = this.lowerLimit1;
  94030. } else if (d1 > this.upperLimit1) {
  94031. if (this.limitState1 != 1) {
  94032. this.limitState1 = 1;
  94033. this.limitImpulse1 = 0;
  94034. }
  94035. this.limitVelocity1 = this.upperLimit1 - d1;
  94036. if (!enableSpring1) d1 = this.upperLimit1;
  94037. } else {
  94038. this.limitState1 = 2;
  94039. this.limitImpulse1 = 0;
  94040. this.limitVelocity1 = 0;
  94041. }
  94042. if (!enableSpring1) {
  94043. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  94044. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  94045. else this.limitVelocity1 = 0;
  94046. }
  94047. } else {
  94048. this.limitState1 = 2;
  94049. this.limitImpulse1 = 0;
  94050. }
  94051. if (enableLimit2) {
  94052. if (this.lowerLimit2 == this.upperLimit2) {
  94053. if (this.limitState2 != 0) {
  94054. this.limitState2 = 0;
  94055. this.limitImpulse2 = 0;
  94056. }
  94057. this.limitVelocity2 = this.lowerLimit2 - d2;
  94058. if (!enableSpring2) d2 = this.lowerLimit2;
  94059. } else if (d2 < this.lowerLimit2) {
  94060. if (this.limitState2 != -1) {
  94061. this.limitState2 = -1;
  94062. this.limitImpulse2 = 0;
  94063. }
  94064. this.limitVelocity2 = this.lowerLimit2 - d2;
  94065. if (!enableSpring2) d2 = this.lowerLimit2;
  94066. } else if (d2 > this.upperLimit2) {
  94067. if (this.limitState2 != 1) {
  94068. this.limitState2 = 1;
  94069. this.limitImpulse2 = 0;
  94070. }
  94071. this.limitVelocity2 = this.upperLimit2 - d2;
  94072. if (!enableSpring2) d2 = this.upperLimit2;
  94073. } else {
  94074. this.limitState2 = 2;
  94075. this.limitImpulse2 = 0;
  94076. this.limitVelocity2 = 0;
  94077. }
  94078. if (!enableSpring2) {
  94079. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  94080. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  94081. else this.limitVelocity2 = 0;
  94082. }
  94083. } else {
  94084. this.limitState2 = 2;
  94085. this.limitImpulse2 = 0;
  94086. }
  94087. if (enableLimit3) {
  94088. if (this.lowerLimit3 == this.upperLimit3) {
  94089. if (this.limitState3 != 0) {
  94090. this.limitState3 = 0;
  94091. this.limitImpulse3 = 0;
  94092. }
  94093. this.limitVelocity3 = this.lowerLimit3 - d3;
  94094. if (!enableSpring3) d3 = this.lowerLimit3;
  94095. } else if (d3 < this.lowerLimit3) {
  94096. if (this.limitState3 != -1) {
  94097. this.limitState3 = -1;
  94098. this.limitImpulse3 = 0;
  94099. }
  94100. this.limitVelocity3 = this.lowerLimit3 - d3;
  94101. if (!enableSpring3) d3 = this.lowerLimit3;
  94102. } else if (d3 > this.upperLimit3) {
  94103. if (this.limitState3 != 1) {
  94104. this.limitState3 = 1;
  94105. this.limitImpulse3 = 0;
  94106. }
  94107. this.limitVelocity3 = this.upperLimit3 - d3;
  94108. if (!enableSpring3) d3 = this.upperLimit3;
  94109. } else {
  94110. this.limitState3 = 2;
  94111. this.limitImpulse3 = 0;
  94112. this.limitVelocity3 = 0;
  94113. }
  94114. if (!enableSpring3) {
  94115. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  94116. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  94117. else this.limitVelocity3 = 0;
  94118. }
  94119. } else {
  94120. this.limitState3 = 2;
  94121. this.limitImpulse3 = 0;
  94122. }
  94123. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  94124. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  94125. } else {
  94126. this.motorImpulse1 = 0;
  94127. this.maxMotorImpulse1 = 0;
  94128. }
  94129. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  94130. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  94131. } else {
  94132. this.motorImpulse2 = 0;
  94133. this.maxMotorImpulse2 = 0;
  94134. }
  94135. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  94136. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  94137. } else {
  94138. this.motorImpulse3 = 0;
  94139. this.maxMotorImpulse3 = 0;
  94140. }
  94141. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  94142. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  94143. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  94144. var w1 = this.m2 / (this.m1 + this.m2);
  94145. if (this.weight >= 0) w1 = this.weight; // use given weight
  94146. var w2 = 1 - w1;
  94147. this.r1x = this.r1.x + rdx * w1;
  94148. this.r1y = this.r1.y + rdy * w1;
  94149. this.r1z = this.r1.z + rdz * w1;
  94150. this.r2x = this.r2.x - rdx * w2;
  94151. this.r2y = this.r2.y - rdy * w2;
  94152. this.r2z = this.r2.z - rdz * w2;
  94153. // build jacobians
  94154. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  94155. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  94156. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  94157. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  94158. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  94159. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  94160. this.l1x1 = this.ax1 * this.m1;
  94161. this.l1y1 = this.ay1 * this.m1;
  94162. this.l1z1 = this.az1 * this.m1;
  94163. this.l2x1 = this.ax1 * this.m2;
  94164. this.l2y1 = this.ay1 * this.m2;
  94165. this.l2z1 = this.az1 * this.m2;
  94166. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  94167. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  94168. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  94169. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  94170. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  94171. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  94172. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  94173. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  94174. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  94175. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  94176. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  94177. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  94178. this.l1x2 = this.ax2 * this.m1;
  94179. this.l1y2 = this.ay2 * this.m1;
  94180. this.l1z2 = this.az2 * this.m1;
  94181. this.l2x2 = this.ax2 * this.m2;
  94182. this.l2y2 = this.ay2 * this.m2;
  94183. this.l2z2 = this.az2 * this.m2;
  94184. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  94185. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  94186. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  94187. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  94188. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  94189. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  94190. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  94191. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  94192. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  94193. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  94194. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  94195. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  94196. this.l1x3 = this.ax3 * this.m1;
  94197. this.l1y3 = this.ay3 * this.m1;
  94198. this.l1z3 = this.az3 * this.m1;
  94199. this.l2x3 = this.ax3 * this.m2;
  94200. this.l2y3 = this.ay3 * this.m2;
  94201. this.l2z3 = this.az3 * this.m2;
  94202. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  94203. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  94204. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  94205. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  94206. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  94207. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  94208. // build an impulse matrix
  94209. var m12 = this.m1 + this.m2;
  94210. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  94211. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  94212. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  94213. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  94214. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  94215. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  94216. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  94217. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  94218. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  94219. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  94220. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  94221. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  94222. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  94223. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  94224. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  94225. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  94226. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  94227. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  94228. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  94229. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  94230. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  94231. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  94232. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  94233. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  94234. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  94235. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  94236. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  94237. this.kv00 = this.k00;
  94238. this.kv11 = this.k11;
  94239. this.kv22 = this.k22;
  94240. this.dv00 = 1 / this.kv00;
  94241. this.dv11 = 1 / this.kv11;
  94242. this.dv22 = 1 / this.kv22;
  94243. if (enableSpring1 && this.limitState1 != 2) {
  94244. var omega = 6.2831853 * frequency1;
  94245. var k = omega * omega * timeStep;
  94246. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  94247. this.cfm1 = this.kv00 * dmp;
  94248. this.limitVelocity1 *= k * dmp;
  94249. } else {
  94250. this.cfm1 = 0;
  94251. this.limitVelocity1 *= invTimeStep * 0.05;
  94252. }
  94253. if (enableSpring2 && this.limitState2 != 2) {
  94254. omega = 6.2831853 * frequency2;
  94255. k = omega * omega * timeStep;
  94256. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  94257. this.cfm2 = this.kv11 * dmp;
  94258. this.limitVelocity2 *= k * dmp;
  94259. } else {
  94260. this.cfm2 = 0;
  94261. this.limitVelocity2 *= invTimeStep * 0.05;
  94262. }
  94263. if (enableSpring3 && this.limitState3 != 2) {
  94264. omega = 6.2831853 * frequency3;
  94265. k = omega * omega * timeStep;
  94266. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  94267. this.cfm3 = this.kv22 * dmp;
  94268. this.limitVelocity3 *= k * dmp;
  94269. } else {
  94270. this.cfm3 = 0;
  94271. this.limitVelocity3 *= invTimeStep * 0.05;
  94272. }
  94273. this.k00 += this.cfm1;
  94274. this.k11 += this.cfm2;
  94275. this.k22 += this.cfm3;
  94276. var inv = 1 / (
  94277. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  94278. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  94279. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  94280. );
  94281. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  94282. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  94283. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  94284. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  94285. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  94286. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  94287. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  94288. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  94289. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  94290. // warm starting
  94291. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  94292. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  94293. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  94294. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  94295. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  94296. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  94297. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  94298. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  94299. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  94300. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  94301. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  94302. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  94303. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  94304. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  94305. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  94306. },
  94307. solve: function () {
  94308. 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;
  94309. 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;
  94310. 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;
  94311. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  94312. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  94313. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  94314. var oldMotorImpulse1 = this.motorImpulse1;
  94315. var oldMotorImpulse2 = this.motorImpulse2;
  94316. var oldMotorImpulse3 = this.motorImpulse3;
  94317. var dMotorImpulse1 = 0;
  94318. var dMotorImpulse2 = 0;
  94319. var dMotorImpulse3 = 0;
  94320. if (this.enableMotor1) {
  94321. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  94322. this.motorImpulse1 += dMotorImpulse1;
  94323. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  94324. this.motorImpulse1 = this.maxMotorImpulse1;
  94325. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  94326. this.motorImpulse1 = -this.maxMotorImpulse1;
  94327. }
  94328. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  94329. }
  94330. if (this.enableMotor2) {
  94331. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  94332. this.motorImpulse2 += dMotorImpulse2;
  94333. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  94334. this.motorImpulse2 = this.maxMotorImpulse2;
  94335. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  94336. this.motorImpulse2 = -this.maxMotorImpulse2;
  94337. }
  94338. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  94339. }
  94340. if (this.enableMotor3) {
  94341. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  94342. this.motorImpulse3 += dMotorImpulse3;
  94343. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  94344. this.motorImpulse3 = this.maxMotorImpulse3;
  94345. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  94346. this.motorImpulse3 = -this.maxMotorImpulse3;
  94347. }
  94348. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  94349. }
  94350. // apply motor impulse to relative velocity
  94351. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  94352. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  94353. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  94354. // subtract target velocity and applied impulse
  94355. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  94356. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  94357. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  94358. var oldLimitImpulse1 = this.limitImpulse1;
  94359. var oldLimitImpulse2 = this.limitImpulse2;
  94360. var oldLimitImpulse3 = this.limitImpulse3;
  94361. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  94362. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  94363. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  94364. this.limitImpulse1 += dLimitImpulse1;
  94365. this.limitImpulse2 += dLimitImpulse2;
  94366. this.limitImpulse3 += dLimitImpulse3;
  94367. // clamp
  94368. var clampState = 0;
  94369. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  94370. dLimitImpulse1 = -oldLimitImpulse1;
  94371. rvn2 += dLimitImpulse1 * this.k10;
  94372. rvn3 += dLimitImpulse1 * this.k20;
  94373. clampState |= 1;
  94374. }
  94375. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  94376. dLimitImpulse2 = -oldLimitImpulse2;
  94377. rvn1 += dLimitImpulse2 * this.k01;
  94378. rvn3 += dLimitImpulse2 * this.k21;
  94379. clampState |= 2;
  94380. }
  94381. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  94382. dLimitImpulse3 = -oldLimitImpulse3;
  94383. rvn1 += dLimitImpulse3 * this.k02;
  94384. rvn2 += dLimitImpulse3 * this.k12;
  94385. clampState |= 4;
  94386. }
  94387. // update un-clamped impulse
  94388. // TODO: isolate division
  94389. var det;
  94390. switch (clampState) {
  94391. case 1:// update 2 3
  94392. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  94393. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  94394. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  94395. break;
  94396. case 2:// update 1 3
  94397. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  94398. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  94399. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  94400. break;
  94401. case 3:// update 3
  94402. dLimitImpulse3 = rvn3 / this.k22;
  94403. break;
  94404. case 4:// update 1 2
  94405. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  94406. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  94407. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  94408. break;
  94409. case 5:// update 2
  94410. dLimitImpulse2 = rvn2 / this.k11;
  94411. break;
  94412. case 6:// update 1
  94413. dLimitImpulse1 = rvn1 / this.k00;
  94414. break;
  94415. }
  94416. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  94417. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  94418. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  94419. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  94420. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  94421. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  94422. // apply impulse
  94423. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  94424. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  94425. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  94426. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  94427. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  94428. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  94429. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  94430. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  94431. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  94432. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  94433. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  94434. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  94435. }
  94436. }
  94437. /**
  94438. * A translational constraint for various joints.
  94439. * @author saharan
  94440. */
  94441. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  94442. this.cfm = NaN;
  94443. this.m1 = NaN;
  94444. this.m2 = NaN;
  94445. this.i1e00 = NaN;
  94446. this.i1e01 = NaN;
  94447. this.i1e02 = NaN;
  94448. this.i1e10 = NaN;
  94449. this.i1e11 = NaN;
  94450. this.i1e12 = NaN;
  94451. this.i1e20 = NaN;
  94452. this.i1e21 = NaN;
  94453. this.i1e22 = NaN;
  94454. this.i2e00 = NaN;
  94455. this.i2e01 = NaN;
  94456. this.i2e02 = NaN;
  94457. this.i2e10 = NaN;
  94458. this.i2e11 = NaN;
  94459. this.i2e12 = NaN;
  94460. this.i2e20 = NaN;
  94461. this.i2e21 = NaN;
  94462. this.i2e22 = NaN;
  94463. this.motorDenom = NaN;
  94464. this.invMotorDenom = NaN;
  94465. this.invDenom = NaN;
  94466. this.ax = NaN;
  94467. this.ay = NaN;
  94468. this.az = NaN;
  94469. this.r1x = NaN;
  94470. this.r1y = NaN;
  94471. this.r1z = NaN;
  94472. this.r2x = NaN;
  94473. this.r2y = NaN;
  94474. this.r2z = NaN;
  94475. this.t1x = NaN;
  94476. this.t1y = NaN;
  94477. this.t1z = NaN;
  94478. this.t2x = NaN;
  94479. this.t2y = NaN;
  94480. this.t2z = NaN;
  94481. this.l1x = NaN;
  94482. this.l1y = NaN;
  94483. this.l1z = NaN;
  94484. this.l2x = NaN;
  94485. this.l2y = NaN;
  94486. this.l2z = NaN;
  94487. this.a1x = NaN;
  94488. this.a1y = NaN;
  94489. this.a1z = NaN;
  94490. this.a2x = NaN;
  94491. this.a2y = NaN;
  94492. this.a2z = NaN;
  94493. this.lowerLimit = NaN;
  94494. this.upperLimit = NaN;
  94495. this.limitVelocity = NaN;
  94496. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  94497. this.enableMotor = false;
  94498. this.motorSpeed = NaN;
  94499. this.maxMotorForce = NaN;
  94500. this.maxMotorImpulse = NaN;
  94501. this.limitMotor = limitMotor;
  94502. this.b1 = joint.body1;
  94503. this.b2 = joint.body2;
  94504. this.p1 = joint.anchorPoint1;
  94505. this.p2 = joint.anchorPoint2;
  94506. this.r1 = joint.relativeAnchorPoint1;
  94507. this.r2 = joint.relativeAnchorPoint2;
  94508. this.l1 = this.b1.linearVelocity;
  94509. this.l2 = this.b2.linearVelocity;
  94510. this.a1 = this.b1.angularVelocity;
  94511. this.a2 = this.b2.angularVelocity;
  94512. this.i1 = this.b1.inverseInertia;
  94513. this.i2 = this.b2.inverseInertia;
  94514. this.limitImpulse = 0;
  94515. this.motorImpulse = 0;
  94516. }
  94517. OIMO.TranslationalConstraint.prototype = {
  94518. constructor: OIMO.TranslationalConstraint,
  94519. preSolve: function (timeStep, invTimeStep) {
  94520. this.ax = this.limitMotor.axis.x;
  94521. this.ay = this.limitMotor.axis.y;
  94522. this.az = this.limitMotor.axis.z;
  94523. this.lowerLimit = this.limitMotor.lowerLimit;
  94524. this.upperLimit = this.limitMotor.upperLimit;
  94525. this.motorSpeed = this.limitMotor.motorSpeed;
  94526. this.maxMotorForce = this.limitMotor.maxMotorForce;
  94527. this.enableMotor = this.maxMotorForce > 0;
  94528. this.m1 = this.b1.inverseMass;
  94529. this.m2 = this.b2.inverseMass;
  94530. var ti1 = this.i1.elements;
  94531. var ti2 = this.i2.elements;
  94532. this.i1e00 = ti1[0];
  94533. this.i1e01 = ti1[1];
  94534. this.i1e02 = ti1[2];
  94535. this.i1e10 = ti1[3];
  94536. this.i1e11 = ti1[4];
  94537. this.i1e12 = ti1[5];
  94538. this.i1e20 = ti1[6];
  94539. this.i1e21 = ti1[7];
  94540. this.i1e22 = ti1[8];
  94541. this.i2e00 = ti2[0];
  94542. this.i2e01 = ti2[1];
  94543. this.i2e02 = ti2[2];
  94544. this.i2e10 = ti2[3];
  94545. this.i2e11 = ti2[4];
  94546. this.i2e12 = ti2[5];
  94547. this.i2e20 = ti2[6];
  94548. this.i2e21 = ti2[7];
  94549. this.i2e22 = ti2[8];
  94550. var dx = this.p2.x - this.p1.x;
  94551. var dy = this.p2.y - this.p1.y;
  94552. var dz = this.p2.z - this.p1.z;
  94553. var d = dx * this.ax + dy * this.ay + dz * this.az;
  94554. var frequency = this.limitMotor.frequency;
  94555. var enableSpring = frequency > 0;
  94556. var enableLimit = this.lowerLimit <= this.upperLimit;
  94557. if (enableSpring && d > 20 || d < -20) {
  94558. enableSpring = false;
  94559. }
  94560. if (enableLimit) {
  94561. if (this.lowerLimit == this.upperLimit) {
  94562. if (this.limitState != 0) {
  94563. this.limitState = 0;
  94564. this.limitImpulse = 0;
  94565. }
  94566. this.limitVelocity = this.lowerLimit - d;
  94567. if (!enableSpring) d = this.lowerLimit;
  94568. } else if (d < this.lowerLimit) {
  94569. if (this.limitState != -1) {
  94570. this.limitState = -1;
  94571. this.limitImpulse = 0;
  94572. }
  94573. this.limitVelocity = this.lowerLimit - d;
  94574. if (!enableSpring) d = this.lowerLimit;
  94575. } else if (d > this.upperLimit) {
  94576. if (this.limitState != 1) {
  94577. this.limitState = 1;
  94578. this.limitImpulse = 0;
  94579. }
  94580. this.limitVelocity = this.upperLimit - d;
  94581. if (!enableSpring) d = this.upperLimit;
  94582. } else {
  94583. this.limitState = 2;
  94584. this.limitImpulse = 0;
  94585. this.limitVelocity = 0;
  94586. }
  94587. if (!enableSpring) {
  94588. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  94589. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  94590. else this.limitVelocity = 0;
  94591. }
  94592. } else {
  94593. this.limitState = 2;
  94594. this.limitImpulse = 0;
  94595. }
  94596. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  94597. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  94598. } else {
  94599. this.motorImpulse = 0;
  94600. this.maxMotorImpulse = 0;
  94601. }
  94602. var rdx = d * this.ax;
  94603. var rdy = d * this.ay;
  94604. var rdz = d * this.az;
  94605. var w1 = this.m1 / (this.m1 + this.m2);
  94606. var w2 = 1 - w1;
  94607. this.r1x = this.r1.x + rdx * w1;
  94608. this.r1y = this.r1.y + rdy * w1;
  94609. this.r1z = this.r1.z + rdz * w1;
  94610. this.r2x = this.r2.x - rdx * w2;
  94611. this.r2y = this.r2.y - rdy * w2;
  94612. this.r2z = this.r2.z - rdz * w2;
  94613. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  94614. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  94615. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  94616. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  94617. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  94618. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  94619. this.l1x = this.ax * this.m1;
  94620. this.l1y = this.ay * this.m1;
  94621. this.l1z = this.az * this.m1;
  94622. this.l2x = this.ax * this.m2;
  94623. this.l2y = this.ay * this.m2;
  94624. this.l2z = this.az * this.m2;
  94625. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  94626. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  94627. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  94628. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  94629. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  94630. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  94631. this.motorDenom =
  94632. this.m1 + this.m2 +
  94633. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  94634. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  94635. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  94636. this.invMotorDenom = 1 / this.motorDenom;
  94637. if (enableSpring && this.limitState != 2) {
  94638. var omega = 6.2831853 * frequency;
  94639. var k = omega * omega * timeStep;
  94640. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  94641. this.cfm = this.motorDenom * dmp;
  94642. this.limitVelocity *= k * dmp;
  94643. } else {
  94644. this.cfm = 0;
  94645. this.limitVelocity *= invTimeStep * 0.05;
  94646. }
  94647. this.invDenom = 1 / (this.motorDenom + this.cfm);
  94648. var totalImpulse = this.limitImpulse + this.motorImpulse;
  94649. this.l1.x += totalImpulse * this.l1x;
  94650. this.l1.y += totalImpulse * this.l1y;
  94651. this.l1.z += totalImpulse * this.l1z;
  94652. this.a1.x += totalImpulse * this.a1x;
  94653. this.a1.y += totalImpulse * this.a1y;
  94654. this.a1.z += totalImpulse * this.a1z;
  94655. this.l2.x -= totalImpulse * this.l2x;
  94656. this.l2.y -= totalImpulse * this.l2y;
  94657. this.l2.z -= totalImpulse * this.l2z;
  94658. this.a2.x -= totalImpulse * this.a2x;
  94659. this.a2.y -= totalImpulse * this.a2y;
  94660. this.a2.z -= totalImpulse * this.a2z;
  94661. },
  94662. solve: function () {
  94663. var rvn =
  94664. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  94665. 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;
  94666. // motor part
  94667. var newMotorImpulse;
  94668. if (this.enableMotor) {
  94669. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  94670. var oldMotorImpulse = this.motorImpulse;
  94671. this.motorImpulse += newMotorImpulse;
  94672. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  94673. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  94674. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  94675. rvn -= newMotorImpulse * this.motorDenom;
  94676. } else newMotorImpulse = 0;
  94677. // limit part
  94678. var newLimitImpulse;
  94679. if (this.limitState != 2) {
  94680. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  94681. var oldLimitImpulse = this.limitImpulse;
  94682. this.limitImpulse += newLimitImpulse;
  94683. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  94684. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  94685. } else newLimitImpulse = 0;
  94686. var totalImpulse = newLimitImpulse + newMotorImpulse;
  94687. this.l1.x += totalImpulse * this.l1x;
  94688. this.l1.y += totalImpulse * this.l1y;
  94689. this.l1.z += totalImpulse * this.l1z;
  94690. this.a1.x += totalImpulse * this.a1x;
  94691. this.a1.y += totalImpulse * this.a1y;
  94692. this.a1.z += totalImpulse * this.a1z;
  94693. this.l2.x -= totalImpulse * this.l2x;
  94694. this.l2.y -= totalImpulse * this.l2y;
  94695. this.l2.z -= totalImpulse * this.l2z;
  94696. this.a2.x -= totalImpulse * this.a2x;
  94697. this.a2.y -= totalImpulse * this.a2y;
  94698. this.a2.z -= totalImpulse * this.a2z;
  94699. }
  94700. }
  94701. /**
  94702. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  94703. * @author saharan
  94704. */
  94705. OIMO.Contact = function () {
  94706. // The first shape.
  94707. this.shape1 = null;
  94708. // The second shape.
  94709. this.shape2 = null;
  94710. // The first rigid body.
  94711. this.body1 = null;
  94712. // The second rigid body.
  94713. this.body2 = null;
  94714. // The previous contact in the world.
  94715. this.prev = null;
  94716. // The next contact in the world.
  94717. this.next = null;
  94718. // Internal
  94719. this.persisting = false;
  94720. // Whether both the rigid bodies are sleeping or not.
  94721. this.sleeping = false;
  94722. // The collision detector between two shapes.
  94723. this.detector = null;
  94724. // The contact constraint of the contact.
  94725. this.constraint = null;
  94726. // Whether the shapes are touching or not.
  94727. this.touching = false;
  94728. this.b1Link = new OIMO.ContactLink(this);
  94729. this.b2Link = new OIMO.ContactLink(this);
  94730. this.s1Link = new OIMO.ContactLink(this);
  94731. this.s2Link = new OIMO.ContactLink(this);
  94732. // The contact manifold of the contact.
  94733. this.manifold = new OIMO.ContactManifold();
  94734. this.buffer = [];// vector 4
  94735. this.buffer.length = 4;
  94736. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  94737. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  94738. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  94739. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  94740. this.points = this.manifold.points;
  94741. this.constraint = new OIMO.ContactConstraint(this.manifold);
  94742. }
  94743. OIMO.Contact.prototype = {
  94744. constructor: OIMO.Contact,
  94745. mixRestitution: function (restitution1, restitution2) {
  94746. return OIMO.sqrt(restitution1 * restitution2);
  94747. },
  94748. mixFriction: function (friction1, friction2) {
  94749. return OIMO.sqrt(friction1 * friction2);
  94750. },
  94751. /**
  94752. * Update the contact manifold.
  94753. */
  94754. updateManifold: function () {
  94755. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  94756. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  94757. var numBuffers = this.manifold.numPoints;
  94758. var i = numBuffers;
  94759. while (i--) {
  94760. //for(var i=0;i<numBuffers;i++){
  94761. var b = this.buffer[i];
  94762. var p = this.points[i];
  94763. b.lp1X = p.localPoint1.x;
  94764. b.lp1Y = p.localPoint1.y;
  94765. b.lp1Z = p.localPoint1.z;
  94766. b.lp2X = p.localPoint2.x;
  94767. b.lp2Y = p.localPoint2.y;
  94768. b.lp2Z = p.localPoint2.z;
  94769. b.impulse = p.normalImpulse;
  94770. }
  94771. this.manifold.numPoints = 0;
  94772. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  94773. var num = this.manifold.numPoints;
  94774. if (num == 0) {
  94775. this.touching = false;
  94776. return;
  94777. }
  94778. this.touching = true;
  94779. i = num;
  94780. while (i--) {
  94781. //for(i=0; i<num; i++){
  94782. p = this.points[i];
  94783. var lp1x = p.localPoint1.x;
  94784. var lp1y = p.localPoint1.y;
  94785. var lp1z = p.localPoint1.z;
  94786. var lp2x = p.localPoint2.x;
  94787. var lp2y = p.localPoint2.y;
  94788. var lp2z = p.localPoint2.z;
  94789. var index = -1;
  94790. var minDistance = 0.0004;
  94791. var j = numBuffers;
  94792. while (j--) {
  94793. //for(var j=0;j<numBuffers;j++){
  94794. b = this.buffer[j];
  94795. var dx = b.lp1X - lp1x;
  94796. var dy = b.lp1Y - lp1y;
  94797. var dz = b.lp1Z - lp1z;
  94798. var distance1 = dx * dx + dy * dy + dz * dz;
  94799. dx = b.lp2X - lp2x;
  94800. dy = b.lp2Y - lp2y;
  94801. dz = b.lp2Z - lp2z;
  94802. var distance2 = dx * dx + dy * dy + dz * dz;
  94803. if (distance1 < distance2) {
  94804. if (distance1 < minDistance) {
  94805. minDistance = distance1;
  94806. index = j;
  94807. }
  94808. } else {
  94809. if (distance2 < minDistance) {
  94810. minDistance = distance2;
  94811. index = j;
  94812. }
  94813. }
  94814. }
  94815. if (index != -1) {
  94816. var tmp = this.buffer[index];
  94817. this.buffer[index] = this.buffer[--numBuffers];
  94818. this.buffer[numBuffers] = tmp;
  94819. p.normalImpulse = tmp.impulse;
  94820. p.warmStarted = true;
  94821. } else {
  94822. p.normalImpulse = 0;
  94823. p.warmStarted = false;
  94824. }
  94825. }
  94826. },
  94827. /**
  94828. * Attach the contact to the shapes.
  94829. * @param shape1
  94830. * @param shape2
  94831. */
  94832. attach: function (shape1, shape2) {
  94833. this.shape1 = shape1;
  94834. this.shape2 = shape2;
  94835. this.body1 = shape1.parent;
  94836. this.body2 = shape2.parent;
  94837. this.manifold.body1 = this.body1;
  94838. this.manifold.body2 = this.body2;
  94839. this.constraint.body1 = this.body1;
  94840. this.constraint.body2 = this.body2;
  94841. this.constraint.attach();
  94842. this.s1Link.shape = shape2;
  94843. this.s1Link.body = this.body2;
  94844. this.s2Link.shape = shape1;
  94845. this.s2Link.body = this.body1;
  94846. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  94847. else this.s1Link.next = null;
  94848. shape1.contactLink = this.s1Link;
  94849. shape1.numContacts++;
  94850. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  94851. else this.s2Link.next = null;
  94852. shape2.contactLink = this.s2Link;
  94853. shape2.numContacts++;
  94854. this.b1Link.shape = shape2;
  94855. this.b1Link.body = this.body2;
  94856. this.b2Link.shape = shape1;
  94857. this.b2Link.body = this.body1;
  94858. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  94859. else this.b1Link.next = null;
  94860. this.body1.contactLink = this.b1Link;
  94861. this.body1.numContacts++;
  94862. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  94863. else this.b2Link.next = null;
  94864. this.body2.contactLink = this.b2Link;
  94865. this.body2.numContacts++;
  94866. this.prev = null;
  94867. this.next = null;
  94868. this.persisting = true;
  94869. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  94870. this.manifold.numPoints = 0;
  94871. },
  94872. /**
  94873. * Detach the contact from the shapes.
  94874. */
  94875. detach: function () {
  94876. var prev = this.s1Link.prev;
  94877. var next = this.s1Link.next;
  94878. if (prev !== null) prev.next = next;
  94879. if (next !== null) next.prev = prev;
  94880. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  94881. this.s1Link.prev = null;
  94882. this.s1Link.next = null;
  94883. this.s1Link.shape = null;
  94884. this.s1Link.body = null;
  94885. this.shape1.numContacts--;
  94886. prev = this.s2Link.prev;
  94887. next = this.s2Link.next;
  94888. if (prev !== null) prev.next = next;
  94889. if (next !== null) next.prev = prev;
  94890. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  94891. this.s2Link.prev = null;
  94892. this.s2Link.next = null;
  94893. this.s2Link.shape = null;
  94894. this.s2Link.body = null;
  94895. this.shape2.numContacts--;
  94896. prev = this.b1Link.prev;
  94897. next = this.b1Link.next;
  94898. if (prev !== null) prev.next = next;
  94899. if (next !== null) next.prev = prev;
  94900. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  94901. this.b1Link.prev = null;
  94902. this.b1Link.next = null;
  94903. this.b1Link.shape = null;
  94904. this.b1Link.body = null;
  94905. this.body1.numContacts--;
  94906. prev = this.b2Link.prev;
  94907. next = this.b2Link.next;
  94908. if (prev !== null) prev.next = next;
  94909. if (next !== null) next.prev = prev;
  94910. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  94911. this.b2Link.prev = null;
  94912. this.b2Link.next = null;
  94913. this.b2Link.shape = null;
  94914. this.b2Link.body = null;
  94915. this.body2.numContacts--;
  94916. this.manifold.body1 = null;
  94917. this.manifold.body2 = null;
  94918. this.constraint.body1 = null;
  94919. this.constraint.body2 = null;
  94920. this.constraint.detach();
  94921. this.shape1 = null;
  94922. this.shape2 = null;
  94923. this.body1 = null;
  94924. this.body2 = null;
  94925. }
  94926. }
  94927. /**
  94928. * ...
  94929. * @author saharan
  94930. */
  94931. OIMO.ContactConstraint = function (manifold) {
  94932. OIMO.Constraint.call(this);
  94933. // The contact manifold of the constraint.
  94934. this.manifold = manifold;
  94935. // The coefficient of restitution of the constraint.
  94936. this.restitution = NaN;
  94937. // The coefficient of friction of the constraint.
  94938. this.friction = NaN;
  94939. this.p1 = null;
  94940. this.p2 = null;
  94941. this.lv1 = null;
  94942. this.lv2 = null;
  94943. this.av1 = null;
  94944. this.av2 = null;
  94945. this.i1 = null;
  94946. this.i2 = null;
  94947. this.ii1 = null;
  94948. this.ii2 = null;
  94949. this.m1 = NaN;
  94950. this.m2 = NaN;
  94951. this.num = 0;
  94952. this.ps = manifold.points;
  94953. this.cs = new OIMO.ContactPointDataBuffer();
  94954. this.cs.next = new OIMO.ContactPointDataBuffer();
  94955. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  94956. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  94957. }
  94958. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  94959. /**
  94960. * Attach the constraint to the bodies.
  94961. */
  94962. OIMO.ContactConstraint.prototype.attach = function () {
  94963. this.p1 = this.body1.position;
  94964. this.p2 = this.body2.position;
  94965. this.lv1 = this.body1.linearVelocity;
  94966. this.av1 = this.body1.angularVelocity;
  94967. this.lv2 = this.body2.linearVelocity;
  94968. this.av2 = this.body2.angularVelocity;
  94969. this.i1 = this.body1.inverseInertia;
  94970. this.i2 = this.body2.inverseInertia;
  94971. }
  94972. /**
  94973. * Detach the constraint from the bodies.
  94974. */
  94975. OIMO.ContactConstraint.prototype.detach = function () {
  94976. this.p1 = null;
  94977. this.p2 = null;
  94978. this.lv1 = null;
  94979. this.lv2 = null;
  94980. this.av1 = null;
  94981. this.av2 = null;
  94982. this.i1 = null;
  94983. this.i2 = null;
  94984. }
  94985. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  94986. this.m1 = this.body1.inverseMass;
  94987. this.m2 = this.body2.inverseMass;
  94988. this.ii1 = this.i1.clone();
  94989. this.ii2 = this.i2.clone();
  94990. var ii1 = this.ii1.elements;
  94991. var ii2 = this.ii2.elements;
  94992. var p1x = this.p1.x;
  94993. var p1y = this.p1.y;
  94994. var p1z = this.p1.z;
  94995. var p2x = this.p2.x;
  94996. var p2y = this.p2.y;
  94997. var p2z = this.p2.z;
  94998. var m1m2 = this.m1 + this.m2;
  94999. this.num = this.manifold.numPoints;
  95000. var c = this.cs;
  95001. for (var i = 0; i < this.num; i++) {
  95002. var p = this.ps[i];
  95003. var tmp1X;
  95004. var tmp1Y;
  95005. var tmp1Z;
  95006. var tmp2X;
  95007. var tmp2Y;
  95008. var tmp2Z;
  95009. tmp1X = p.position.x;
  95010. tmp1Y = p.position.y;
  95011. tmp1Z = p.position.z;
  95012. var rp1X = tmp1X - p1x;
  95013. var rp1Y = tmp1Y - p1y;
  95014. var rp1Z = tmp1Z - p1z;
  95015. var rp2X = tmp1X - p2x;
  95016. var rp2Y = tmp1Y - p2y;
  95017. var rp2Z = tmp1Z - p2z;
  95018. c.rp1X = rp1X;
  95019. c.rp1Y = rp1Y;
  95020. c.rp1Z = rp1Z;
  95021. c.rp2X = rp2X;
  95022. c.rp2Y = rp2Y;
  95023. c.rp2Z = rp2Z;
  95024. c.norImp = p.normalImpulse;
  95025. c.tanImp = p.tangentImpulse;
  95026. c.binImp = p.binormalImpulse;
  95027. var norX = p.normal.x;
  95028. var norY = p.normal.y;
  95029. var norZ = p.normal.z;
  95030. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  95031. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  95032. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  95033. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  95034. var tanX = rvX - rvn * norX;
  95035. var tanY = rvY - rvn * norY;
  95036. var tanZ = rvZ - rvn * norZ;
  95037. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  95038. if (len > 0.04) {
  95039. len = 1 / OIMO.sqrt(len);
  95040. } else {
  95041. tanX = norY * norX - norZ * norZ;
  95042. tanY = -norZ * norY - norX * norX;
  95043. tanZ = norX * norZ + norY * norY;
  95044. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  95045. }
  95046. tanX *= len;
  95047. tanY *= len;
  95048. tanZ *= len;
  95049. var binX = norY * tanZ - norZ * tanY;
  95050. var binY = norZ * tanX - norX * tanZ;
  95051. var binZ = norX * tanY - norY * tanX;
  95052. c.norX = norX;
  95053. c.norY = norY;
  95054. c.norZ = norZ;
  95055. c.tanX = tanX;
  95056. c.tanY = tanY;
  95057. c.tanZ = tanZ;
  95058. c.binX = binX;
  95059. c.binY = binY;
  95060. c.binZ = binZ;
  95061. c.norU1X = norX * this.m1;
  95062. c.norU1Y = norY * this.m1;
  95063. c.norU1Z = norZ * this.m1;
  95064. c.norU2X = norX * this.m2;
  95065. c.norU2Y = norY * this.m2;
  95066. c.norU2Z = norZ * this.m2;
  95067. c.tanU1X = tanX * this.m1;
  95068. c.tanU1Y = tanY * this.m1;
  95069. c.tanU1Z = tanZ * this.m1;
  95070. c.tanU2X = tanX * this.m2;
  95071. c.tanU2Y = tanY * this.m2;
  95072. c.tanU2Z = tanZ * this.m2;
  95073. c.binU1X = binX * this.m1;
  95074. c.binU1Y = binY * this.m1;
  95075. c.binU1Z = binZ * this.m1;
  95076. c.binU2X = binX * this.m2;
  95077. c.binU2Y = binY * this.m2;
  95078. c.binU2Z = binZ * this.m2;
  95079. var norT1X = rp1Y * norZ - rp1Z * norY;
  95080. var norT1Y = rp1Z * norX - rp1X * norZ;
  95081. var norT1Z = rp1X * norY - rp1Y * norX;
  95082. var norT2X = rp2Y * norZ - rp2Z * norY;
  95083. var norT2Y = rp2Z * norX - rp2X * norZ;
  95084. var norT2Z = rp2X * norY - rp2Y * norX;
  95085. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  95086. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  95087. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  95088. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  95089. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  95090. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  95091. var binT1X = rp1Y * binZ - rp1Z * binY;
  95092. var binT1Y = rp1Z * binX - rp1X * binZ;
  95093. var binT1Z = rp1X * binY - rp1Y * binX;
  95094. var binT2X = rp2Y * binZ - rp2Z * binY;
  95095. var binT2Y = rp2Z * binX - rp2X * binZ;
  95096. var binT2Z = rp2X * binY - rp2Y * binX;
  95097. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  95098. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  95099. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  95100. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  95101. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  95102. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  95103. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  95104. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  95105. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  95106. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  95107. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  95108. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  95109. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  95110. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  95111. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  95112. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  95113. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  95114. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  95115. c.norT1X = norT1X;
  95116. c.norT1Y = norT1Y;
  95117. c.norT1Z = norT1Z;
  95118. c.tanT1X = tanT1X;
  95119. c.tanT1Y = tanT1Y;
  95120. c.tanT1Z = tanT1Z;
  95121. c.binT1X = binT1X;
  95122. c.binT1Y = binT1Y;
  95123. c.binT1Z = binT1Z;
  95124. c.norT2X = norT2X;
  95125. c.norT2Y = norT2Y;
  95126. c.norT2Z = norT2Z;
  95127. c.tanT2X = tanT2X;
  95128. c.tanT2Y = tanT2Y;
  95129. c.tanT2Z = tanT2Z;
  95130. c.binT2X = binT2X;
  95131. c.binT2Y = binT2Y;
  95132. c.binT2Z = binT2Z;
  95133. c.norTU1X = norTU1X;
  95134. c.norTU1Y = norTU1Y;
  95135. c.norTU1Z = norTU1Z;
  95136. c.tanTU1X = tanTU1X;
  95137. c.tanTU1Y = tanTU1Y;
  95138. c.tanTU1Z = tanTU1Z;
  95139. c.binTU1X = binTU1X;
  95140. c.binTU1Y = binTU1Y;
  95141. c.binTU1Z = binTU1Z;
  95142. c.norTU2X = norTU2X;
  95143. c.norTU2Y = norTU2Y;
  95144. c.norTU2Z = norTU2Z;
  95145. c.tanTU2X = tanTU2X;
  95146. c.tanTU2Y = tanTU2Y;
  95147. c.tanTU2Z = tanTU2Z;
  95148. c.binTU2X = binTU2X;
  95149. c.binTU2Y = binTU2Y;
  95150. c.binTU2Z = binTU2Z;
  95151. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  95152. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  95153. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  95154. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  95155. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  95156. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  95157. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  95158. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  95159. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  95160. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  95161. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  95162. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  95163. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  95164. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  95165. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  95166. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  95167. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  95168. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  95169. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  95170. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  95171. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  95172. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  95173. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  95174. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  95175. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  95176. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  95177. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  95178. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  95179. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  95180. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  95181. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  95182. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  95183. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  95184. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  95185. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  95186. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  95187. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  95188. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  95189. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  95190. c.norDen = norDen;
  95191. c.tanDen = tanDen;
  95192. c.binDen = binDen;
  95193. if (p.warmStarted) {
  95194. var norImp = p.normalImpulse;
  95195. this.lv1.x += c.norU1X * norImp;
  95196. this.lv1.y += c.norU1Y * norImp;
  95197. this.lv1.z += c.norU1Z * norImp;
  95198. this.av1.x += norTU1X * norImp;
  95199. this.av1.y += norTU1Y * norImp;
  95200. this.av1.z += norTU1Z * norImp;
  95201. this.lv2.x -= c.norU2X * norImp;
  95202. this.lv2.y -= c.norU2Y * norImp;
  95203. this.lv2.z -= c.norU2Z * norImp;
  95204. this.av2.x -= norTU2X * norImp;
  95205. this.av2.y -= norTU2Y * norImp;
  95206. this.av2.z -= norTU2Z * norImp;
  95207. c.norImp = norImp;
  95208. c.tanImp = 0;
  95209. c.binImp = 0;
  95210. rvn = 0; // disable bouncing
  95211. } else {
  95212. c.norImp = 0;
  95213. c.tanImp = 0;
  95214. c.binImp = 0;
  95215. }
  95216. if (rvn > -1) {
  95217. rvn = 0; // disable bouncing
  95218. }
  95219. var norTar = this.restitution * -rvn;
  95220. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  95221. if (norTar < sepV) norTar = sepV;
  95222. c.norTar = norTar;
  95223. c.last = i == this.num - 1;
  95224. c = c.next;
  95225. }
  95226. }
  95227. OIMO.ContactConstraint.prototype.solve = function () {
  95228. var lv1x = this.lv1.x;
  95229. var lv1y = this.lv1.y;
  95230. var lv1z = this.lv1.z;
  95231. var lv2x = this.lv2.x;
  95232. var lv2y = this.lv2.y;
  95233. var lv2z = this.lv2.z;
  95234. var av1x = this.av1.x;
  95235. var av1y = this.av1.y;
  95236. var av1z = this.av1.z;
  95237. var av2x = this.av2.x;
  95238. var av2y = this.av2.y;
  95239. var av2z = this.av2.z;
  95240. var c = this.cs;
  95241. while (true) {
  95242. var oldImp1;
  95243. var newImp1;
  95244. var oldImp2;
  95245. var newImp2;
  95246. var rvn;
  95247. var norImp = c.norImp;
  95248. var tanImp = c.tanImp;
  95249. var binImp = c.binImp;
  95250. var max = -norImp * this.friction;
  95251. var rvX = lv2x - lv1x;
  95252. var rvY = lv2y - lv1y;
  95253. var rvZ = lv2z - lv1z;
  95254. rvn =
  95255. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  95256. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  95257. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  95258. ;
  95259. oldImp1 = tanImp;
  95260. newImp1 = rvn * c.tanDen;
  95261. tanImp += newImp1;
  95262. rvn =
  95263. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  95264. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  95265. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  95266. ;
  95267. oldImp2 = binImp;
  95268. newImp2 = rvn * c.binDen;
  95269. binImp += newImp2;
  95270. // cone friction clamp
  95271. var len = tanImp * tanImp + binImp * binImp;
  95272. if (len > max * max) {
  95273. len = max / OIMO.sqrt(len);
  95274. tanImp *= len;
  95275. binImp *= len;
  95276. }
  95277. newImp1 = tanImp - oldImp1;
  95278. newImp2 = binImp - oldImp2;
  95279. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  95280. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  95281. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  95282. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  95283. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  95284. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  95285. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  95286. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  95287. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  95288. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  95289. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  95290. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  95291. // restitution part
  95292. rvn =
  95293. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  95294. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  95295. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  95296. oldImp1 = norImp;
  95297. newImp1 = (rvn - c.norTar) * c.norDen;
  95298. norImp += newImp1;
  95299. if (norImp > 0) norImp = 0;
  95300. newImp1 = norImp - oldImp1;
  95301. lv1x += c.norU1X * newImp1;
  95302. lv1y += c.norU1Y * newImp1;
  95303. lv1z += c.norU1Z * newImp1;
  95304. av1x += c.norTU1X * newImp1;
  95305. av1y += c.norTU1Y * newImp1;
  95306. av1z += c.norTU1Z * newImp1;
  95307. lv2x -= c.norU2X * newImp1;
  95308. lv2y -= c.norU2Y * newImp1;
  95309. lv2z -= c.norU2Z * newImp1;
  95310. av2x -= c.norTU2X * newImp1;
  95311. av2y -= c.norTU2Y * newImp1;
  95312. av2z -= c.norTU2Z * newImp1;
  95313. c.norImp = norImp;
  95314. c.tanImp = tanImp;
  95315. c.binImp = binImp;
  95316. if (c.last) break;
  95317. c = c.next;
  95318. }
  95319. this.lv1.x = lv1x;
  95320. this.lv1.y = lv1y;
  95321. this.lv1.z = lv1z;
  95322. this.lv2.x = lv2x;
  95323. this.lv2.y = lv2y;
  95324. this.lv2.z = lv2z;
  95325. this.av1.x = av1x;
  95326. this.av1.y = av1y;
  95327. this.av1.z = av1z;
  95328. this.av2.x = av2x;
  95329. this.av2.y = av2y;
  95330. this.av2.z = av2z;
  95331. }
  95332. OIMO.ContactConstraint.prototype.postSolve = function () {
  95333. var c = this.cs;
  95334. var i = this.num;
  95335. while (i--) {
  95336. //for(var i=0;i<this.num;i++){
  95337. var p = this.ps[i];
  95338. p.normal.x = c.norX;
  95339. p.normal.y = c.norY;
  95340. p.normal.z = c.norZ;
  95341. p.tangent.x = c.tanX;
  95342. p.tangent.y = c.tanY;
  95343. p.tangent.z = c.tanZ;
  95344. p.binormal.x = c.binX;
  95345. p.binormal.y = c.binY;
  95346. p.binormal.z = c.binZ;
  95347. p.normalImpulse = c.norImp;
  95348. p.tangentImpulse = c.tanImp;
  95349. p.binormalImpulse = c.binImp;
  95350. p.normalDenominator = c.norDen;
  95351. p.tangentDenominator = c.tanDen;
  95352. p.binormalDenominator = c.binDen;
  95353. c = c.next;
  95354. }
  95355. }
  95356. /**
  95357. * A link list of contacts.
  95358. * @author saharan
  95359. */
  95360. OIMO.ContactLink = function (contact) {
  95361. // The previous contact link.
  95362. this.prev = null;
  95363. // The next contact link.
  95364. this.next = null;
  95365. // The shape of the contact.
  95366. this.shape = null;
  95367. // The other rigid body.
  95368. this.body = null;
  95369. // The contact of the link.
  95370. this.contact = contact;
  95371. }
  95372. /**
  95373. * A contact manifold between two shapes.
  95374. * @author saharan
  95375. */
  95376. OIMO.ContactManifold = function () {
  95377. // The first rigid body.
  95378. this.body1 = null;
  95379. // The second rigid body.
  95380. this.body2 = null;
  95381. // The number of manifold points.
  95382. this.numPoints = 0;
  95383. // The manifold points.
  95384. this.points = [];
  95385. this.points.length = 4;
  95386. this.points[0] = new OIMO.ManifoldPoint();
  95387. this.points[1] = new OIMO.ManifoldPoint();
  95388. this.points[2] = new OIMO.ManifoldPoint();
  95389. this.points[3] = new OIMO.ManifoldPoint();
  95390. }
  95391. OIMO.ContactManifold.prototype = {
  95392. constructor: OIMO.ContactManifold,
  95393. /**
  95394. * Reset the manifold.
  95395. * @param shape1
  95396. * @param shape2
  95397. */
  95398. reset: function (shape1, shape2) {
  95399. this.body1 = shape1.parent;
  95400. this.body2 = shape2.parent;
  95401. this.numPoints = 0;
  95402. },
  95403. /**
  95404. * Add a point into this manifold.
  95405. * @param x
  95406. * @param y
  95407. * @param z
  95408. * @param normalX
  95409. * @param normalY
  95410. * @param normalZ
  95411. * @param penetration
  95412. * @param flip
  95413. */
  95414. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  95415. var p = this.points[this.numPoints++];
  95416. p.position.x = x;
  95417. p.position.y = y;
  95418. p.position.z = z;
  95419. var r = this.body1.rotation;
  95420. var rx = x - this.body1.position.x;
  95421. var ry = y - this.body1.position.y;
  95422. var rz = z - this.body1.position.z;
  95423. var tr = r.elements;
  95424. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  95425. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  95426. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  95427. r = this.body2.rotation;
  95428. rx = x - this.body2.position.x;
  95429. ry = y - this.body2.position.y;
  95430. rz = z - this.body2.position.z;
  95431. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  95432. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  95433. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  95434. p.normalImpulse = 0;
  95435. if (flip) {
  95436. p.normal.x = -normalX;
  95437. p.normal.y = -normalY;
  95438. p.normal.z = -normalZ;
  95439. } else {
  95440. p.normal.x = normalX;
  95441. p.normal.y = normalY;
  95442. p.normal.z = normalZ;
  95443. }
  95444. p.penetration = penetration;
  95445. p.warmStarted = false;
  95446. }
  95447. }
  95448. OIMO.ContactPointDataBuffer = function () {
  95449. this.norX = NaN;
  95450. this.norY = NaN;
  95451. this.norZ = NaN;
  95452. this.tanX = NaN;
  95453. this.tanY = NaN;
  95454. this.tanZ = NaN;
  95455. this.binX = NaN;
  95456. this.binY = NaN;
  95457. this.binZ = NaN;
  95458. this.rp1X = NaN;
  95459. this.rp1Y = NaN;
  95460. this.rp1Z = NaN;
  95461. this.rp2X = NaN;
  95462. this.rp2Y = NaN;
  95463. this.rp2Z = NaN;
  95464. this.norU1X = NaN;
  95465. this.norU1Y = NaN;
  95466. this.norU1Z = NaN;
  95467. this.norU2X = NaN;
  95468. this.norU2Y = NaN;
  95469. this.norU2Z = NaN;
  95470. this.tanU1X = NaN;
  95471. this.tanU1Y = NaN;
  95472. this.tanU1Z = NaN;
  95473. this.tanU2X = NaN;
  95474. this.tanU2Y = NaN;
  95475. this.tanU2Z = NaN;
  95476. this.binU1X = NaN;
  95477. this.binU1Y = NaN;
  95478. this.binU1Z = NaN;
  95479. this.binU2X = NaN;
  95480. this.binU2Y = NaN;
  95481. this.binU2Z = NaN;
  95482. this.norT1X = NaN;
  95483. this.norT1Y = NaN;
  95484. this.norT1Z = NaN;
  95485. this.norT2X = NaN;
  95486. this.norT2Y = NaN;
  95487. this.norT2Z = NaN;
  95488. this.tanT1X = NaN;
  95489. this.tanT1Y = NaN;
  95490. this.tanT1Z = NaN;
  95491. this.tanT2X = NaN;
  95492. this.tanT2Y = NaN;
  95493. this.tanT2Z = NaN;
  95494. this.binT1X = NaN;
  95495. this.binT1Y = NaN;
  95496. this.binT1Z = NaN;
  95497. this.binT2X = NaN;
  95498. this.binT2Y = NaN;
  95499. this.binT2Z = NaN;
  95500. this.norTU1X = NaN;
  95501. this.norTU1Y = NaN;
  95502. this.norTU1Z = NaN;
  95503. this.norTU2X = NaN;
  95504. this.norTU2Y = NaN;
  95505. this.norTU2Z = NaN;
  95506. this.tanTU1X = NaN;
  95507. this.tanTU1Y = NaN;
  95508. this.tanTU1Z = NaN;
  95509. this.tanTU2X = NaN;
  95510. this.tanTU2Y = NaN;
  95511. this.tanTU2Z = NaN;
  95512. this.binTU1X = NaN;
  95513. this.binTU1Y = NaN;
  95514. this.binTU1Z = NaN;
  95515. this.binTU2X = NaN;
  95516. this.binTU2Y = NaN;
  95517. this.binTU2Z = NaN;
  95518. this.norImp = NaN;
  95519. this.tanImp = NaN;
  95520. this.binImp = NaN;
  95521. this.norDen = NaN;
  95522. this.tanDen = NaN;
  95523. this.binDen = NaN;
  95524. this.norTar = NaN;
  95525. this.next = null;
  95526. this.last = false;
  95527. }
  95528. OIMO.ImpulseDataBuffer = function () {
  95529. this.lp1X = NaN;
  95530. this.lp1Y = NaN;
  95531. this.lp1Z = NaN;
  95532. this.lp2X = NaN;
  95533. this.lp2Y = NaN;
  95534. this.lp2Z = NaN;
  95535. this.impulse = NaN;
  95536. }
  95537. /**
  95538. * The class holds details of the contact point.
  95539. * @author saharan
  95540. */
  95541. OIMO.ManifoldPoint = function () {
  95542. // Whether this manifold point is persisting or not.
  95543. this.warmStarted = false;
  95544. // The position of this manifold point.
  95545. this.position = new OIMO.Vec3();
  95546. // The position in the first shape's coordinate.
  95547. this.localPoint1 = new OIMO.Vec3();
  95548. // The position in the second shape's coordinate.
  95549. this.localPoint2 = new OIMO.Vec3();
  95550. // The normal vector of this manifold point.
  95551. this.normal = new OIMO.Vec3();
  95552. // The tangent vector of this manifold point.
  95553. this.tangent = new OIMO.Vec3();
  95554. // The binormal vector of this manifold point.
  95555. this.binormal = new OIMO.Vec3();
  95556. // The impulse in normal direction.
  95557. this.normalImpulse = 0;
  95558. // The impulse in tangent direction.
  95559. this.tangentImpulse = 0;
  95560. // The impulse in binormal direction.
  95561. this.binormalImpulse = 0;
  95562. // The denominator in normal direction.
  95563. this.normalDenominator = 0;
  95564. // The denominator in tangent direction.
  95565. this.tangentDenominator = 0;
  95566. // The denominator in binormal direction.
  95567. this.binormalDenominator = 0;
  95568. // The depth of penetration.
  95569. this.penetration = 0;
  95570. }
  95571. /**
  95572. * This class holds mass information of a shape.
  95573. * @author saharan
  95574. */
  95575. OIMO.MassInfo = function () {
  95576. // Mass of the shape.
  95577. this.mass = 0;
  95578. // The moment inertia of the shape.
  95579. this.inertia = new OIMO.Mat33();
  95580. };
  95581. /**
  95582. * A shape is used to detect collisions of rigid bodies.
  95583. * @author saharan
  95584. * @author lo-th
  95585. */
  95586. OIMO.Shape = function (config) {
  95587. this.type = OIMO.SHAPE_NULL;
  95588. // The global identification of the shape should be unique to the shape.
  95589. this.id = OIMO.nextID++;
  95590. // The previous shape in parent rigid body.
  95591. this.prev = null;
  95592. // The next shape in parent rigid body.
  95593. this.next = null;
  95594. // The proxy of the shape used for broad-phase collision detection.
  95595. this.proxy = null;
  95596. // The parent rigid body of the shape.
  95597. this.parent = null;
  95598. // The linked list of the contacts with the shape.
  95599. this.contactLink = null;
  95600. // The number of the contacts with the shape.
  95601. this.numContacts = 0;
  95602. // The center of gravity of the shape in world coordinate system.
  95603. this.position = new OIMO.Vec3();
  95604. // The rotation matrix of the shape in world coordinate system
  95605. this.rotation = new OIMO.Mat33();
  95606. // The position of the shape in parent's coordinate system.
  95607. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  95608. // The rotation matrix of the shape in parent's coordinate system.
  95609. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  95610. // The axis-aligned bounding box of the shape.
  95611. this.aabb = new OIMO.AABB();
  95612. // The density of the shape.
  95613. this.density = config.density;
  95614. // The coefficient of friction of the shape.
  95615. this.friction = config.friction;
  95616. // The coefficient of restitution of the shape.
  95617. this.restitution = config.restitution;
  95618. // The bits of the collision groups to which the shape belongs.
  95619. this.belongsTo = config.belongsTo;
  95620. // The bits of the collision groups with which the shape collides.
  95621. this.collidesWith = config.collidesWith;
  95622. };
  95623. OIMO.Shape.prototype = {
  95624. constructor: OIMO.Shape,
  95625. // Calculate the mass information of the shape.
  95626. calculateMassInfo: function (out) {
  95627. OIMO.Error("Shape", "Inheritance error.");
  95628. },
  95629. // Update the proxy of the shape.
  95630. updateProxy: function () {
  95631. OIMO.Error("Shape", "Inheritance error.");
  95632. }
  95633. };
  95634. /**
  95635. * A shape configuration holds common configuration data for constructing a shape.
  95636. * Shape configurations can be reused safely.
  95637. * @author saharan
  95638. */
  95639. OIMO.ShapeConfig = function () {
  95640. // The position of the shape in parent's coordinate system.
  95641. this.relativePosition = new OIMO.Vec3();
  95642. // The rotation matrix of the shape in parent's coordinate system.
  95643. this.relativeRotation = new OIMO.Mat33();
  95644. // The coefficient of friction of the shape.
  95645. this.friction = 0.4;
  95646. // The coefficient of restitution of the shape.
  95647. this.restitution = 0.2;
  95648. // The density of the shape.
  95649. this.density = 1;
  95650. // The bits of the collision groups to which the shape belongs.
  95651. this.belongsTo = 1;
  95652. // The bits of the collision groups with which the shape collides.
  95653. this.collidesWith = 0xffffffff;
  95654. };
  95655. /**
  95656. * A box shape.
  95657. * @author saharan
  95658. * @author lo-th
  95659. */
  95660. OIMO.BoxShape = function (config, Width, Height, Depth) {
  95661. OIMO.Shape.call(this, config);
  95662. this.type = OIMO.SHAPE_BOX;
  95663. // The width of the box.
  95664. this.width = Width;
  95665. // The height of the box.
  95666. this.height = Height;
  95667. // The depth of the box.
  95668. this.depth = Depth;
  95669. // The half-width of the box.
  95670. this.halfWidth = Width * 0.5;
  95671. // The half-height of the box.
  95672. this.halfHeight = Height * 0.5;
  95673. // The half-depth of the box.
  95674. this.halfDepth = Depth * 0.5;
  95675. this.dimentions = new OIMO_ARRAY_TYPE(18);
  95676. this.elements = new OIMO_ARRAY_TYPE(24);
  95677. };
  95678. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  95679. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  95680. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  95681. var mass = this.width * this.height * this.depth * this.density;
  95682. var divid = 1 / 12;
  95683. out.mass = mass;
  95684. out.inertia.set(
  95685. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  95686. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  95687. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  95688. );
  95689. };
  95690. OIMO.BoxShape.prototype.updateProxy = function () {
  95691. var te = this.rotation.elements;
  95692. var di = this.dimentions;
  95693. // Width
  95694. di[0] = te[0];
  95695. di[1] = te[3];
  95696. di[2] = te[6];
  95697. // Height
  95698. di[3] = te[1];
  95699. di[4] = te[4];
  95700. di[5] = te[7];
  95701. // Depth
  95702. di[6] = te[2];
  95703. di[7] = te[5];
  95704. di[8] = te[8];
  95705. // halp Width
  95706. di[9] = te[0] * this.halfWidth;
  95707. di[10] = te[3] * this.halfWidth;
  95708. di[11] = te[6] * this.halfWidth;
  95709. // halp Height
  95710. di[12] = te[1] * this.halfHeight;
  95711. di[13] = te[4] * this.halfHeight;
  95712. di[14] = te[7] * this.halfHeight;
  95713. // halp Depth
  95714. di[15] = te[2] * this.halfDepth;
  95715. di[16] = te[5] * this.halfDepth;
  95716. di[17] = te[8] * this.halfDepth;
  95717. var wx = di[9];
  95718. var wy = di[10];
  95719. var wz = di[11];
  95720. var hx = di[12];
  95721. var hy = di[13];
  95722. var hz = di[14];
  95723. var dx = di[15];
  95724. var dy = di[16];
  95725. var dz = di[17];
  95726. var x = this.position.x;
  95727. var y = this.position.y;
  95728. var z = this.position.z;
  95729. var v = this.elements;
  95730. //v1
  95731. v[0] = x + wx + hx + dx;
  95732. v[1] = y + wy + hy + dy;
  95733. v[2] = z + wz + hz + dz;
  95734. //v2
  95735. v[3] = x + wx + hx - dx;
  95736. v[4] = y + wy + hy - dy;
  95737. v[5] = z + wz + hz - dz;
  95738. //v3
  95739. v[6] = x + wx - hx + dx;
  95740. v[7] = y + wy - hy + dy;
  95741. v[8] = z + wz - hz + dz;
  95742. //v4
  95743. v[9] = x + wx - hx - dx;
  95744. v[10] = y + wy - hy - dy;
  95745. v[11] = z + wz - hz - dz;
  95746. //v5
  95747. v[12] = x - wx + hx + dx;
  95748. v[13] = y - wy + hy + dy;
  95749. v[14] = z - wz + hz + dz;
  95750. //v6
  95751. v[15] = x - wx + hx - dx;
  95752. v[16] = y - wy + hy - dy;
  95753. v[17] = z - wz + hz - dz;
  95754. //v7
  95755. v[18] = x - wx - hx + dx;
  95756. v[19] = y - wy - hy + dy;
  95757. v[20] = z - wz - hz + dz;
  95758. //v8
  95759. v[21] = x - wx - hx - dx;
  95760. v[22] = y - wy - hy - dy;
  95761. v[23] = z - wz - hz - dz;
  95762. var w = di[9] < 0 ? -di[9] : di[9];
  95763. var h = di[10] < 0 ? -di[10] : di[10];
  95764. var d = di[11] < 0 ? -di[11] : di[11];
  95765. w = di[12] < 0 ? w - di[12] : w + di[12];
  95766. h = di[13] < 0 ? h - di[13] : h + di[13];
  95767. d = di[14] < 0 ? d - di[14] : d + di[14];
  95768. w = di[15] < 0 ? w - di[15] : w + di[15];
  95769. h = di[16] < 0 ? h - di[16] : h + di[16];
  95770. d = di[17] < 0 ? d - di[17] : d + di[17];
  95771. var p = OIMO.AABB_PROX;
  95772. this.aabb.set(
  95773. this.position.x - w - p, this.position.x + w + p,
  95774. this.position.y - h - p, this.position.y + h + p,
  95775. this.position.z - d - p, this.position.z + d + p
  95776. );
  95777. if (this.proxy != null) this.proxy.update();
  95778. };
  95779. /**
  95780. * A sphere shape.
  95781. * @author saharan
  95782. * @author lo-th
  95783. */
  95784. OIMO.SphereShape = function (config, radius) {
  95785. OIMO.Shape.call(this, config);
  95786. this.type = OIMO.SHAPE_SPHERE;
  95787. // The radius of the shape.
  95788. this.radius = radius;
  95789. };
  95790. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  95791. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  95792. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  95793. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  95794. out.mass = mass;
  95795. var inertia = mass * this.radius * this.radius * 0.4;
  95796. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  95797. };
  95798. OIMO.SphereShape.prototype.updateProxy = function () {
  95799. var p = OIMO.AABB_PROX;
  95800. this.aabb.set(
  95801. this.position.x - this.radius - p, this.position.x + this.radius + p,
  95802. this.position.y - this.radius - p, this.position.y + this.radius + p,
  95803. this.position.z - this.radius - p, this.position.z + this.radius + p
  95804. );
  95805. if (this.proxy != null) this.proxy.update();
  95806. };
  95807. /**
  95808. * A cylinder shap.
  95809. * @author saharan
  95810. * @author lo-th
  95811. */
  95812. OIMO.CylinderShape = function (config, radius, height) {
  95813. OIMO.Shape.call(this, config);
  95814. this.type = OIMO.SHAPE_CYLINDER;
  95815. this.radius = radius;
  95816. this.height = height;
  95817. this.halfHeight = height * 0.5;
  95818. this.normalDirection = new OIMO.Vec3();
  95819. this.halfDirection = new OIMO.Vec3();
  95820. };
  95821. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  95822. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  95823. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  95824. var rsq = this.radius * this.radius;
  95825. var mass = OIMO.PI * rsq * this.height * this.density;
  95826. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  95827. var inertiaY = 0.5 * rsq;
  95828. out.mass = mass;
  95829. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  95830. };
  95831. OIMO.CylinderShape.prototype.updateProxy = function () {
  95832. var te = this.rotation.elements;
  95833. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  95834. xx = te[1] * te[1];
  95835. yy = te[4] * te[4];
  95836. zz = te[7] * te[7];
  95837. this.normalDirection.set(te[1], te[4], te[7]);
  95838. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  95839. wx = 1 - xx;
  95840. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  95841. if (len > 0) len = this.radius / len;
  95842. wx *= len;
  95843. hy = 1 - yy;
  95844. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  95845. if (len > 0) len = this.radius / len;
  95846. hy *= len;
  95847. dz = 1 - zz;
  95848. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  95849. if (len > 0) len = this.radius / len;
  95850. dz *= len;
  95851. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  95852. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  95853. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  95854. w = wx < 0 ? w - wx : w + wx;
  95855. h = hy < 0 ? h - hy : h + hy;
  95856. d = dz < 0 ? d - dz : d + dz;
  95857. p = OIMO.AABB_PROX;
  95858. this.aabb.set(
  95859. this.position.x - w - p, this.position.x + w + p,
  95860. this.position.y - h - p, this.position.y + h + p,
  95861. this.position.z - d - p, this.position.z + d + p
  95862. );
  95863. if (this.proxy != null) this.proxy.update();
  95864. };
  95865. /**
  95866. * A tetra shape.
  95867. * @author xprogram
  95868. */
  95869. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  95870. OIMO.Shape.call(this, config);
  95871. this.type = OIMO.SHAPE_TETRA;
  95872. // Vertices and faces of tetra
  95873. this.verts = [p1, p2, p3, p4];
  95874. this.faces = [
  95875. mtri(0, 1, 2),
  95876. mtri(1, 2, 3),
  95877. mtri(2, 3, 4),
  95878. mtri(4, 0, 1),
  95879. ];
  95880. };
  95881. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  95882. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  95883. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  95884. // I guess you could calculate box mass and split it
  95885. // in half for the tetra...
  95886. };
  95887. OIMO.TetraShape.prototype.updateProxy = function () {
  95888. this.aabb.setFromPoints(this.verts);
  95889. if (this.proxy !== null)
  95890. this.proxy.update();
  95891. };
  95892. function mtri(a, b, c) {
  95893. return { a: a, b: b, c: c };
  95894. }
  95895. OIMO.CollisionDetector = function () {
  95896. this.flip = false;
  95897. };
  95898. OIMO.CollisionDetector.prototype = {
  95899. constructor: OIMO.CollisionDetector,
  95900. detectCollision: function (shape1, shape2, manifold) {
  95901. OIMO.Error("CollisionDetector", "Inheritance error.");
  95902. }
  95903. };
  95904. /**
  95905. * A collision detector which detects collisions between two boxes.
  95906. * @author saharan
  95907. */
  95908. OIMO.BoxBoxCollisionDetector = function () {
  95909. OIMO.CollisionDetector.call(this);
  95910. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  95911. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  95912. this.used = new OIMO_ARRAY_TYPE(8);
  95913. this.INF = 1 / 0;
  95914. };
  95915. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  95916. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  95917. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  95918. // What you are doing
  95919. // · I to prepare a separate axis of the fifteen
  95920. //-Six in each of three normal vectors of the xyz direction of the box both
  95921. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  95922. // · Calculate the depth to the separation axis
  95923. // Calculates the distance using the inner product and put the amount of embedment
  95924. // · However a vertical separation axis and side to weight a little to avoid vibration
  95925. // And end when there is a separate axis that is remote even one
  95926. // · I look for separation axis with little to dent most
  95927. // Men and if separation axis of the first six - end collision
  95928. // Heng If it separate axis of nine other - side collision
  95929. // Heng - case of a side collision
  95930. // · Find points of two sides on which you made ​​the separation axis
  95931. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  95932. //-Surface - the case of the plane crash
  95933. //-Box A, box B and the other a box of better made ​​a separate axis
  95934. // • 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
  95935. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  95936. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  95937. // • If more than one candidate 5 exists, scraping up to four
  95938. // For potential collision points of all, to examine the distance between the surface A
  95939. // • If you were on the inside surface of A, and the collision point
  95940. var b1;
  95941. var b2;
  95942. if (shape1.id < shape2.id) {
  95943. b1 = (shape1);
  95944. b2 = (shape2);
  95945. } else {
  95946. b1 = (shape2);
  95947. b2 = (shape1);
  95948. }
  95949. var V1 = b1.elements;
  95950. var V2 = b2.elements;
  95951. var D1 = b1.dimentions;
  95952. var D2 = b2.dimentions;
  95953. var p1 = b1.position;
  95954. var p2 = b2.position;
  95955. var p1x = p1.x;
  95956. var p1y = p1.y;
  95957. var p1z = p1.z;
  95958. var p2x = p2.x;
  95959. var p2y = p2.y;
  95960. var p2z = p2.z;
  95961. // diff
  95962. var dx = p2x - p1x;
  95963. var dy = p2y - p1y;
  95964. var dz = p2z - p1z;
  95965. // distance
  95966. var w1 = b1.halfWidth;
  95967. var h1 = b1.halfHeight;
  95968. var d1 = b1.halfDepth;
  95969. var w2 = b2.halfWidth;
  95970. var h2 = b2.halfHeight;
  95971. var d2 = b2.halfDepth;
  95972. // direction
  95973. // ----------------------------
  95974. // 15 separating axes
  95975. // 1~6: face
  95976. // 7~f: edge
  95977. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  95978. // ----------------------------
  95979. var a1x = D1[0];
  95980. var a1y = D1[1];
  95981. var a1z = D1[2];
  95982. var a2x = D1[3];
  95983. var a2y = D1[4];
  95984. var a2z = D1[5];
  95985. var a3x = D1[6];
  95986. var a3y = D1[7];
  95987. var a3z = D1[8];
  95988. var d1x = D1[9];
  95989. var d1y = D1[10];
  95990. var d1z = D1[11];
  95991. var d2x = D1[12];
  95992. var d2y = D1[13];
  95993. var d2z = D1[14];
  95994. var d3x = D1[15];
  95995. var d3y = D1[16];
  95996. var d3z = D1[17];
  95997. var a4x = D2[0];
  95998. var a4y = D2[1];
  95999. var a4z = D2[2];
  96000. var a5x = D2[3];
  96001. var a5y = D2[4];
  96002. var a5z = D2[5];
  96003. var a6x = D2[6];
  96004. var a6y = D2[7];
  96005. var a6z = D2[8];
  96006. var d4x = D2[9];
  96007. var d4y = D2[10];
  96008. var d4z = D2[11];
  96009. var d5x = D2[12];
  96010. var d5y = D2[13];
  96011. var d5z = D2[14];
  96012. var d6x = D2[15];
  96013. var d6y = D2[16];
  96014. var d6z = D2[17];
  96015. var a7x = a1y * a4z - a1z * a4y;
  96016. var a7y = a1z * a4x - a1x * a4z;
  96017. var a7z = a1x * a4y - a1y * a4x;
  96018. var a8x = a1y * a5z - a1z * a5y;
  96019. var a8y = a1z * a5x - a1x * a5z;
  96020. var a8z = a1x * a5y - a1y * a5x;
  96021. var a9x = a1y * a6z - a1z * a6y;
  96022. var a9y = a1z * a6x - a1x * a6z;
  96023. var a9z = a1x * a6y - a1y * a6x;
  96024. var aax = a2y * a4z - a2z * a4y;
  96025. var aay = a2z * a4x - a2x * a4z;
  96026. var aaz = a2x * a4y - a2y * a4x;
  96027. var abx = a2y * a5z - a2z * a5y;
  96028. var aby = a2z * a5x - a2x * a5z;
  96029. var abz = a2x * a5y - a2y * a5x;
  96030. var acx = a2y * a6z - a2z * a6y;
  96031. var acy = a2z * a6x - a2x * a6z;
  96032. var acz = a2x * a6y - a2y * a6x;
  96033. var adx = a3y * a4z - a3z * a4y;
  96034. var ady = a3z * a4x - a3x * a4z;
  96035. var adz = a3x * a4y - a3y * a4x;
  96036. var aex = a3y * a5z - a3z * a5y;
  96037. var aey = a3z * a5x - a3x * a5z;
  96038. var aez = a3x * a5y - a3y * a5x;
  96039. var afx = a3y * a6z - a3z * a6y;
  96040. var afy = a3z * a6x - a3x * a6z;
  96041. var afz = a3x * a6y - a3y * a6x;
  96042. // right or left flags
  96043. var right1;
  96044. var right2;
  96045. var right3;
  96046. var right4;
  96047. var right5;
  96048. var right6;
  96049. var right7;
  96050. var right8;
  96051. var right9;
  96052. var righta;
  96053. var rightb;
  96054. var rightc;
  96055. var rightd;
  96056. var righte;
  96057. var rightf;
  96058. // overlapping distances
  96059. var overlap1;
  96060. var overlap2;
  96061. var overlap3;
  96062. var overlap4;
  96063. var overlap5;
  96064. var overlap6;
  96065. var overlap7;
  96066. var overlap8;
  96067. var overlap9;
  96068. var overlapa;
  96069. var overlapb;
  96070. var overlapc;
  96071. var overlapd;
  96072. var overlape;
  96073. var overlapf;
  96074. // invalid flags
  96075. var invalid7 = false;
  96076. var invalid8 = false;
  96077. var invalid9 = false;
  96078. var invalida = false;
  96079. var invalidb = false;
  96080. var invalidc = false;
  96081. var invalidd = false;
  96082. var invalide = false;
  96083. var invalidf = false;
  96084. // temporary variables
  96085. var len;
  96086. var len1;
  96087. var len2;
  96088. var dot1;
  96089. var dot2;
  96090. var dot3;
  96091. // try axis 1
  96092. len = a1x * dx + a1y * dy + a1z * dz;
  96093. right1 = len > 0;
  96094. if (!right1) len = -len;
  96095. len1 = w1;
  96096. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  96097. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  96098. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  96099. if (dot1 < 0) dot1 = -dot1;
  96100. if (dot2 < 0) dot2 = -dot2;
  96101. if (dot3 < 0) dot3 = -dot3;
  96102. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  96103. overlap1 = len - len1 - len2;
  96104. if (overlap1 > 0) return;
  96105. // try axis 2
  96106. len = a2x * dx + a2y * dy + a2z * dz;
  96107. right2 = len > 0;
  96108. if (!right2) len = -len;
  96109. len1 = h1;
  96110. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  96111. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  96112. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  96113. if (dot1 < 0) dot1 = -dot1;
  96114. if (dot2 < 0) dot2 = -dot2;
  96115. if (dot3 < 0) dot3 = -dot3;
  96116. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  96117. overlap2 = len - len1 - len2;
  96118. if (overlap2 > 0) return;
  96119. // try axis 3
  96120. len = a3x * dx + a3y * dy + a3z * dz;
  96121. right3 = len > 0;
  96122. if (!right3) len = -len;
  96123. len1 = d1;
  96124. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  96125. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  96126. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  96127. if (dot1 < 0) dot1 = -dot1;
  96128. if (dot2 < 0) dot2 = -dot2;
  96129. if (dot3 < 0) dot3 = -dot3;
  96130. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  96131. overlap3 = len - len1 - len2;
  96132. if (overlap3 > 0) return;
  96133. // try axis 4
  96134. len = a4x * dx + a4y * dy + a4z * dz;
  96135. right4 = len > 0;
  96136. if (!right4) len = -len;
  96137. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  96138. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  96139. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  96140. if (dot1 < 0) dot1 = -dot1;
  96141. if (dot2 < 0) dot2 = -dot2;
  96142. if (dot3 < 0) dot3 = -dot3;
  96143. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  96144. len2 = w2;
  96145. overlap4 = (len - len1 - len2) * 1.0;
  96146. if (overlap4 > 0) return;
  96147. // try axis 5
  96148. len = a5x * dx + a5y * dy + a5z * dz;
  96149. right5 = len > 0;
  96150. if (!right5) len = -len;
  96151. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  96152. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  96153. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  96154. if (dot1 < 0) dot1 = -dot1;
  96155. if (dot2 < 0) dot2 = -dot2;
  96156. if (dot3 < 0) dot3 = -dot3;
  96157. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  96158. len2 = h2;
  96159. overlap5 = (len - len1 - len2) * 1.0;
  96160. if (overlap5 > 0) return;
  96161. // try axis 6
  96162. len = a6x * dx + a6y * dy + a6z * dz;
  96163. right6 = len > 0;
  96164. if (!right6) len = -len;
  96165. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  96166. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  96167. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  96168. if (dot1 < 0) dot1 = -dot1;
  96169. if (dot2 < 0) dot2 = -dot2;
  96170. if (dot3 < 0) dot3 = -dot3;
  96171. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  96172. len2 = d2;
  96173. overlap6 = (len - len1 - len2) * 1.0;
  96174. if (overlap6 > 0) return;
  96175. // try axis 7
  96176. len = a7x * a7x + a7y * a7y + a7z * a7z;
  96177. if (len > 1e-5) {
  96178. len = 1 / OIMO.sqrt(len);
  96179. a7x *= len;
  96180. a7y *= len;
  96181. a7z *= len;
  96182. len = a7x * dx + a7y * dy + a7z * dz;
  96183. right7 = len > 0;
  96184. if (!right7) len = -len;
  96185. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  96186. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  96187. if (dot1 < 0) dot1 = -dot1;
  96188. if (dot2 < 0) dot2 = -dot2;
  96189. len1 = dot1 * h1 + dot2 * d1;
  96190. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  96191. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  96192. if (dot1 < 0) dot1 = -dot1;
  96193. if (dot2 < 0) dot2 = -dot2;
  96194. len2 = dot1 * h2 + dot2 * d2;
  96195. overlap7 = len - len1 - len2;
  96196. if (overlap7 > 0) return;
  96197. } else {
  96198. right7 = false;
  96199. overlap7 = 0;
  96200. invalid7 = true;
  96201. }
  96202. // try axis 8
  96203. len = a8x * a8x + a8y * a8y + a8z * a8z;
  96204. if (len > 1e-5) {
  96205. len = 1 / OIMO.sqrt(len);
  96206. a8x *= len;
  96207. a8y *= len;
  96208. a8z *= len;
  96209. len = a8x * dx + a8y * dy + a8z * dz;
  96210. right8 = len > 0;
  96211. if (!right8) len = -len;
  96212. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  96213. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  96214. if (dot1 < 0) dot1 = -dot1;
  96215. if (dot2 < 0) dot2 = -dot2;
  96216. len1 = dot1 * h1 + dot2 * d1;
  96217. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  96218. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  96219. if (dot1 < 0) dot1 = -dot1;
  96220. if (dot2 < 0) dot2 = -dot2;
  96221. len2 = dot1 * w2 + dot2 * d2;
  96222. overlap8 = len - len1 - len2;
  96223. if (overlap8 > 0) return;
  96224. } else {
  96225. right8 = false;
  96226. overlap8 = 0;
  96227. invalid8 = true;
  96228. }
  96229. // try axis 9
  96230. len = a9x * a9x + a9y * a9y + a9z * a9z;
  96231. if (len > 1e-5) {
  96232. len = 1 / OIMO.sqrt(len);
  96233. a9x *= len;
  96234. a9y *= len;
  96235. a9z *= len;
  96236. len = a9x * dx + a9y * dy + a9z * dz;
  96237. right9 = len > 0;
  96238. if (!right9) len = -len;
  96239. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  96240. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  96241. if (dot1 < 0) dot1 = -dot1;
  96242. if (dot2 < 0) dot2 = -dot2;
  96243. len1 = dot1 * h1 + dot2 * d1;
  96244. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  96245. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  96246. if (dot1 < 0) dot1 = -dot1;
  96247. if (dot2 < 0) dot2 = -dot2;
  96248. len2 = dot1 * w2 + dot2 * h2;
  96249. overlap9 = len - len1 - len2;
  96250. if (overlap9 > 0) return;
  96251. } else {
  96252. right9 = false;
  96253. overlap9 = 0;
  96254. invalid9 = true;
  96255. }
  96256. // try axis 10
  96257. len = aax * aax + aay * aay + aaz * aaz;
  96258. if (len > 1e-5) {
  96259. len = 1 / OIMO.sqrt(len);
  96260. aax *= len;
  96261. aay *= len;
  96262. aaz *= len;
  96263. len = aax * dx + aay * dy + aaz * dz;
  96264. righta = len > 0;
  96265. if (!righta) len = -len;
  96266. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  96267. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  96268. if (dot1 < 0) dot1 = -dot1;
  96269. if (dot2 < 0) dot2 = -dot2;
  96270. len1 = dot1 * w1 + dot2 * d1;
  96271. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  96272. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  96273. if (dot1 < 0) dot1 = -dot1;
  96274. if (dot2 < 0) dot2 = -dot2;
  96275. len2 = dot1 * h2 + dot2 * d2;
  96276. overlapa = len - len1 - len2;
  96277. if (overlapa > 0) return;
  96278. } else {
  96279. righta = false;
  96280. overlapa = 0;
  96281. invalida = true;
  96282. }
  96283. // try axis 11
  96284. len = abx * abx + aby * aby + abz * abz;
  96285. if (len > 1e-5) {
  96286. len = 1 / OIMO.sqrt(len);
  96287. abx *= len;
  96288. aby *= len;
  96289. abz *= len;
  96290. len = abx * dx + aby * dy + abz * dz;
  96291. rightb = len > 0;
  96292. if (!rightb) len = -len;
  96293. dot1 = abx * a1x + aby * a1y + abz * a1z;
  96294. dot2 = abx * a3x + aby * a3y + abz * a3z;
  96295. if (dot1 < 0) dot1 = -dot1;
  96296. if (dot2 < 0) dot2 = -dot2;
  96297. len1 = dot1 * w1 + dot2 * d1;
  96298. dot1 = abx * a4x + aby * a4y + abz * a4z;
  96299. dot2 = abx * a6x + aby * a6y + abz * a6z;
  96300. if (dot1 < 0) dot1 = -dot1;
  96301. if (dot2 < 0) dot2 = -dot2;
  96302. len2 = dot1 * w2 + dot2 * d2;
  96303. overlapb = len - len1 - len2;
  96304. if (overlapb > 0) return;
  96305. } else {
  96306. rightb = false;
  96307. overlapb = 0;
  96308. invalidb = true;
  96309. }
  96310. // try axis 12
  96311. len = acx * acx + acy * acy + acz * acz;
  96312. if (len > 1e-5) {
  96313. len = 1 / OIMO.sqrt(len);
  96314. acx *= len;
  96315. acy *= len;
  96316. acz *= len;
  96317. len = acx * dx + acy * dy + acz * dz;
  96318. rightc = len > 0;
  96319. if (!rightc) len = -len;
  96320. dot1 = acx * a1x + acy * a1y + acz * a1z;
  96321. dot2 = acx * a3x + acy * a3y + acz * a3z;
  96322. if (dot1 < 0) dot1 = -dot1;
  96323. if (dot2 < 0) dot2 = -dot2;
  96324. len1 = dot1 * w1 + dot2 * d1;
  96325. dot1 = acx * a4x + acy * a4y + acz * a4z;
  96326. dot2 = acx * a5x + acy * a5y + acz * a5z;
  96327. if (dot1 < 0) dot1 = -dot1;
  96328. if (dot2 < 0) dot2 = -dot2;
  96329. len2 = dot1 * w2 + dot2 * h2;
  96330. overlapc = len - len1 - len2;
  96331. if (overlapc > 0) return;
  96332. } else {
  96333. rightc = false;
  96334. overlapc = 0;
  96335. invalidc = true;
  96336. }
  96337. // try axis 13
  96338. len = adx * adx + ady * ady + adz * adz;
  96339. if (len > 1e-5) {
  96340. len = 1 / OIMO.sqrt(len);
  96341. adx *= len;
  96342. ady *= len;
  96343. adz *= len;
  96344. len = adx * dx + ady * dy + adz * dz;
  96345. rightd = len > 0;
  96346. if (!rightd) len = -len;
  96347. dot1 = adx * a1x + ady * a1y + adz * a1z;
  96348. dot2 = adx * a2x + ady * a2y + adz * a2z;
  96349. if (dot1 < 0) dot1 = -dot1;
  96350. if (dot2 < 0) dot2 = -dot2;
  96351. len1 = dot1 * w1 + dot2 * h1;
  96352. dot1 = adx * a5x + ady * a5y + adz * a5z;
  96353. dot2 = adx * a6x + ady * a6y + adz * a6z;
  96354. if (dot1 < 0) dot1 = -dot1;
  96355. if (dot2 < 0) dot2 = -dot2;
  96356. len2 = dot1 * h2 + dot2 * d2;
  96357. overlapd = len - len1 - len2;
  96358. if (overlapd > 0) return;
  96359. } else {
  96360. rightd = false;
  96361. overlapd = 0;
  96362. invalidd = true;
  96363. }
  96364. // try axis 14
  96365. len = aex * aex + aey * aey + aez * aez;
  96366. if (len > 1e-5) {
  96367. len = 1 / OIMO.sqrt(len);
  96368. aex *= len;
  96369. aey *= len;
  96370. aez *= len;
  96371. len = aex * dx + aey * dy + aez * dz;
  96372. righte = len > 0;
  96373. if (!righte) len = -len;
  96374. dot1 = aex * a1x + aey * a1y + aez * a1z;
  96375. dot2 = aex * a2x + aey * a2y + aez * a2z;
  96376. if (dot1 < 0) dot1 = -dot1;
  96377. if (dot2 < 0) dot2 = -dot2;
  96378. len1 = dot1 * w1 + dot2 * h1;
  96379. dot1 = aex * a4x + aey * a4y + aez * a4z;
  96380. dot2 = aex * a6x + aey * a6y + aez * a6z;
  96381. if (dot1 < 0) dot1 = -dot1;
  96382. if (dot2 < 0) dot2 = -dot2;
  96383. len2 = dot1 * w2 + dot2 * d2;
  96384. overlape = len - len1 - len2;
  96385. if (overlape > 0) return;
  96386. } else {
  96387. righte = false;
  96388. overlape = 0;
  96389. invalide = true;
  96390. }
  96391. // try axis 15
  96392. len = afx * afx + afy * afy + afz * afz;
  96393. if (len > 1e-5) {
  96394. len = 1 / OIMO.sqrt(len);
  96395. afx *= len;
  96396. afy *= len;
  96397. afz *= len;
  96398. len = afx * dx + afy * dy + afz * dz;
  96399. rightf = len > 0;
  96400. if (!rightf) len = -len;
  96401. dot1 = afx * a1x + afy * a1y + afz * a1z;
  96402. dot2 = afx * a2x + afy * a2y + afz * a2z;
  96403. if (dot1 < 0) dot1 = -dot1;
  96404. if (dot2 < 0) dot2 = -dot2;
  96405. len1 = dot1 * w1 + dot2 * h1;
  96406. dot1 = afx * a4x + afy * a4y + afz * a4z;
  96407. dot2 = afx * a5x + afy * a5y + afz * a5z;
  96408. if (dot1 < 0) dot1 = -dot1;
  96409. if (dot2 < 0) dot2 = -dot2;
  96410. len2 = dot1 * w2 + dot2 * h2;
  96411. overlapf = len - len1 - len2;
  96412. if (overlapf > 0) return;
  96413. } else {
  96414. rightf = false;
  96415. overlapf = 0;
  96416. invalidf = true;
  96417. }
  96418. // boxes are overlapping
  96419. var depth = overlap1;
  96420. var depth2 = overlap1;
  96421. var minIndex = 0;
  96422. var right = right1;
  96423. if (overlap2 > depth2) {
  96424. depth = overlap2;
  96425. depth2 = overlap2;
  96426. minIndex = 1;
  96427. right = right2;
  96428. }
  96429. if (overlap3 > depth2) {
  96430. depth = overlap3;
  96431. depth2 = overlap3;
  96432. minIndex = 2;
  96433. right = right3;
  96434. }
  96435. if (overlap4 > depth2) {
  96436. depth = overlap4;
  96437. depth2 = overlap4;
  96438. minIndex = 3;
  96439. right = right4;
  96440. }
  96441. if (overlap5 > depth2) {
  96442. depth = overlap5;
  96443. depth2 = overlap5;
  96444. minIndex = 4;
  96445. right = right5;
  96446. }
  96447. if (overlap6 > depth2) {
  96448. depth = overlap6;
  96449. depth2 = overlap6;
  96450. minIndex = 5;
  96451. right = right6;
  96452. }
  96453. if (overlap7 - 0.01 > depth2 && !invalid7) {
  96454. depth = overlap7;
  96455. depth2 = overlap7 - 0.01;
  96456. minIndex = 6;
  96457. right = right7;
  96458. }
  96459. if (overlap8 - 0.01 > depth2 && !invalid8) {
  96460. depth = overlap8;
  96461. depth2 = overlap8 - 0.01;
  96462. minIndex = 7;
  96463. right = right8;
  96464. }
  96465. if (overlap9 - 0.01 > depth2 && !invalid9) {
  96466. depth = overlap9;
  96467. depth2 = overlap9 - 0.01;
  96468. minIndex = 8;
  96469. right = right9;
  96470. }
  96471. if (overlapa - 0.01 > depth2 && !invalida) {
  96472. depth = overlapa;
  96473. depth2 = overlapa - 0.01;
  96474. minIndex = 9;
  96475. right = righta;
  96476. }
  96477. if (overlapb - 0.01 > depth2 && !invalidb) {
  96478. depth = overlapb;
  96479. depth2 = overlapb - 0.01;
  96480. minIndex = 10;
  96481. right = rightb;
  96482. }
  96483. if (overlapc - 0.01 > depth2 && !invalidc) {
  96484. depth = overlapc;
  96485. depth2 = overlapc - 0.01;
  96486. minIndex = 11;
  96487. right = rightc;
  96488. }
  96489. if (overlapd - 0.01 > depth2 && !invalidd) {
  96490. depth = overlapd;
  96491. depth2 = overlapd - 0.01;
  96492. minIndex = 12;
  96493. right = rightd;
  96494. }
  96495. if (overlape - 0.01 > depth2 && !invalide) {
  96496. depth = overlape;
  96497. depth2 = overlape - 0.01;
  96498. minIndex = 13;
  96499. right = righte;
  96500. }
  96501. if (overlapf - 0.01 > depth2 && !invalidf) {
  96502. depth = overlapf;
  96503. minIndex = 14;
  96504. right = rightf;
  96505. }
  96506. // normal
  96507. var nx = 0;
  96508. var ny = 0;
  96509. var nz = 0;
  96510. // edge line or face side normal
  96511. var n1x = 0;
  96512. var n1y = 0;
  96513. var n1z = 0;
  96514. var n2x = 0;
  96515. var n2y = 0;
  96516. var n2z = 0;
  96517. // center of current face
  96518. var cx = 0;
  96519. var cy = 0;
  96520. var cz = 0;
  96521. // face side
  96522. var s1x = 0;
  96523. var s1y = 0;
  96524. var s1z = 0;
  96525. var s2x = 0;
  96526. var s2y = 0;
  96527. var s2z = 0;
  96528. // swap b1 b2
  96529. var swap = false;
  96530. //_______________________________________
  96531. if (minIndex == 0) {// b1.x * b2
  96532. if (right) {
  96533. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  96534. nx = a1x; ny = a1y; nz = a1z;
  96535. } else {
  96536. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  96537. nx = -a1x; ny = -a1y; nz = -a1z;
  96538. }
  96539. s1x = d2x; s1y = d2y; s1z = d2z;
  96540. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  96541. s2x = d3x; s2y = d3y; s2z = d3z;
  96542. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  96543. }
  96544. else if (minIndex == 1) {// b1.y * b2
  96545. if (right) {
  96546. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  96547. nx = a2x; ny = a2y; nz = a2z;
  96548. } else {
  96549. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  96550. nx = -a2x; ny = -a2y; nz = -a2z;
  96551. }
  96552. s1x = d1x; s1y = d1y; s1z = d1z;
  96553. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  96554. s2x = d3x; s2y = d3y; s2z = d3z;
  96555. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  96556. }
  96557. else if (minIndex == 2) {// b1.z * b2
  96558. if (right) {
  96559. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  96560. nx = a3x; ny = a3y; nz = a3z;
  96561. } else {
  96562. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  96563. nx = -a3x; ny = -a3y; nz = -a3z;
  96564. }
  96565. s1x = d1x; s1y = d1y; s1z = d1z;
  96566. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  96567. s2x = d2x; s2y = d2y; s2z = d2z;
  96568. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  96569. }
  96570. else if (minIndex == 3) {// b2.x * b1
  96571. swap = true;
  96572. if (!right) {
  96573. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  96574. nx = a4x; ny = a4y; nz = a4z;
  96575. } else {
  96576. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  96577. nx = -a4x; ny = -a4y; nz = -a4z;
  96578. }
  96579. s1x = d5x; s1y = d5y; s1z = d5z;
  96580. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  96581. s2x = d6x; s2y = d6y; s2z = d6z;
  96582. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  96583. }
  96584. else if (minIndex == 4) {// b2.y * b1
  96585. swap = true;
  96586. if (!right) {
  96587. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  96588. nx = a5x; ny = a5y; nz = a5z;
  96589. } else {
  96590. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  96591. nx = -a5x; ny = -a5y; nz = -a5z;
  96592. }
  96593. s1x = d4x; s1y = d4y; s1z = d4z;
  96594. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  96595. s2x = d6x; s2y = d6y; s2z = d6z;
  96596. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  96597. }
  96598. else if (minIndex == 5) {// b2.z * b1
  96599. swap = true;
  96600. if (!right) {
  96601. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  96602. nx = a6x; ny = a6y; nz = a6z;
  96603. } else {
  96604. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  96605. nx = -a6x; ny = -a6y; nz = -a6z;
  96606. }
  96607. s1x = d4x; s1y = d4y; s1z = d4z;
  96608. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  96609. s2x = d5x; s2y = d5y; s2z = d5z;
  96610. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  96611. }
  96612. else if (minIndex == 6) {// b1.x * b2.x
  96613. nx = a7x; ny = a7y; nz = a7z;
  96614. n1x = a1x; n1y = a1y; n1z = a1z;
  96615. n2x = a4x; n2y = a4y; n2z = a4z;
  96616. }
  96617. else if (minIndex == 7) {// b1.x * b2.y
  96618. nx = a8x; ny = a8y; nz = a8z;
  96619. n1x = a1x; n1y = a1y; n1z = a1z;
  96620. n2x = a5x; n2y = a5y; n2z = a5z;
  96621. }
  96622. else if (minIndex == 8) {// b1.x * b2.z
  96623. nx = a9x; ny = a9y; nz = a9z;
  96624. n1x = a1x; n1y = a1y; n1z = a1z;
  96625. n2x = a6x; n2y = a6y; n2z = a6z;
  96626. }
  96627. else if (minIndex == 9) {// b1.y * b2.x
  96628. nx = aax; ny = aay; nz = aaz;
  96629. n1x = a2x; n1y = a2y; n1z = a2z;
  96630. n2x = a4x; n2y = a4y; n2z = a4z
  96631. }
  96632. else if (minIndex == 10) {// b1.y * b2.y
  96633. nx = abx; ny = aby; nz = abz;
  96634. n1x = a2x; n1y = a2y; n1z = a2z;
  96635. n2x = a5x; n2y = a5y; n2z = a5z;
  96636. }
  96637. else if (minIndex == 11) {// b1.y * b2.z
  96638. nx = acx; ny = acy; nz = acz;
  96639. n1x = a2x; n1y = a2y; n1z = a2z;
  96640. n2x = a6x; n2y = a6y; n2z = a6z;
  96641. }
  96642. else if (minIndex == 12) {// b1.z * b2.x
  96643. nx = adx; ny = ady; nz = adz;
  96644. n1x = a3x; n1y = a3y; n1z = a3z;
  96645. n2x = a4x; n2y = a4y; n2z = a4z;
  96646. }
  96647. else if (minIndex == 13) {// b1.z * b2.y
  96648. nx = aex; ny = aey; nz = aez;
  96649. n1x = a3x; n1y = a3y; n1z = a3z;
  96650. n2x = a5x; n2y = a5y; n2z = a5z;
  96651. }
  96652. else if (minIndex == 14) {// b1.z * b2.z
  96653. nx = afx; ny = afy; nz = afz;
  96654. n1x = a3x; n1y = a3y; n1z = a3z;
  96655. n2x = a6x; n2y = a6y; n2z = a6z;
  96656. }
  96657. //__________________________________________
  96658. var v;
  96659. if (minIndex > 5) {
  96660. if (!right) {
  96661. nx = -nx; ny = -ny; nz = -nz;
  96662. }
  96663. var distance;
  96664. var maxDistance;
  96665. var vx;
  96666. var vy;
  96667. var vz;
  96668. var v1x;
  96669. var v1y;
  96670. var v1z;
  96671. var v2x;
  96672. var v2y;
  96673. var v2z;
  96674. //vertex1;
  96675. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  96676. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  96677. //vertex2;
  96678. vx = V1[3]; vy = V1[4]; vz = V1[5];
  96679. distance = nx * vx + ny * vy + nz * vz;
  96680. if (distance > maxDistance) {
  96681. maxDistance = distance;
  96682. v1x = vx; v1y = vy; v1z = vz;
  96683. }
  96684. //vertex3;
  96685. vx = V1[6]; vy = V1[7]; vz = V1[8];
  96686. distance = nx * vx + ny * vy + nz * vz;
  96687. if (distance > maxDistance) {
  96688. maxDistance = distance;
  96689. v1x = vx; v1y = vy; v1z = vz;
  96690. }
  96691. //vertex4;
  96692. vx = V1[9]; vy = V1[10]; vz = V1[11];
  96693. distance = nx * vx + ny * vy + nz * vz;
  96694. if (distance > maxDistance) {
  96695. maxDistance = distance;
  96696. v1x = vx; v1y = vy; v1z = vz;
  96697. }
  96698. //vertex5;
  96699. vx = V1[12]; vy = V1[13]; vz = V1[14];
  96700. distance = nx * vx + ny * vy + nz * vz;
  96701. if (distance > maxDistance) {
  96702. maxDistance = distance;
  96703. v1x = vx; v1y = vy; v1z = vz;
  96704. }
  96705. //vertex6;
  96706. vx = V1[15]; vy = V1[16]; vz = V1[17];
  96707. distance = nx * vx + ny * vy + nz * vz;
  96708. if (distance > maxDistance) {
  96709. maxDistance = distance;
  96710. v1x = vx; v1y = vy; v1z = vz;
  96711. }
  96712. //vertex7;
  96713. vx = V1[18]; vy = V1[19]; vz = V1[20];
  96714. distance = nx * vx + ny * vy + nz * vz;
  96715. if (distance > maxDistance) {
  96716. maxDistance = distance;
  96717. v1x = vx; v1y = vy; v1z = vz;
  96718. }
  96719. //vertex8;
  96720. vx = V1[21]; vy = V1[22]; vz = V1[23];
  96721. distance = nx * vx + ny * vy + nz * vz;
  96722. if (distance > maxDistance) {
  96723. maxDistance = distance;
  96724. v1x = vx; v1y = vy; v1z = vz;
  96725. }
  96726. //vertex1;
  96727. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  96728. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  96729. //vertex2;
  96730. vx = V2[3]; vy = V2[4]; vz = V2[5];
  96731. distance = nx * vx + ny * vy + nz * vz;
  96732. if (distance < maxDistance) {
  96733. maxDistance = distance;
  96734. v2x = vx; v2y = vy; v2z = vz;
  96735. }
  96736. //vertex3;
  96737. vx = V2[6]; vy = V2[7]; vz = V2[8];
  96738. distance = nx * vx + ny * vy + nz * vz;
  96739. if (distance < maxDistance) {
  96740. maxDistance = distance;
  96741. v2x = vx; v2y = vy; v2z = vz;
  96742. }
  96743. //vertex4;
  96744. vx = V2[9]; vy = V2[10]; vz = V2[11];
  96745. distance = nx * vx + ny * vy + nz * vz;
  96746. if (distance < maxDistance) {
  96747. maxDistance = distance;
  96748. v2x = vx; v2y = vy; v2z = vz;
  96749. }
  96750. //vertex5;
  96751. vx = V2[12]; vy = V2[13]; vz = V2[14];
  96752. distance = nx * vx + ny * vy + nz * vz;
  96753. if (distance < maxDistance) {
  96754. maxDistance = distance;
  96755. v2x = vx; v2y = vy; v2z = vz;
  96756. }
  96757. //vertex6;
  96758. vx = V2[15]; vy = V2[16]; vz = V2[17];
  96759. distance = nx * vx + ny * vy + nz * vz;
  96760. if (distance < maxDistance) {
  96761. maxDistance = distance;
  96762. v2x = vx; v2y = vy; v2z = vz;
  96763. }
  96764. //vertex7;
  96765. vx = V2[18]; vy = V2[19]; vz = V2[20];
  96766. distance = nx * vx + ny * vy + nz * vz;
  96767. if (distance < maxDistance) {
  96768. maxDistance = distance;
  96769. v2x = vx; v2y = vy; v2z = vz;
  96770. }
  96771. //vertex8;
  96772. vx = V2[21]; vy = V2[22]; vz = V2[23];
  96773. distance = nx * vx + ny * vy + nz * vz;
  96774. if (distance < maxDistance) {
  96775. maxDistance = distance;
  96776. v2x = vx; v2y = vy; v2z = vz;
  96777. }
  96778. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  96779. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  96780. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  96781. 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);
  96782. return;
  96783. }
  96784. // now detect face-face collision...
  96785. // target quad
  96786. var q1x;
  96787. var q1y;
  96788. var q1z;
  96789. var q2x;
  96790. var q2y;
  96791. var q2z;
  96792. var q3x;
  96793. var q3y;
  96794. var q3z;
  96795. var q4x;
  96796. var q4y;
  96797. var q4z;
  96798. // search support face and vertex
  96799. var minDot = 1;
  96800. var dot = 0;
  96801. var minDotIndex = 0;
  96802. if (swap) {
  96803. dot = a1x * nx + a1y * ny + a1z * nz;
  96804. if (dot < minDot) {
  96805. minDot = dot;
  96806. minDotIndex = 0;
  96807. }
  96808. if (-dot < minDot) {
  96809. minDot = -dot;
  96810. minDotIndex = 1;
  96811. }
  96812. dot = a2x * nx + a2y * ny + a2z * nz;
  96813. if (dot < minDot) {
  96814. minDot = dot;
  96815. minDotIndex = 2;
  96816. }
  96817. if (-dot < minDot) {
  96818. minDot = -dot;
  96819. minDotIndex = 3;
  96820. }
  96821. dot = a3x * nx + a3y * ny + a3z * nz;
  96822. if (dot < minDot) {
  96823. minDot = dot;
  96824. minDotIndex = 4;
  96825. }
  96826. if (-dot < minDot) {
  96827. minDot = -dot;
  96828. minDotIndex = 5;
  96829. }
  96830. if (minDotIndex == 0) {// x+ face
  96831. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  96832. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  96833. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  96834. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  96835. }
  96836. else if (minDotIndex == 1) {// x- face
  96837. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  96838. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  96839. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  96840. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  96841. }
  96842. else if (minDotIndex == 2) {// y+ face
  96843. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  96844. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  96845. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  96846. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  96847. }
  96848. else if (minDotIndex == 3) {// y- face
  96849. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  96850. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  96851. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  96852. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  96853. }
  96854. else if (minDotIndex == 4) {// z+ face
  96855. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  96856. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  96857. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  96858. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  96859. }
  96860. else if (minDotIndex == 5) {// z- face
  96861. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  96862. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  96863. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  96864. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  96865. }
  96866. } else {
  96867. dot = a4x * nx + a4y * ny + a4z * nz;
  96868. if (dot < minDot) {
  96869. minDot = dot;
  96870. minDotIndex = 0;
  96871. }
  96872. if (-dot < minDot) {
  96873. minDot = -dot;
  96874. minDotIndex = 1;
  96875. }
  96876. dot = a5x * nx + a5y * ny + a5z * nz;
  96877. if (dot < minDot) {
  96878. minDot = dot;
  96879. minDotIndex = 2;
  96880. }
  96881. if (-dot < minDot) {
  96882. minDot = -dot;
  96883. minDotIndex = 3;
  96884. }
  96885. dot = a6x * nx + a6y * ny + a6z * nz;
  96886. if (dot < minDot) {
  96887. minDot = dot;
  96888. minDotIndex = 4;
  96889. }
  96890. if (-dot < minDot) {
  96891. minDot = -dot;
  96892. minDotIndex = 5;
  96893. }
  96894. //______________________________________________________
  96895. if (minDotIndex == 0) {// x+ face
  96896. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  96897. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  96898. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  96899. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  96900. }
  96901. else if (minDotIndex == 1) {// x- face
  96902. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  96903. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  96904. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  96905. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  96906. }
  96907. else if (minDotIndex == 2) {// y+ face
  96908. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  96909. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  96910. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  96911. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  96912. }
  96913. else if (minDotIndex == 3) {// y- face
  96914. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  96915. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  96916. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  96917. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  96918. }
  96919. else if (minDotIndex == 4) {// z+ face
  96920. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  96921. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  96922. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  96923. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  96924. }
  96925. else if (minDotIndex == 5) {// z- face
  96926. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  96927. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  96928. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  96929. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  96930. }
  96931. }
  96932. // clip vertices
  96933. var numClipVertices;
  96934. var numAddedClipVertices;
  96935. var index;
  96936. var x1;
  96937. var y1;
  96938. var z1;
  96939. var x2;
  96940. var y2;
  96941. var z2;
  96942. this.clipVertices1[0] = q1x;
  96943. this.clipVertices1[1] = q1y;
  96944. this.clipVertices1[2] = q1z;
  96945. this.clipVertices1[3] = q2x;
  96946. this.clipVertices1[4] = q2y;
  96947. this.clipVertices1[5] = q2z;
  96948. this.clipVertices1[6] = q3x;
  96949. this.clipVertices1[7] = q3y;
  96950. this.clipVertices1[8] = q3z;
  96951. this.clipVertices1[9] = q4x;
  96952. this.clipVertices1[10] = q4y;
  96953. this.clipVertices1[11] = q4z;
  96954. numAddedClipVertices = 0;
  96955. x1 = this.clipVertices1[9];
  96956. y1 = this.clipVertices1[10];
  96957. z1 = this.clipVertices1[11];
  96958. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  96959. //var i = 4;
  96960. //while(i--){
  96961. for (var i = 0; i < 4; i++) {
  96962. index = i * 3;
  96963. x2 = this.clipVertices1[index];
  96964. y2 = this.clipVertices1[index + 1];
  96965. z2 = this.clipVertices1[index + 2];
  96966. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  96967. if (dot1 > 0) {
  96968. if (dot2 > 0) {
  96969. index = numAddedClipVertices * 3;
  96970. numAddedClipVertices++;
  96971. this.clipVertices2[index] = x2;
  96972. this.clipVertices2[index + 1] = y2;
  96973. this.clipVertices2[index + 2] = z2;
  96974. } else {
  96975. index = numAddedClipVertices * 3;
  96976. numAddedClipVertices++;
  96977. t = dot1 / (dot1 - dot2);
  96978. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  96979. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  96980. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  96981. }
  96982. } else {
  96983. if (dot2 > 0) {
  96984. index = numAddedClipVertices * 3;
  96985. numAddedClipVertices++;
  96986. t = dot1 / (dot1 - dot2);
  96987. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  96988. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  96989. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  96990. index = numAddedClipVertices * 3;
  96991. numAddedClipVertices++;
  96992. this.clipVertices2[index] = x2;
  96993. this.clipVertices2[index + 1] = y2;
  96994. this.clipVertices2[index + 2] = z2;
  96995. }
  96996. }
  96997. x1 = x2;
  96998. y1 = y2;
  96999. z1 = z2;
  97000. dot1 = dot2;
  97001. }
  97002. numClipVertices = numAddedClipVertices;
  97003. if (numClipVertices == 0) return;
  97004. numAddedClipVertices = 0;
  97005. index = (numClipVertices - 1) * 3;
  97006. x1 = this.clipVertices2[index];
  97007. y1 = this.clipVertices2[index + 1];
  97008. z1 = this.clipVertices2[index + 2];
  97009. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  97010. //i = numClipVertices;
  97011. //while(i--){
  97012. for (i = 0; i < numClipVertices; i++) {
  97013. index = i * 3;
  97014. x2 = this.clipVertices2[index];
  97015. y2 = this.clipVertices2[index + 1];
  97016. z2 = this.clipVertices2[index + 2];
  97017. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  97018. if (dot1 > 0) {
  97019. if (dot2 > 0) {
  97020. index = numAddedClipVertices * 3;
  97021. numAddedClipVertices++;
  97022. this.clipVertices1[index] = x2;
  97023. this.clipVertices1[index + 1] = y2;
  97024. this.clipVertices1[index + 2] = z2;
  97025. } else {
  97026. index = numAddedClipVertices * 3;
  97027. numAddedClipVertices++;
  97028. t = dot1 / (dot1 - dot2);
  97029. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97030. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97031. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97032. }
  97033. } else {
  97034. if (dot2 > 0) {
  97035. index = numAddedClipVertices * 3;
  97036. numAddedClipVertices++;
  97037. t = dot1 / (dot1 - dot2);
  97038. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97039. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97040. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97041. index = numAddedClipVertices * 3;
  97042. numAddedClipVertices++;
  97043. this.clipVertices1[index] = x2;
  97044. this.clipVertices1[index + 1] = y2;
  97045. this.clipVertices1[index + 2] = z2;
  97046. }
  97047. }
  97048. x1 = x2;
  97049. y1 = y2;
  97050. z1 = z2;
  97051. dot1 = dot2;
  97052. }
  97053. numClipVertices = numAddedClipVertices;
  97054. if (numClipVertices == 0) return;
  97055. numAddedClipVertices = 0;
  97056. index = (numClipVertices - 1) * 3;
  97057. x1 = this.clipVertices1[index];
  97058. y1 = this.clipVertices1[index + 1];
  97059. z1 = this.clipVertices1[index + 2];
  97060. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  97061. //i = numClipVertices;
  97062. //while(i--){
  97063. for (i = 0; i < numClipVertices; i++) {
  97064. index = i * 3;
  97065. x2 = this.clipVertices1[index];
  97066. y2 = this.clipVertices1[index + 1];
  97067. z2 = this.clipVertices1[index + 2];
  97068. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  97069. if (dot1 > 0) {
  97070. if (dot2 > 0) {
  97071. index = numAddedClipVertices * 3;
  97072. numAddedClipVertices++;
  97073. this.clipVertices2[index] = x2;
  97074. this.clipVertices2[index + 1] = y2;
  97075. this.clipVertices2[index + 2] = z2;
  97076. } else {
  97077. index = numAddedClipVertices * 3;
  97078. numAddedClipVertices++;
  97079. t = dot1 / (dot1 - dot2);
  97080. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  97081. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  97082. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  97083. }
  97084. } else {
  97085. if (dot2 > 0) {
  97086. index = numAddedClipVertices * 3;
  97087. numAddedClipVertices++;
  97088. t = dot1 / (dot1 - dot2);
  97089. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  97090. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  97091. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  97092. index = numAddedClipVertices * 3;
  97093. numAddedClipVertices++;
  97094. this.clipVertices2[index] = x2;
  97095. this.clipVertices2[index + 1] = y2;
  97096. this.clipVertices2[index + 2] = z2;
  97097. }
  97098. }
  97099. x1 = x2;
  97100. y1 = y2;
  97101. z1 = z2;
  97102. dot1 = dot2;
  97103. }
  97104. numClipVertices = numAddedClipVertices;
  97105. if (numClipVertices == 0) return;
  97106. numAddedClipVertices = 0;
  97107. index = (numClipVertices - 1) * 3;
  97108. x1 = this.clipVertices2[index];
  97109. y1 = this.clipVertices2[index + 1];
  97110. z1 = this.clipVertices2[index + 2];
  97111. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  97112. //i = numClipVertices;
  97113. //while(i--){
  97114. for (i = 0; i < numClipVertices; i++) {
  97115. index = i * 3;
  97116. x2 = this.clipVertices2[index];
  97117. y2 = this.clipVertices2[index + 1];
  97118. z2 = this.clipVertices2[index + 2];
  97119. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  97120. if (dot1 > 0) {
  97121. if (dot2 > 0) {
  97122. index = numAddedClipVertices * 3;
  97123. numAddedClipVertices++;
  97124. this.clipVertices1[index] = x2;
  97125. this.clipVertices1[index + 1] = y2;
  97126. this.clipVertices1[index + 2] = z2;
  97127. } else {
  97128. index = numAddedClipVertices * 3;
  97129. numAddedClipVertices++;
  97130. t = dot1 / (dot1 - dot2);
  97131. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97132. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97133. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97134. }
  97135. } else {
  97136. if (dot2 > 0) {
  97137. index = numAddedClipVertices * 3;
  97138. numAddedClipVertices++;
  97139. t = dot1 / (dot1 - dot2);
  97140. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97141. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97142. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97143. index = numAddedClipVertices * 3;
  97144. numAddedClipVertices++;
  97145. this.clipVertices1[index] = x2;
  97146. this.clipVertices1[index + 1] = y2;
  97147. this.clipVertices1[index + 2] = z2;
  97148. }
  97149. }
  97150. x1 = x2;
  97151. y1 = y2;
  97152. z1 = z2;
  97153. dot1 = dot2;
  97154. }
  97155. numClipVertices = numAddedClipVertices;
  97156. if (swap) {
  97157. var tb = b1;
  97158. b1 = b2;
  97159. b2 = tb;
  97160. }
  97161. if (numClipVertices == 0) return;
  97162. var flipped = b1 != shape1;
  97163. if (numClipVertices > 4) {
  97164. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  97165. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  97166. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  97167. n1x = q1x - x1;
  97168. n1y = q1y - y1;
  97169. n1z = q1z - z1;
  97170. n2x = q2x - x1;
  97171. n2y = q2y - y1;
  97172. n2z = q2z - z1;
  97173. var index1 = 0;
  97174. var index2 = 0;
  97175. var index3 = 0;
  97176. var index4 = 0;
  97177. var maxDot = -this.INF;
  97178. minDot = this.INF;
  97179. //i = numClipVertices;
  97180. //while(i--){
  97181. for (i = 0; i < numClipVertices; i++) {
  97182. this.used[i] = false;
  97183. index = i * 3;
  97184. x1 = this.clipVertices1[index];
  97185. y1 = this.clipVertices1[index + 1];
  97186. z1 = this.clipVertices1[index + 2];
  97187. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  97188. if (dot < minDot) {
  97189. minDot = dot;
  97190. index1 = i;
  97191. }
  97192. if (dot > maxDot) {
  97193. maxDot = dot;
  97194. index3 = i;
  97195. }
  97196. }
  97197. this.used[index1] = true;
  97198. this.used[index3] = true;
  97199. maxDot = -this.INF;
  97200. minDot = this.INF;
  97201. //i = numClipVertices;
  97202. //while(i--){
  97203. for (i = 0; i < numClipVertices; i++) {
  97204. if (this.used[i]) continue;
  97205. index = i * 3;
  97206. x1 = this.clipVertices1[index];
  97207. y1 = this.clipVertices1[index + 1];
  97208. z1 = this.clipVertices1[index + 2];
  97209. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  97210. if (dot < minDot) {
  97211. minDot = dot;
  97212. index2 = i;
  97213. }
  97214. if (dot > maxDot) {
  97215. maxDot = dot;
  97216. index4 = i;
  97217. }
  97218. }
  97219. index = index1 * 3;
  97220. x1 = this.clipVertices1[index];
  97221. y1 = this.clipVertices1[index + 1];
  97222. z1 = this.clipVertices1[index + 2];
  97223. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  97224. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  97225. index = index2 * 3;
  97226. x1 = this.clipVertices1[index];
  97227. y1 = this.clipVertices1[index + 1];
  97228. z1 = this.clipVertices1[index + 2];
  97229. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  97230. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  97231. index = index3 * 3;
  97232. x1 = this.clipVertices1[index];
  97233. y1 = this.clipVertices1[index + 1];
  97234. z1 = this.clipVertices1[index + 2];
  97235. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  97236. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  97237. index = index4 * 3;
  97238. x1 = this.clipVertices1[index];
  97239. y1 = this.clipVertices1[index + 1];
  97240. z1 = this.clipVertices1[index + 2];
  97241. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  97242. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  97243. } else {
  97244. //i = numClipVertices;
  97245. //while(i--){
  97246. for (i = 0; i < numClipVertices; i++) {
  97247. index = i * 3;
  97248. x1 = this.clipVertices1[index];
  97249. y1 = this.clipVertices1[index + 1];
  97250. z1 = this.clipVertices1[index + 2];
  97251. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  97252. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  97253. }
  97254. }
  97255. };
  97256. /**
  97257. * A collision detector which detects collisions between sphere and box.
  97258. * @author saharan
  97259. */
  97260. OIMO.SphereBoxCollisionDetector = function (flip) {
  97261. OIMO.CollisionDetector.call(this);
  97262. this.flip = flip;
  97263. };
  97264. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  97265. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  97266. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  97267. var s;
  97268. var b;
  97269. if (this.flip) {
  97270. s = (shape2);
  97271. b = (shape1);
  97272. } else {
  97273. s = (shape1);
  97274. b = (shape2);
  97275. }
  97276. var D = b.dimentions;
  97277. var ps = s.position;
  97278. var psx = ps.x;
  97279. var psy = ps.y;
  97280. var psz = ps.z;
  97281. var pb = b.position;
  97282. var pbx = pb.x;
  97283. var pby = pb.y;
  97284. var pbz = pb.z;
  97285. var rad = s.radius;
  97286. var hw = b.halfWidth;
  97287. var hh = b.halfHeight;
  97288. var hd = b.halfDepth;
  97289. var dx = psx - pbx;
  97290. var dy = psy - pby;
  97291. var dz = psz - pbz;
  97292. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  97293. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  97294. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  97295. var cx;
  97296. var cy;
  97297. var cz;
  97298. var len;
  97299. var invLen;
  97300. var overlap = 0;
  97301. if (sx > hw) {
  97302. sx = hw;
  97303. } else if (sx < -hw) {
  97304. sx = -hw;
  97305. } else {
  97306. overlap = 1;
  97307. }
  97308. if (sy > hh) {
  97309. sy = hh;
  97310. } else if (sy < -hh) {
  97311. sy = -hh;
  97312. } else {
  97313. overlap |= 2;
  97314. }
  97315. if (sz > hd) {
  97316. sz = hd;
  97317. } else if (sz < -hd) {
  97318. sz = -hd;
  97319. } else {
  97320. overlap |= 4;
  97321. }
  97322. if (overlap == 7) {
  97323. // center of sphere is in the box
  97324. if (sx < 0) {
  97325. dx = hw + sx;
  97326. } else {
  97327. dx = hw - sx;
  97328. }
  97329. if (sy < 0) {
  97330. dy = hh + sy;
  97331. } else {
  97332. dy = hh - sy;
  97333. }
  97334. if (sz < 0) {
  97335. dz = hd + sz;
  97336. } else {
  97337. dz = hd - sz;
  97338. }
  97339. if (dx < dy) {
  97340. if (dx < dz) {
  97341. len = dx - hw;
  97342. if (sx < 0) {
  97343. sx = -hw;
  97344. dx = D[0];
  97345. dy = D[1];
  97346. dz = D[2];
  97347. } else {
  97348. sx = hw;
  97349. dx = -D[0];
  97350. dy = -D[1];
  97351. dz = -D[2];
  97352. }
  97353. } else {
  97354. len = dz - hd;
  97355. if (sz < 0) {
  97356. sz = -hd;
  97357. dx = D[6];
  97358. dy = D[7];
  97359. dz = D[8];
  97360. } else {
  97361. sz = hd;
  97362. dx = -D[6];
  97363. dy = -D[7];
  97364. dz = -D[8];
  97365. }
  97366. }
  97367. } else {
  97368. if (dy < dz) {
  97369. len = dy - hh;
  97370. if (sy < 0) {
  97371. sy = -hh;
  97372. dx = D[3];
  97373. dy = D[4];
  97374. dz = D[5];
  97375. } else {
  97376. sy = hh;
  97377. dx = -D[3];
  97378. dy = -D[4];
  97379. dz = -D[5];
  97380. }
  97381. } else {
  97382. len = dz - hd;
  97383. if (sz < 0) {
  97384. sz = -hd;
  97385. dx = D[6];
  97386. dy = D[7];
  97387. dz = D[8];
  97388. } else {
  97389. sz = hd;
  97390. dx = -D[6];
  97391. dy = -D[7];
  97392. dz = -D[8];
  97393. }
  97394. }
  97395. }
  97396. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  97397. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  97398. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  97399. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  97400. } else {
  97401. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  97402. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  97403. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  97404. dx = cx - ps.x;
  97405. dy = cy - ps.y;
  97406. dz = cz - ps.z;
  97407. len = dx * dx + dy * dy + dz * dz;
  97408. if (len > 0 && len < rad * rad) {
  97409. len = OIMO.sqrt(len);
  97410. invLen = 1 / len;
  97411. dx *= invLen;
  97412. dy *= invLen;
  97413. dz *= invLen;
  97414. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  97415. }
  97416. }
  97417. };
  97418. /**
  97419. * A collision detector which detects collisions between two spheres.
  97420. * @author saharan
  97421. */
  97422. OIMO.SphereSphereCollisionDetector = function () {
  97423. OIMO.CollisionDetector.call(this);
  97424. };
  97425. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  97426. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  97427. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  97428. var s1 = shape1;
  97429. var s2 = shape2;
  97430. var p1 = s1.position;
  97431. var p2 = s2.position;
  97432. var dx = p2.x - p1.x;
  97433. var dy = p2.y - p1.y;
  97434. var dz = p2.z - p1.z;
  97435. var len = dx * dx + dy * dy + dz * dz;
  97436. var r1 = s1.radius;
  97437. var r2 = s2.radius;
  97438. var rad = r1 + r2;
  97439. if (len > 0 && len < rad * rad) {
  97440. len = OIMO.sqrt(len);
  97441. var invLen = 1 / len;
  97442. dx *= invLen;
  97443. dy *= invLen;
  97444. dz *= invLen;
  97445. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  97446. }
  97447. };
  97448. OIMO.BoxCylinderCollisionDetector = function (flip) {
  97449. OIMO.CollisionDetector.call(this);
  97450. this.flip = flip;
  97451. };
  97452. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  97453. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  97454. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  97455. var t1x;
  97456. var t1y;
  97457. var t1z;
  97458. var t2x;
  97459. var t2y;
  97460. var t2z;
  97461. var sup = new OIMO.Vec3();
  97462. var len;
  97463. var p1x;
  97464. var p1y;
  97465. var p1z;
  97466. var p2x;
  97467. var p2y;
  97468. var p2z;
  97469. var v01x = c1.position.x;
  97470. var v01y = c1.position.y;
  97471. var v01z = c1.position.z;
  97472. var v02x = c2.position.x;
  97473. var v02y = c2.position.y;
  97474. var v02z = c2.position.z;
  97475. var v0x = v02x - v01x;
  97476. var v0y = v02y - v01y;
  97477. var v0z = v02z - v01z;
  97478. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  97479. var nx = -v0x;
  97480. var ny = -v0y;
  97481. var nz = -v0z;
  97482. this.supportPointB(c1, -nx, -ny, -nz, sup);
  97483. var v11x = sup.x;
  97484. var v11y = sup.y;
  97485. var v11z = sup.z;
  97486. this.supportPointC(c2, nx, ny, nz, sup);
  97487. var v12x = sup.x;
  97488. var v12y = sup.y;
  97489. var v12z = sup.z;
  97490. var v1x = v12x - v11x;
  97491. var v1y = v12y - v11y;
  97492. var v1z = v12z - v11z;
  97493. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  97494. return false;
  97495. }
  97496. nx = v1y * v0z - v1z * v0y;
  97497. ny = v1z * v0x - v1x * v0z;
  97498. nz = v1x * v0y - v1y * v0x;
  97499. if (nx * nx + ny * ny + nz * nz == 0) {
  97500. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  97501. sep.normalize(sep);
  97502. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  97503. return true;
  97504. }
  97505. this.supportPointB(c1, -nx, -ny, -nz, sup);
  97506. var v21x = sup.x;
  97507. var v21y = sup.y;
  97508. var v21z = sup.z;
  97509. this.supportPointC(c2, nx, ny, nz, sup);
  97510. var v22x = sup.x;
  97511. var v22y = sup.y;
  97512. var v22z = sup.z;
  97513. var v2x = v22x - v21x;
  97514. var v2y = v22y - v21y;
  97515. var v2z = v22z - v21z;
  97516. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  97517. return false;
  97518. }
  97519. t1x = v1x - v0x;
  97520. t1y = v1y - v0y;
  97521. t1z = v1z - v0z;
  97522. t2x = v2x - v0x;
  97523. t2y = v2y - v0y;
  97524. t2z = v2z - v0z;
  97525. nx = t1y * t2z - t1z * t2y;
  97526. ny = t1z * t2x - t1x * t2z;
  97527. nz = t1x * t2y - t1y * t2x;
  97528. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  97529. t1x = v1x;
  97530. t1y = v1y;
  97531. t1z = v1z;
  97532. v1x = v2x;
  97533. v1y = v2y;
  97534. v1z = v2z;
  97535. v2x = t1x;
  97536. v2y = t1y;
  97537. v2z = t1z;
  97538. t1x = v11x;
  97539. t1y = v11y;
  97540. t1z = v11z;
  97541. v11x = v21x;
  97542. v11y = v21y;
  97543. v11z = v21z;
  97544. v21x = t1x;
  97545. v21y = t1y;
  97546. v21z = t1z;
  97547. t1x = v12x;
  97548. t1y = v12y;
  97549. t1z = v12z;
  97550. v12x = v22x;
  97551. v12y = v22y;
  97552. v12z = v22z;
  97553. v22x = t1x;
  97554. v22y = t1y;
  97555. v22z = t1z;
  97556. nx = -nx;
  97557. ny = -ny;
  97558. nz = -nz;
  97559. }
  97560. var iterations = 0;
  97561. while (true) {
  97562. if (++iterations > 100) {
  97563. return false;
  97564. }
  97565. this.supportPointB(c1, -nx, -ny, -nz, sup);
  97566. var v31x = sup.x;
  97567. var v31y = sup.y;
  97568. var v31z = sup.z;
  97569. this.supportPointC(c2, nx, ny, nz, sup);
  97570. var v32x = sup.x;
  97571. var v32y = sup.y;
  97572. var v32z = sup.z;
  97573. var v3x = v32x - v31x;
  97574. var v3y = v32y - v31y;
  97575. var v3z = v32z - v31z;
  97576. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  97577. return false;
  97578. }
  97579. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  97580. v2x = v3x;
  97581. v2y = v3y;
  97582. v2z = v3z;
  97583. v21x = v31x;
  97584. v21y = v31y;
  97585. v21z = v31z;
  97586. v22x = v32x;
  97587. v22y = v32y;
  97588. v22z = v32z;
  97589. t1x = v1x - v0x;
  97590. t1y = v1y - v0y;
  97591. t1z = v1z - v0z;
  97592. t2x = v3x - v0x;
  97593. t2y = v3y - v0y;
  97594. t2z = v3z - v0z;
  97595. nx = t1y * t2z - t1z * t2y;
  97596. ny = t1z * t2x - t1x * t2z;
  97597. nz = t1x * t2y - t1y * t2x;
  97598. continue;
  97599. }
  97600. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  97601. v1x = v3x;
  97602. v1y = v3y;
  97603. v1z = v3z;
  97604. v11x = v31x;
  97605. v11y = v31y;
  97606. v11z = v31z;
  97607. v12x = v32x;
  97608. v12y = v32y;
  97609. v12z = v32z;
  97610. t1x = v3x - v0x;
  97611. t1y = v3y - v0y;
  97612. t1z = v3z - v0z;
  97613. t2x = v2x - v0x;
  97614. t2y = v2y - v0y;
  97615. t2z = v2z - v0z;
  97616. nx = t1y * t2z - t1z * t2y;
  97617. ny = t1z * t2x - t1x * t2z;
  97618. nz = t1x * t2y - t1y * t2x;
  97619. continue;
  97620. }
  97621. var hit = false;
  97622. while (true) {
  97623. t1x = v2x - v1x;
  97624. t1y = v2y - v1y;
  97625. t1z = v2z - v1z;
  97626. t2x = v3x - v1x;
  97627. t2y = v3y - v1y;
  97628. t2z = v3z - v1z;
  97629. nx = t1y * t2z - t1z * t2y;
  97630. ny = t1z * t2x - t1x * t2z;
  97631. nz = t1x * t2y - t1y * t2x;
  97632. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  97633. nx *= len;
  97634. ny *= len;
  97635. nz *= len;
  97636. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  97637. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  97638. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  97639. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  97640. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  97641. var sum = b0 + b1 + b2 + b3;
  97642. if (sum <= 0) {
  97643. b0 = 0;
  97644. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  97645. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  97646. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  97647. sum = b1 + b2 + b3;
  97648. }
  97649. var inv = 1 / sum;
  97650. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  97651. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  97652. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  97653. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  97654. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  97655. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  97656. hit = true;
  97657. }
  97658. this.supportPointB(c1, -nx, -ny, -nz, sup);
  97659. var v41x = sup.x;
  97660. var v41y = sup.y;
  97661. var v41z = sup.z;
  97662. this.supportPointC(c2, nx, ny, nz, sup);
  97663. var v42x = sup.x;
  97664. var v42y = sup.y;
  97665. var v42z = sup.z;
  97666. var v4x = v42x - v41x;
  97667. var v4y = v42y - v41y;
  97668. var v4z = v42z - v41z;
  97669. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  97670. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  97671. if (hit) {
  97672. sep.init(-nx, -ny, -nz);
  97673. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  97674. dep.x = separation;
  97675. return true;
  97676. }
  97677. return false;
  97678. }
  97679. if (
  97680. (v4y * v1z - v4z * v1y) * v0x +
  97681. (v4z * v1x - v4x * v1z) * v0y +
  97682. (v4x * v1y - v4y * v1x) * v0z < 0
  97683. ) {
  97684. if (
  97685. (v4y * v2z - v4z * v2y) * v0x +
  97686. (v4z * v2x - v4x * v2z) * v0y +
  97687. (v4x * v2y - v4y * v2x) * v0z < 0
  97688. ) {
  97689. v1x = v4x;
  97690. v1y = v4y;
  97691. v1z = v4z;
  97692. v11x = v41x;
  97693. v11y = v41y;
  97694. v11z = v41z;
  97695. v12x = v42x;
  97696. v12y = v42y;
  97697. v12z = v42z;
  97698. } else {
  97699. v3x = v4x;
  97700. v3y = v4y;
  97701. v3z = v4z;
  97702. v31x = v41x;
  97703. v31y = v41y;
  97704. v31z = v41z;
  97705. v32x = v42x;
  97706. v32y = v42y;
  97707. v32z = v42z;
  97708. }
  97709. } else {
  97710. if (
  97711. (v4y * v3z - v4z * v3y) * v0x +
  97712. (v4z * v3x - v4x * v3z) * v0y +
  97713. (v4x * v3y - v4y * v3x) * v0z < 0
  97714. ) {
  97715. v2x = v4x;
  97716. v2y = v4y;
  97717. v2z = v4z;
  97718. v21x = v41x;
  97719. v21y = v41y;
  97720. v21z = v41z;
  97721. v22x = v42x;
  97722. v22y = v42y;
  97723. v22z = v42z;
  97724. } else {
  97725. v1x = v4x;
  97726. v1y = v4y;
  97727. v1z = v4z;
  97728. v11x = v41x;
  97729. v11y = v41y;
  97730. v11z = v41z;
  97731. v12x = v42x;
  97732. v12y = v42y;
  97733. v12z = v42z;
  97734. }
  97735. }
  97736. }
  97737. }
  97738. //return false;
  97739. };
  97740. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  97741. var rot = c.rotation.elements;
  97742. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  97743. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  97744. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  97745. var w = c.halfWidth;
  97746. var h = c.halfHeight;
  97747. var d = c.halfDepth;
  97748. var ox;
  97749. var oy;
  97750. var oz;
  97751. if (ldx < 0) ox = -w;
  97752. else ox = w;
  97753. if (ldy < 0) oy = -h;
  97754. else oy = h;
  97755. if (ldz < 0) oz = -d;
  97756. else oz = d;
  97757. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  97758. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  97759. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  97760. out.init(ldx, ldy, ldz);
  97761. };
  97762. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  97763. var rot = c.rotation.elements;
  97764. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  97765. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  97766. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  97767. var radx = ldx;
  97768. var radz = ldz;
  97769. var len = radx * radx + radz * radz;
  97770. var rad = c.radius;
  97771. var hh = c.halfHeight;
  97772. var ox;
  97773. var oy;
  97774. var oz;
  97775. if (len == 0) {
  97776. if (ldy < 0) {
  97777. ox = rad;
  97778. oy = -hh;
  97779. oz = 0;
  97780. } else {
  97781. ox = rad;
  97782. oy = hh;
  97783. oz = 0;
  97784. }
  97785. } else {
  97786. len = c.radius / OIMO.sqrt(len);
  97787. if (ldy < 0) {
  97788. ox = radx * len;
  97789. oy = -hh;
  97790. oz = radz * len;
  97791. } else {
  97792. ox = radx * len;
  97793. oy = hh;
  97794. oz = radz * len;
  97795. }
  97796. }
  97797. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  97798. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  97799. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  97800. out.init(ldx, ldy, ldz);
  97801. };
  97802. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  97803. var b;
  97804. var c;
  97805. if (this.flip) {
  97806. b = shape2;
  97807. c = shape1;
  97808. } else {
  97809. b = shape1;
  97810. c = shape2;
  97811. }
  97812. var sep = new OIMO.Vec3();
  97813. var pos = new OIMO.Vec3();
  97814. var dep = new OIMO.Vec3();
  97815. var co;
  97816. if (!this.getSep(b, c, sep, pos, dep)) return;
  97817. var pbx = b.position.x;
  97818. var pby = b.position.y;
  97819. var pbz = b.position.z;
  97820. var pcx = c.position.x;
  97821. var pcy = c.position.y;
  97822. var pcz = c.position.z;
  97823. var bw = b.halfWidth;
  97824. var bh = b.halfHeight;
  97825. var bd = b.halfDepth;
  97826. var ch = c.halfHeight;
  97827. var r = c.radius;
  97828. var D = b.dimentions;
  97829. var nwx = D[0];//b.normalDirectionWidth.x;
  97830. var nwy = D[1];//b.normalDirectionWidth.y;
  97831. var nwz = D[2];//b.normalDirectionWidth.z;
  97832. var nhx = D[3];//b.normalDirectionHeight.x;
  97833. var nhy = D[4];//b.normalDirectionHeight.y;
  97834. var nhz = D[5];//b.normalDirectionHeight.z;
  97835. var ndx = D[6];//b.normalDirectionDepth.x;
  97836. var ndy = D[7];//b.normalDirectionDepth.y;
  97837. var ndz = D[8];//b.normalDirectionDepth.z;
  97838. var dwx = D[9];//b.halfDirectionWidth.x;
  97839. var dwy = D[10];//b.halfDirectionWidth.y;
  97840. var dwz = D[11];//b.halfDirectionWidth.z;
  97841. var dhx = D[12];//b.halfDirectionHeight.x;
  97842. var dhy = D[13];//b.halfDirectionHeight.y;
  97843. var dhz = D[14];//b.halfDirectionHeight.z;
  97844. var ddx = D[15];//b.halfDirectionDepth.x;
  97845. var ddy = D[16];//b.halfDirectionDepth.y;
  97846. var ddz = D[17];//b.halfDirectionDepth.z;
  97847. var ncx = c.normalDirection.x;
  97848. var ncy = c.normalDirection.y;
  97849. var ncz = c.normalDirection.z;
  97850. var dcx = c.halfDirection.x;
  97851. var dcy = c.halfDirection.y;
  97852. var dcz = c.halfDirection.z;
  97853. var nx = sep.x;
  97854. var ny = sep.y;
  97855. var nz = sep.z;
  97856. var dotw = nx * nwx + ny * nwy + nz * nwz;
  97857. var doth = nx * nhx + ny * nhy + nz * nhz;
  97858. var dotd = nx * ndx + ny * ndy + nz * ndz;
  97859. var dotc = nx * ncx + ny * ncy + nz * ncz;
  97860. var right1 = dotw > 0;
  97861. var right2 = doth > 0;
  97862. var right3 = dotd > 0;
  97863. var right4 = dotc > 0;
  97864. if (!right1) dotw = -dotw;
  97865. if (!right2) doth = -doth;
  97866. if (!right3) dotd = -dotd;
  97867. if (!right4) dotc = -dotc;
  97868. var state = 0;
  97869. if (dotc > 0.999) {
  97870. if (dotw > 0.999) {
  97871. if (dotw > dotc) state = 1;
  97872. else state = 4;
  97873. } else if (doth > 0.999) {
  97874. if (doth > dotc) state = 2;
  97875. else state = 4;
  97876. } else if (dotd > 0.999) {
  97877. if (dotd > dotc) state = 3;
  97878. else state = 4;
  97879. } else state = 4;
  97880. } else {
  97881. if (dotw > 0.999) state = 1;
  97882. else if (doth > 0.999) state = 2;
  97883. else if (dotd > 0.999) state = 3;
  97884. }
  97885. var cbx;
  97886. var cby;
  97887. var cbz;
  97888. var ccx;
  97889. var ccy;
  97890. var ccz;
  97891. var r00;
  97892. var r01;
  97893. var r02;
  97894. var r10;
  97895. var r11;
  97896. var r12;
  97897. var r20;
  97898. var r21;
  97899. var r22;
  97900. var px;
  97901. var py;
  97902. var pz;
  97903. var pd;
  97904. var dot;
  97905. var len;
  97906. var tx;
  97907. var ty;
  97908. var tz;
  97909. var td;
  97910. var dx;
  97911. var dy;
  97912. var dz;
  97913. var d1x;
  97914. var d1y;
  97915. var d1z;
  97916. var d2x;
  97917. var d2y;
  97918. var d2z;
  97919. var sx;
  97920. var sy;
  97921. var sz;
  97922. var sd;
  97923. var ex;
  97924. var ey;
  97925. var ez;
  97926. var ed;
  97927. var dot1;
  97928. var dot2;
  97929. var t1;
  97930. var t2;
  97931. var dir1x;
  97932. var dir1y;
  97933. var dir1z;
  97934. var dir2x;
  97935. var dir2y;
  97936. var dir2z;
  97937. var dir1l;
  97938. var dir2l;
  97939. if (state == 0) {
  97940. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  97941. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  97942. } else if (state == 4) {
  97943. if (right4) {
  97944. ccx = pcx - dcx;
  97945. ccy = pcy - dcy;
  97946. ccz = pcz - dcz;
  97947. nx = -ncx;
  97948. ny = -ncy;
  97949. nz = -ncz;
  97950. } else {
  97951. ccx = pcx + dcx;
  97952. ccy = pcy + dcy;
  97953. ccz = pcz + dcz;
  97954. nx = ncx;
  97955. ny = ncy;
  97956. nz = ncz;
  97957. }
  97958. var v1x;
  97959. var v1y;
  97960. var v1z;
  97961. var v2x;
  97962. var v2y;
  97963. var v2z;
  97964. var v3x;
  97965. var v3y;
  97966. var v3z;
  97967. var v4x;
  97968. var v4y;
  97969. var v4z;
  97970. dot = 1;
  97971. state = 0;
  97972. dot1 = nwx * nx + nwy * ny + nwz * nz;
  97973. if (dot1 < dot) {
  97974. dot = dot1;
  97975. state = 0;
  97976. }
  97977. if (-dot1 < dot) {
  97978. dot = -dot1;
  97979. state = 1;
  97980. }
  97981. dot1 = nhx * nx + nhy * ny + nhz * nz;
  97982. if (dot1 < dot) {
  97983. dot = dot1;
  97984. state = 2;
  97985. }
  97986. if (-dot1 < dot) {
  97987. dot = -dot1;
  97988. state = 3;
  97989. }
  97990. dot1 = ndx * nx + ndy * ny + ndz * nz;
  97991. if (dot1 < dot) {
  97992. dot = dot1;
  97993. state = 4;
  97994. }
  97995. if (-dot1 < dot) {
  97996. dot = -dot1;
  97997. state = 5;
  97998. }
  97999. var v = b.elements;
  98000. switch (state) {
  98001. case 0:
  98002. //v=b.vertex1;
  98003. v1x = v[0];//v.x;
  98004. v1y = v[1];//v.y;
  98005. v1z = v[2];//v.z;
  98006. //v=b.vertex3;
  98007. v2x = v[6];//v.x;
  98008. v2y = v[7];//v.y;
  98009. v2z = v[8];//v.z;
  98010. //v=b.vertex4;
  98011. v3x = v[9];//v.x;
  98012. v3y = v[10];//v.y;
  98013. v3z = v[11];//v.z;
  98014. //v=b.vertex2;
  98015. v4x = v[3];//v.x;
  98016. v4y = v[4];//v.y;
  98017. v4z = v[5];//v.z;
  98018. break;
  98019. case 1:
  98020. //v=b.vertex6;
  98021. v1x = v[15];//v.x;
  98022. v1y = v[16];//v.y;
  98023. v1z = v[17];//v.z;
  98024. //v=b.vertex8;
  98025. v2x = v[21];//v.x;
  98026. v2y = v[22];//v.y;
  98027. v2z = v[23];//v.z;
  98028. //v=b.vertex7;
  98029. v3x = v[18];//v.x;
  98030. v3y = v[19];//v.y;
  98031. v3z = v[20];//v.z;
  98032. //v=b.vertex5;
  98033. v4x = v[12];//v.x;
  98034. v4y = v[13];//v.y;
  98035. v4z = v[14];//v.z;
  98036. break;
  98037. case 2:
  98038. //v=b.vertex5;
  98039. v1x = v[12];//v.x;
  98040. v1y = v[13];//v.y;
  98041. v1z = v[14];//v.z;
  98042. //v=b.vertex1;
  98043. v2x = v[0];//v.x;
  98044. v2y = v[1];//v.y;
  98045. v2z = v[2];//v.z;
  98046. //v=b.vertex2;
  98047. v3x = v[3];//v.x;
  98048. v3y = v[4];//v.y;
  98049. v3z = v[5];//v.z;
  98050. //v=b.vertex6;
  98051. v4x = v[15];//v.x;
  98052. v4y = v[16];//v.y;
  98053. v4z = v[17];//v.z;
  98054. break;
  98055. case 3:
  98056. //v=b.vertex8;
  98057. v1x = v[21];//v.x;
  98058. v1y = v[22];//v.y;
  98059. v1z = v[23];//v.z;
  98060. //v=b.vertex4;
  98061. v2x = v[9];//v.x;
  98062. v2y = v[10];//v.y;
  98063. v2z = v[11];//v.z;
  98064. //v=b.vertex3;
  98065. v3x = v[6];//v.x;
  98066. v3y = v[7];//v.y;
  98067. v3z = v[8];//v.z;
  98068. //v=b.vertex7;
  98069. v4x = v[18];//v.x;
  98070. v4y = v[19];//v.y;
  98071. v4z = v[20];//v.z;
  98072. break;
  98073. case 4:
  98074. //v=b.vertex5;
  98075. v1x = v[12];//v.x;
  98076. v1y = v[13];//v.y;
  98077. v1z = v[14];//v.z;
  98078. //v=b.vertex7;
  98079. v2x = v[18];//v.x;
  98080. v2y = v[19];//v.y;
  98081. v2z = v[20];//v.z;
  98082. //v=b.vertex3;
  98083. v3x = v[6];//v.x;
  98084. v3y = v[7];//v.y;
  98085. v3z = v[8];//v.z;
  98086. //v=b.vertex1;
  98087. v4x = v[0];//v.x;
  98088. v4y = v[1];//v.y;
  98089. v4z = v[2];//v.z;
  98090. break;
  98091. case 5:
  98092. //v=b.vertex2;
  98093. v1x = v[3];//v.x;
  98094. v1y = v[4];//v.y;
  98095. v1z = v[5];//v.z;
  98096. //v=b.vertex4;
  98097. v2x = v[9];//v.x;
  98098. v2y = v[10];//v.y;
  98099. v2z = v[11];//v.z;
  98100. //v=b.vertex8;
  98101. v3x = v[21];//v.x;
  98102. v3y = v[22];//v.y;
  98103. v3z = v[23];//v.z;
  98104. //v=b.vertex6;
  98105. v4x = v[15];//v.x;
  98106. v4y = v[16];//v.y;
  98107. v4z = v[17];//v.z;
  98108. break;
  98109. }
  98110. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  98111. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  98112. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  98113. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  98114. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  98115. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  98116. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  98117. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  98118. } else {
  98119. switch (state) {
  98120. case 1:
  98121. if (right1) {
  98122. cbx = pbx + dwx;
  98123. cby = pby + dwy;
  98124. cbz = pbz + dwz;
  98125. nx = nwx;
  98126. ny = nwy;
  98127. nz = nwz;
  98128. } else {
  98129. cbx = pbx - dwx;
  98130. cby = pby - dwy;
  98131. cbz = pbz - dwz;
  98132. nx = -nwx;
  98133. ny = -nwy;
  98134. nz = -nwz;
  98135. }
  98136. dir1x = nhx;
  98137. dir1y = nhy;
  98138. dir1z = nhz;
  98139. dir1l = bh;
  98140. dir2x = ndx;
  98141. dir2y = ndy;
  98142. dir2z = ndz;
  98143. dir2l = bd;
  98144. break;
  98145. case 2:
  98146. if (right2) {
  98147. cbx = pbx + dhx;
  98148. cby = pby + dhy;
  98149. cbz = pbz + dhz;
  98150. nx = nhx;
  98151. ny = nhy;
  98152. nz = nhz;
  98153. } else {
  98154. cbx = pbx - dhx;
  98155. cby = pby - dhy;
  98156. cbz = pbz - dhz;
  98157. nx = -nhx;
  98158. ny = -nhy;
  98159. nz = -nhz;
  98160. }
  98161. dir1x = nwx;
  98162. dir1y = nwy;
  98163. dir1z = nwz;
  98164. dir1l = bw;
  98165. dir2x = ndx;
  98166. dir2y = ndy;
  98167. dir2z = ndz;
  98168. dir2l = bd;
  98169. break;
  98170. case 3:
  98171. if (right3) {
  98172. cbx = pbx + ddx;
  98173. cby = pby + ddy;
  98174. cbz = pbz + ddz;
  98175. nx = ndx;
  98176. ny = ndy;
  98177. nz = ndz;
  98178. } else {
  98179. cbx = pbx - ddx;
  98180. cby = pby - ddy;
  98181. cbz = pbz - ddz;
  98182. nx = -ndx;
  98183. ny = -ndy;
  98184. nz = -ndz;
  98185. }
  98186. dir1x = nwx;
  98187. dir1y = nwy;
  98188. dir1z = nwz;
  98189. dir1l = bw;
  98190. dir2x = nhx;
  98191. dir2y = nhy;
  98192. dir2z = nhz;
  98193. dir2l = bh;
  98194. break;
  98195. }
  98196. dot = nx * ncx + ny * ncy + nz * ncz;
  98197. if (dot < 0) len = ch;
  98198. else len = -ch;
  98199. ccx = pcx + len * ncx;
  98200. ccy = pcy + len * ncy;
  98201. ccz = pcz + len * ncz;
  98202. if (dotc >= 0.999999) {
  98203. tx = -ny;
  98204. ty = nz;
  98205. tz = nx;
  98206. } else {
  98207. tx = nx;
  98208. ty = ny;
  98209. tz = nz;
  98210. }
  98211. len = tx * ncx + ty * ncy + tz * ncz;
  98212. dx = len * ncx - tx;
  98213. dy = len * ncy - ty;
  98214. dz = len * ncz - tz;
  98215. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  98216. if (len == 0) return;
  98217. len = r / len;
  98218. dx *= len;
  98219. dy *= len;
  98220. dz *= len;
  98221. tx = ccx + dx;
  98222. ty = ccy + dy;
  98223. tz = ccz + dz;
  98224. if (dot < -0.96 || dot > 0.96) {
  98225. r00 = ncx * ncx * 1.5 - 0.5;
  98226. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  98227. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  98228. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  98229. r11 = ncy * ncy * 1.5 - 0.5;
  98230. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  98231. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  98232. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  98233. r22 = ncz * ncz * 1.5 - 0.5;
  98234. px = tx;
  98235. py = ty;
  98236. pz = tz;
  98237. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  98238. tx = px - pd * nx - cbx;
  98239. ty = py - pd * ny - cby;
  98240. tz = pz - pd * nz - cbz;
  98241. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  98242. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  98243. if (sd < -dir1l) sd = -dir1l;
  98244. else if (sd > dir1l) sd = dir1l;
  98245. if (ed < -dir2l) ed = -dir2l;
  98246. else if (ed > dir2l) ed = dir2l;
  98247. tx = sd * dir1x + ed * dir2x;
  98248. ty = sd * dir1y + ed * dir2y;
  98249. tz = sd * dir1z + ed * dir2z;
  98250. px = cbx + tx;
  98251. py = cby + ty;
  98252. pz = cbz + tz;
  98253. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  98254. px = dx * r00 + dy * r01 + dz * r02;
  98255. py = dx * r10 + dy * r11 + dz * r12;
  98256. pz = dx * r20 + dy * r21 + dz * r22;
  98257. px = (dx = px) + ccx;
  98258. py = (dy = py) + ccy;
  98259. pz = (dz = pz) + ccz;
  98260. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  98261. if (pd <= 0) {
  98262. tx = px - pd * nx - cbx;
  98263. ty = py - pd * ny - cby;
  98264. tz = pz - pd * nz - cbz;
  98265. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  98266. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  98267. if (sd < -dir1l) sd = -dir1l;
  98268. else if (sd > dir1l) sd = dir1l;
  98269. if (ed < -dir2l) ed = -dir2l;
  98270. else if (ed > dir2l) ed = dir2l;
  98271. tx = sd * dir1x + ed * dir2x;
  98272. ty = sd * dir1y + ed * dir2y;
  98273. tz = sd * dir1z + ed * dir2z;
  98274. px = cbx + tx;
  98275. py = cby + ty;
  98276. pz = cbz + tz;
  98277. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  98278. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  98279. }
  98280. px = dx * r00 + dy * r01 + dz * r02;
  98281. py = dx * r10 + dy * r11 + dz * r12;
  98282. pz = dx * r20 + dy * r21 + dz * r22;
  98283. px = (dx = px) + ccx;
  98284. py = (dy = py) + ccy;
  98285. pz = (dz = pz) + ccz;
  98286. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  98287. if (pd <= 0) {
  98288. tx = px - pd * nx - cbx;
  98289. ty = py - pd * ny - cby;
  98290. tz = pz - pd * nz - cbz;
  98291. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  98292. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  98293. if (sd < -dir1l) sd = -dir1l;
  98294. else if (sd > dir1l) sd = dir1l;
  98295. if (ed < -dir2l) ed = -dir2l;
  98296. else if (ed > dir2l) ed = dir2l;
  98297. tx = sd * dir1x + ed * dir2x;
  98298. ty = sd * dir1y + ed * dir2y;
  98299. tz = sd * dir1z + ed * dir2z;
  98300. px = cbx + tx;
  98301. py = cby + ty;
  98302. pz = cbz + tz;
  98303. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  98304. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  98305. }
  98306. } else {
  98307. sx = tx;
  98308. sy = ty;
  98309. sz = tz;
  98310. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  98311. sx -= sd * nx;
  98312. sy -= sd * ny;
  98313. sz -= sd * nz;
  98314. if (dot > 0) {
  98315. ex = tx + dcx * 2;
  98316. ey = ty + dcy * 2;
  98317. ez = tz + dcz * 2;
  98318. } else {
  98319. ex = tx - dcx * 2;
  98320. ey = ty - dcy * 2;
  98321. ez = tz - dcz * 2;
  98322. }
  98323. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  98324. ex -= ed * nx;
  98325. ey -= ed * ny;
  98326. ez -= ed * nz;
  98327. d1x = sx - cbx;
  98328. d1y = sy - cby;
  98329. d1z = sz - cbz;
  98330. d2x = ex - cbx;
  98331. d2y = ey - cby;
  98332. d2z = ez - cbz;
  98333. tx = ex - sx;
  98334. ty = ey - sy;
  98335. tz = ez - sz;
  98336. td = ed - sd;
  98337. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  98338. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  98339. dot1 = dotw - dir1l;
  98340. dot2 = doth - dir1l;
  98341. if (dot1 > 0) {
  98342. if (dot2 > 0) return;
  98343. t1 = dot1 / (dot1 - dot2);
  98344. sx = sx + tx * t1;
  98345. sy = sy + ty * t1;
  98346. sz = sz + tz * t1;
  98347. sd = sd + td * t1;
  98348. d1x = sx - cbx;
  98349. d1y = sy - cby;
  98350. d1z = sz - cbz;
  98351. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  98352. tx = ex - sx;
  98353. ty = ey - sy;
  98354. tz = ez - sz;
  98355. td = ed - sd;
  98356. } else if (dot2 > 0) {
  98357. t1 = dot1 / (dot1 - dot2);
  98358. ex = sx + tx * t1;
  98359. ey = sy + ty * t1;
  98360. ez = sz + tz * t1;
  98361. ed = sd + td * t1;
  98362. d2x = ex - cbx;
  98363. d2y = ey - cby;
  98364. d2z = ez - cbz;
  98365. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  98366. tx = ex - sx;
  98367. ty = ey - sy;
  98368. tz = ez - sz;
  98369. td = ed - sd;
  98370. }
  98371. dot1 = dotw + dir1l;
  98372. dot2 = doth + dir1l;
  98373. if (dot1 < 0) {
  98374. if (dot2 < 0) return;
  98375. t1 = dot1 / (dot1 - dot2);
  98376. sx = sx + tx * t1;
  98377. sy = sy + ty * t1;
  98378. sz = sz + tz * t1;
  98379. sd = sd + td * t1;
  98380. d1x = sx - cbx;
  98381. d1y = sy - cby;
  98382. d1z = sz - cbz;
  98383. tx = ex - sx;
  98384. ty = ey - sy;
  98385. tz = ez - sz;
  98386. td = ed - sd;
  98387. } else if (dot2 < 0) {
  98388. t1 = dot1 / (dot1 - dot2);
  98389. ex = sx + tx * t1;
  98390. ey = sy + ty * t1;
  98391. ez = sz + tz * t1;
  98392. ed = sd + td * t1;
  98393. d2x = ex - cbx;
  98394. d2y = ey - cby;
  98395. d2z = ez - cbz;
  98396. tx = ex - sx;
  98397. ty = ey - sy;
  98398. tz = ez - sz;
  98399. td = ed - sd;
  98400. }
  98401. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  98402. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  98403. dot1 = dotw - dir2l;
  98404. dot2 = doth - dir2l;
  98405. if (dot1 > 0) {
  98406. if (dot2 > 0) return;
  98407. t1 = dot1 / (dot1 - dot2);
  98408. sx = sx + tx * t1;
  98409. sy = sy + ty * t1;
  98410. sz = sz + tz * t1;
  98411. sd = sd + td * t1;
  98412. d1x = sx - cbx;
  98413. d1y = sy - cby;
  98414. d1z = sz - cbz;
  98415. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  98416. tx = ex - sx;
  98417. ty = ey - sy;
  98418. tz = ez - sz;
  98419. td = ed - sd;
  98420. } else if (dot2 > 0) {
  98421. t1 = dot1 / (dot1 - dot2);
  98422. ex = sx + tx * t1;
  98423. ey = sy + ty * t1;
  98424. ez = sz + tz * t1;
  98425. ed = sd + td * t1;
  98426. d2x = ex - cbx;
  98427. d2y = ey - cby;
  98428. d2z = ez - cbz;
  98429. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  98430. tx = ex - sx;
  98431. ty = ey - sy;
  98432. tz = ez - sz;
  98433. td = ed - sd;
  98434. }
  98435. dot1 = dotw + dir2l;
  98436. dot2 = doth + dir2l;
  98437. if (dot1 < 0) {
  98438. if (dot2 < 0) return;
  98439. t1 = dot1 / (dot1 - dot2);
  98440. sx = sx + tx * t1;
  98441. sy = sy + ty * t1;
  98442. sz = sz + tz * t1;
  98443. sd = sd + td * t1;
  98444. } else if (dot2 < 0) {
  98445. t1 = dot1 / (dot1 - dot2);
  98446. ex = sx + tx * t1;
  98447. ey = sy + ty * t1;
  98448. ez = sz + tz * t1;
  98449. ed = sd + td * t1;
  98450. }
  98451. if (sd < 0) {
  98452. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  98453. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  98454. }
  98455. if (ed < 0) {
  98456. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  98457. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  98458. }
  98459. }
  98460. }
  98461. };
  98462. OIMO.CylinderCylinderCollisionDetector = function () {
  98463. OIMO.CollisionDetector.call(this);
  98464. };
  98465. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  98466. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  98467. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  98468. var t1x;
  98469. var t1y;
  98470. var t1z;
  98471. var t2x;
  98472. var t2y;
  98473. var t2z;
  98474. var sup = new OIMO.Vec3();
  98475. var len;
  98476. var p1x;
  98477. var p1y;
  98478. var p1z;
  98479. var p2x;
  98480. var p2y;
  98481. var p2z;
  98482. var v01x = c1.position.x;
  98483. var v01y = c1.position.y;
  98484. var v01z = c1.position.z;
  98485. var v02x = c2.position.x;
  98486. var v02y = c2.position.y;
  98487. var v02z = c2.position.z;
  98488. var v0x = v02x - v01x;
  98489. var v0y = v02y - v01y;
  98490. var v0z = v02z - v01z;
  98491. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  98492. var nx = -v0x;
  98493. var ny = -v0y;
  98494. var nz = -v0z;
  98495. this.supportPoint(c1, -nx, -ny, -nz, sup);
  98496. var v11x = sup.x;
  98497. var v11y = sup.y;
  98498. var v11z = sup.z;
  98499. this.supportPoint(c2, nx, ny, nz, sup);
  98500. var v12x = sup.x;
  98501. var v12y = sup.y;
  98502. var v12z = sup.z;
  98503. var v1x = v12x - v11x;
  98504. var v1y = v12y - v11y;
  98505. var v1z = v12z - v11z;
  98506. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  98507. return false;
  98508. }
  98509. nx = v1y * v0z - v1z * v0y;
  98510. ny = v1z * v0x - v1x * v0z;
  98511. nz = v1x * v0y - v1y * v0x;
  98512. if (nx * nx + ny * ny + nz * nz == 0) {
  98513. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  98514. sep.normalize(sep);
  98515. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  98516. return true;
  98517. }
  98518. this.supportPoint(c1, -nx, -ny, -nz, sup);
  98519. var v21x = sup.x;
  98520. var v21y = sup.y;
  98521. var v21z = sup.z;
  98522. this.supportPoint(c2, nx, ny, nz, sup);
  98523. var v22x = sup.x;
  98524. var v22y = sup.y;
  98525. var v22z = sup.z;
  98526. var v2x = v22x - v21x;
  98527. var v2y = v22y - v21y;
  98528. var v2z = v22z - v21z;
  98529. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  98530. return false;
  98531. }
  98532. t1x = v1x - v0x;
  98533. t1y = v1y - v0y;
  98534. t1z = v1z - v0z;
  98535. t2x = v2x - v0x;
  98536. t2y = v2y - v0y;
  98537. t2z = v2z - v0z;
  98538. nx = t1y * t2z - t1z * t2y;
  98539. ny = t1z * t2x - t1x * t2z;
  98540. nz = t1x * t2y - t1y * t2x;
  98541. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  98542. t1x = v1x;
  98543. t1y = v1y;
  98544. t1z = v1z;
  98545. v1x = v2x;
  98546. v1y = v2y;
  98547. v1z = v2z;
  98548. v2x = t1x;
  98549. v2y = t1y;
  98550. v2z = t1z;
  98551. t1x = v11x;
  98552. t1y = v11y;
  98553. t1z = v11z;
  98554. v11x = v21x;
  98555. v11y = v21y;
  98556. v11z = v21z;
  98557. v21x = t1x;
  98558. v21y = t1y;
  98559. v21z = t1z;
  98560. t1x = v12x;
  98561. t1y = v12y;
  98562. t1z = v12z;
  98563. v12x = v22x;
  98564. v12y = v22y;
  98565. v12z = v22z;
  98566. v22x = t1x;
  98567. v22y = t1y;
  98568. v22z = t1z;
  98569. nx = -nx;
  98570. ny = -ny;
  98571. nz = -nz;
  98572. }
  98573. var iterations = 0;
  98574. while (true) {
  98575. if (++iterations > 100) {
  98576. return false;
  98577. }
  98578. this.supportPoint(c1, -nx, -ny, -nz, sup);
  98579. var v31x = sup.x;
  98580. var v31y = sup.y;
  98581. var v31z = sup.z;
  98582. this.supportPoint(c2, nx, ny, nz, sup);
  98583. var v32x = sup.x;
  98584. var v32y = sup.y;
  98585. var v32z = sup.z;
  98586. var v3x = v32x - v31x;
  98587. var v3y = v32y - v31y;
  98588. var v3z = v32z - v31z;
  98589. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  98590. return false;
  98591. }
  98592. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  98593. v2x = v3x;
  98594. v2y = v3y;
  98595. v2z = v3z;
  98596. v21x = v31x;
  98597. v21y = v31y;
  98598. v21z = v31z;
  98599. v22x = v32x;
  98600. v22y = v32y;
  98601. v22z = v32z;
  98602. t1x = v1x - v0x;
  98603. t1y = v1y - v0y;
  98604. t1z = v1z - v0z;
  98605. t2x = v3x - v0x;
  98606. t2y = v3y - v0y;
  98607. t2z = v3z - v0z;
  98608. nx = t1y * t2z - t1z * t2y;
  98609. ny = t1z * t2x - t1x * t2z;
  98610. nz = t1x * t2y - t1y * t2x;
  98611. continue;
  98612. }
  98613. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  98614. v1x = v3x;
  98615. v1y = v3y;
  98616. v1z = v3z;
  98617. v11x = v31x;
  98618. v11y = v31y;
  98619. v11z = v31z;
  98620. v12x = v32x;
  98621. v12y = v32y;
  98622. v12z = v32z;
  98623. t1x = v3x - v0x;
  98624. t1y = v3y - v0y;
  98625. t1z = v3z - v0z;
  98626. t2x = v2x - v0x;
  98627. t2y = v2y - v0y;
  98628. t2z = v2z - v0z;
  98629. nx = t1y * t2z - t1z * t2y;
  98630. ny = t1z * t2x - t1x * t2z;
  98631. nz = t1x * t2y - t1y * t2x;
  98632. continue;
  98633. }
  98634. var hit = false;
  98635. while (true) {
  98636. t1x = v2x - v1x;
  98637. t1y = v2y - v1y;
  98638. t1z = v2z - v1z;
  98639. t2x = v3x - v1x;
  98640. t2y = v3y - v1y;
  98641. t2z = v3z - v1z;
  98642. nx = t1y * t2z - t1z * t2y;
  98643. ny = t1z * t2x - t1x * t2z;
  98644. nz = t1x * t2y - t1y * t2x;
  98645. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  98646. nx *= len;
  98647. ny *= len;
  98648. nz *= len;
  98649. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  98650. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  98651. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  98652. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  98653. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  98654. var sum = b0 + b1 + b2 + b3;
  98655. if (sum <= 0) {
  98656. b0 = 0;
  98657. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  98658. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  98659. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  98660. sum = b1 + b2 + b3;
  98661. }
  98662. var inv = 1 / sum;
  98663. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  98664. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  98665. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  98666. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  98667. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  98668. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  98669. hit = true;
  98670. }
  98671. this.supportPoint(c1, -nx, -ny, -nz, sup);
  98672. var v41x = sup.x;
  98673. var v41y = sup.y;
  98674. var v41z = sup.z;
  98675. this.supportPoint(c2, nx, ny, nz, sup);
  98676. var v42x = sup.x;
  98677. var v42y = sup.y;
  98678. var v42z = sup.z;
  98679. var v4x = v42x - v41x;
  98680. var v4y = v42y - v41y;
  98681. var v4z = v42z - v41z;
  98682. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  98683. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  98684. if (hit) {
  98685. sep.init(-nx, -ny, -nz);
  98686. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  98687. dep.x = separation;
  98688. return true;
  98689. }
  98690. return false;
  98691. }
  98692. if (
  98693. (v4y * v1z - v4z * v1y) * v0x +
  98694. (v4z * v1x - v4x * v1z) * v0y +
  98695. (v4x * v1y - v4y * v1x) * v0z < 0
  98696. ) {
  98697. if (
  98698. (v4y * v2z - v4z * v2y) * v0x +
  98699. (v4z * v2x - v4x * v2z) * v0y +
  98700. (v4x * v2y - v4y * v2x) * v0z < 0
  98701. ) {
  98702. v1x = v4x;
  98703. v1y = v4y;
  98704. v1z = v4z;
  98705. v11x = v41x;
  98706. v11y = v41y;
  98707. v11z = v41z;
  98708. v12x = v42x;
  98709. v12y = v42y;
  98710. v12z = v42z;
  98711. } else {
  98712. v3x = v4x;
  98713. v3y = v4y;
  98714. v3z = v4z;
  98715. v31x = v41x;
  98716. v31y = v41y;
  98717. v31z = v41z;
  98718. v32x = v42x;
  98719. v32y = v42y;
  98720. v32z = v42z;
  98721. }
  98722. } else {
  98723. if (
  98724. (v4y * v3z - v4z * v3y) * v0x +
  98725. (v4z * v3x - v4x * v3z) * v0y +
  98726. (v4x * v3y - v4y * v3x) * v0z < 0
  98727. ) {
  98728. v2x = v4x;
  98729. v2y = v4y;
  98730. v2z = v4z;
  98731. v21x = v41x;
  98732. v21y = v41y;
  98733. v21z = v41z;
  98734. v22x = v42x;
  98735. v22y = v42y;
  98736. v22z = v42z;
  98737. } else {
  98738. v1x = v4x;
  98739. v1y = v4y;
  98740. v1z = v4z;
  98741. v11x = v41x;
  98742. v11y = v41y;
  98743. v11z = v41z;
  98744. v12x = v42x;
  98745. v12y = v42y;
  98746. v12z = v42z;
  98747. }
  98748. }
  98749. }
  98750. }
  98751. //return false;
  98752. };
  98753. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  98754. var rot = c.rotation.elements;
  98755. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  98756. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  98757. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  98758. var radx = ldx;
  98759. var radz = ldz;
  98760. var len = radx * radx + radz * radz;
  98761. var rad = c.radius;
  98762. var hh = c.halfHeight;
  98763. var ox;
  98764. var oy;
  98765. var oz;
  98766. if (len == 0) {
  98767. if (ldy < 0) {
  98768. ox = rad;
  98769. oy = -hh;
  98770. oz = 0;
  98771. } else {
  98772. ox = rad;
  98773. oy = hh;
  98774. oz = 0;
  98775. }
  98776. } else {
  98777. len = c.radius / OIMO.sqrt(len);
  98778. if (ldy < 0) {
  98779. ox = radx * len;
  98780. oy = -hh;
  98781. oz = radz * len;
  98782. } else {
  98783. ox = radx * len;
  98784. oy = hh;
  98785. oz = radz * len;
  98786. }
  98787. }
  98788. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  98789. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  98790. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  98791. out.init(ldx, ldy, ldz);
  98792. };
  98793. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  98794. var c1;
  98795. var c2;
  98796. if (shape1.id < shape2.id) {
  98797. c1 = shape1;
  98798. c2 = shape2;
  98799. } else {
  98800. c1 = shape2;
  98801. c2 = shape1;
  98802. }
  98803. var p1 = c1.position;
  98804. var p2 = c2.position;
  98805. var p1x = p1.x;
  98806. var p1y = p1.y;
  98807. var p1z = p1.z;
  98808. var p2x = p2.x;
  98809. var p2y = p2.y;
  98810. var p2z = p2.z;
  98811. var h1 = c1.halfHeight;
  98812. var h2 = c2.halfHeight;
  98813. var n1 = c1.normalDirection;
  98814. var n2 = c2.normalDirection;
  98815. var d1 = c1.halfDirection;
  98816. var d2 = c2.halfDirection;
  98817. var r1 = c1.radius;
  98818. var r2 = c2.radius;
  98819. var n1x = n1.x;
  98820. var n1y = n1.y;
  98821. var n1z = n1.z;
  98822. var n2x = n2.x;
  98823. var n2y = n2.y;
  98824. var n2z = n2.z;
  98825. var d1x = d1.x;
  98826. var d1y = d1.y;
  98827. var d1z = d1.z;
  98828. var d2x = d2.x;
  98829. var d2y = d2.y;
  98830. var d2z = d2.z;
  98831. var dx = p1x - p2x;
  98832. var dy = p1y - p2y;
  98833. var dz = p1z - p2z;
  98834. var len;
  98835. var len1;
  98836. var len2;
  98837. var c;
  98838. var c1x;
  98839. var c1y;
  98840. var c1z;
  98841. var c2x;
  98842. var c2y;
  98843. var c2z;
  98844. var tx;
  98845. var ty;
  98846. var tz;
  98847. var sx;
  98848. var sy;
  98849. var sz;
  98850. var ex;
  98851. var ey;
  98852. var ez;
  98853. var depth1;
  98854. var depth2;
  98855. var dot;
  98856. var t1;
  98857. var t2;
  98858. var sep = new OIMO.Vec3();
  98859. var pos = new OIMO.Vec3();
  98860. var dep = new OIMO.Vec3();
  98861. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  98862. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  98863. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  98864. var right1 = dot1 > 0;
  98865. var right2 = dot2 > 0;
  98866. if (!right1) dot1 = -dot1;
  98867. if (!right2) dot2 = -dot2;
  98868. var state = 0;
  98869. if (dot1 > 0.999 || dot2 > 0.999) {
  98870. if (dot1 > dot2) state = 1;
  98871. else state = 2;
  98872. }
  98873. var nx;
  98874. var ny;
  98875. var nz;
  98876. var depth = dep.x;
  98877. var r00;
  98878. var r01;
  98879. var r02;
  98880. var r10;
  98881. var r11;
  98882. var r12;
  98883. var r20;
  98884. var r21;
  98885. var r22;
  98886. var px;
  98887. var py;
  98888. var pz;
  98889. var pd;
  98890. var a;
  98891. var b;
  98892. var e;
  98893. var f;
  98894. nx = sep.x;
  98895. ny = sep.y;
  98896. nz = sep.z;
  98897. switch (state) {
  98898. case 0:
  98899. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  98900. break;
  98901. case 1:
  98902. if (right1) {
  98903. c1x = p1x + d1x;
  98904. c1y = p1y + d1y;
  98905. c1z = p1z + d1z;
  98906. nx = n1x;
  98907. ny = n1y;
  98908. nz = n1z;
  98909. } else {
  98910. c1x = p1x - d1x;
  98911. c1y = p1y - d1y;
  98912. c1z = p1z - d1z;
  98913. nx = -n1x;
  98914. ny = -n1y;
  98915. nz = -n1z;
  98916. }
  98917. dot = nx * n2x + ny * n2y + nz * n2z;
  98918. if (dot < 0) len = h2;
  98919. else len = -h2;
  98920. c2x = p2x + len * n2x;
  98921. c2y = p2y + len * n2y;
  98922. c2z = p2z + len * n2z;
  98923. if (dot2 >= 0.999999) {
  98924. tx = -ny;
  98925. ty = nz;
  98926. tz = nx;
  98927. } else {
  98928. tx = nx;
  98929. ty = ny;
  98930. tz = nz;
  98931. }
  98932. len = tx * n2x + ty * n2y + tz * n2z;
  98933. dx = len * n2x - tx;
  98934. dy = len * n2y - ty;
  98935. dz = len * n2z - tz;
  98936. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  98937. if (len == 0) break;
  98938. len = r2 / len;
  98939. dx *= len;
  98940. dy *= len;
  98941. dz *= len;
  98942. tx = c2x + dx;
  98943. ty = c2y + dy;
  98944. tz = c2z + dz;
  98945. if (dot < -0.96 || dot > 0.96) {
  98946. r00 = n2x * n2x * 1.5 - 0.5;
  98947. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  98948. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  98949. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  98950. r11 = n2y * n2y * 1.5 - 0.5;
  98951. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  98952. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  98953. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  98954. r22 = n2z * n2z * 1.5 - 0.5;
  98955. px = tx;
  98956. py = ty;
  98957. pz = tz;
  98958. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  98959. tx = px - pd * nx - c1x;
  98960. ty = py - pd * ny - c1y;
  98961. tz = pz - pd * nz - c1z;
  98962. len = tx * tx + ty * ty + tz * tz;
  98963. if (len > r1 * r1) {
  98964. len = r1 / OIMO.sqrt(len);
  98965. tx *= len;
  98966. ty *= len;
  98967. tz *= len;
  98968. }
  98969. px = c1x + tx;
  98970. py = c1y + ty;
  98971. pz = c1z + tz;
  98972. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  98973. px = dx * r00 + dy * r01 + dz * r02;
  98974. py = dx * r10 + dy * r11 + dz * r12;
  98975. pz = dx * r20 + dy * r21 + dz * r22;
  98976. px = (dx = px) + c2x;
  98977. py = (dy = py) + c2y;
  98978. pz = (dz = pz) + c2z;
  98979. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  98980. if (pd <= 0) {
  98981. tx = px - pd * nx - c1x;
  98982. ty = py - pd * ny - c1y;
  98983. tz = pz - pd * nz - c1z;
  98984. len = tx * tx + ty * ty + tz * tz;
  98985. if (len > r1 * r1) {
  98986. len = r1 / OIMO.sqrt(len);
  98987. tx *= len;
  98988. ty *= len;
  98989. tz *= len;
  98990. }
  98991. px = c1x + tx;
  98992. py = c1y + ty;
  98993. pz = c1z + tz;
  98994. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  98995. }
  98996. px = dx * r00 + dy * r01 + dz * r02;
  98997. py = dx * r10 + dy * r11 + dz * r12;
  98998. pz = dx * r20 + dy * r21 + dz * r22;
  98999. px = (dx = px) + c2x;
  99000. py = (dy = py) + c2y;
  99001. pz = (dz = pz) + c2z;
  99002. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  99003. if (pd <= 0) {
  99004. tx = px - pd * nx - c1x;
  99005. ty = py - pd * ny - c1y;
  99006. tz = pz - pd * nz - c1z;
  99007. len = tx * tx + ty * ty + tz * tz;
  99008. if (len > r1 * r1) {
  99009. len = r1 / OIMO.sqrt(len);
  99010. tx *= len;
  99011. ty *= len;
  99012. tz *= len;
  99013. }
  99014. px = c1x + tx;
  99015. py = c1y + ty;
  99016. pz = c1z + tz;
  99017. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  99018. }
  99019. } else {
  99020. sx = tx;
  99021. sy = ty;
  99022. sz = tz;
  99023. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  99024. sx -= depth1 * nx;
  99025. sy -= depth1 * ny;
  99026. sz -= depth1 * nz;
  99027. if (dot > 0) {
  99028. ex = tx + n2x * h2 * 2;
  99029. ey = ty + n2y * h2 * 2;
  99030. ez = tz + n2z * h2 * 2;
  99031. } else {
  99032. ex = tx - n2x * h2 * 2;
  99033. ey = ty - n2y * h2 * 2;
  99034. ez = tz - n2z * h2 * 2;
  99035. }
  99036. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  99037. ex -= depth2 * nx;
  99038. ey -= depth2 * ny;
  99039. ez -= depth2 * nz;
  99040. dx = c1x - sx;
  99041. dy = c1y - sy;
  99042. dz = c1z - sz;
  99043. tx = ex - sx;
  99044. ty = ey - sy;
  99045. tz = ez - sz;
  99046. a = dx * dx + dy * dy + dz * dz;
  99047. b = dx * tx + dy * ty + dz * tz;
  99048. e = tx * tx + ty * ty + tz * tz;
  99049. f = b * b - e * (a - r1 * r1);
  99050. if (f < 0) break;
  99051. f = OIMO.sqrt(f);
  99052. t1 = (b + f) / e;
  99053. t2 = (b - f) / e;
  99054. if (t2 < t1) {
  99055. len = t1;
  99056. t1 = t2;
  99057. t2 = len;
  99058. }
  99059. if (t2 > 1) t2 = 1;
  99060. if (t1 < 0) t1 = 0;
  99061. tx = sx + (ex - sx) * t1;
  99062. ty = sy + (ey - sy) * t1;
  99063. tz = sz + (ez - sz) * t1;
  99064. ex = sx + (ex - sx) * t2;
  99065. ey = sy + (ey - sy) * t2;
  99066. ez = sz + (ez - sz) * t2;
  99067. sx = tx;
  99068. sy = ty;
  99069. sz = tz;
  99070. len = depth1 + (depth2 - depth1) * t1;
  99071. depth2 = depth1 + (depth2 - depth1) * t2;
  99072. depth1 = len;
  99073. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  99074. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  99075. }
  99076. break;
  99077. case 2:
  99078. if (right2) {
  99079. c2x = p2x - d2x;
  99080. c2y = p2y - d2y;
  99081. c2z = p2z - d2z;
  99082. nx = -n2x;
  99083. ny = -n2y;
  99084. nz = -n2z;
  99085. } else {
  99086. c2x = p2x + d2x;
  99087. c2y = p2y + d2y;
  99088. c2z = p2z + d2z;
  99089. nx = n2x;
  99090. ny = n2y;
  99091. nz = n2z;
  99092. }
  99093. dot = nx * n1x + ny * n1y + nz * n1z;
  99094. if (dot < 0) len = h1;
  99095. else len = -h1;
  99096. c1x = p1x + len * n1x;
  99097. c1y = p1y + len * n1y;
  99098. c1z = p1z + len * n1z;
  99099. if (dot1 >= 0.999999) {
  99100. tx = -ny;
  99101. ty = nz;
  99102. tz = nx;
  99103. } else {
  99104. tx = nx;
  99105. ty = ny;
  99106. tz = nz;
  99107. }
  99108. len = tx * n1x + ty * n1y + tz * n1z;
  99109. dx = len * n1x - tx;
  99110. dy = len * n1y - ty;
  99111. dz = len * n1z - tz;
  99112. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  99113. if (len == 0) break;
  99114. len = r1 / len;
  99115. dx *= len;
  99116. dy *= len;
  99117. dz *= len;
  99118. tx = c1x + dx;
  99119. ty = c1y + dy;
  99120. tz = c1z + dz;
  99121. if (dot < -0.96 || dot > 0.96) {
  99122. r00 = n1x * n1x * 1.5 - 0.5;
  99123. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  99124. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  99125. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  99126. r11 = n1y * n1y * 1.5 - 0.5;
  99127. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  99128. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  99129. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  99130. r22 = n1z * n1z * 1.5 - 0.5;
  99131. px = tx;
  99132. py = ty;
  99133. pz = tz;
  99134. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  99135. tx = px - pd * nx - c2x;
  99136. ty = py - pd * ny - c2y;
  99137. tz = pz - pd * nz - c2z;
  99138. len = tx * tx + ty * ty + tz * tz;
  99139. if (len > r2 * r2) {
  99140. len = r2 / OIMO.sqrt(len);
  99141. tx *= len;
  99142. ty *= len;
  99143. tz *= len;
  99144. }
  99145. px = c2x + tx;
  99146. py = c2y + ty;
  99147. pz = c2z + tz;
  99148. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  99149. px = dx * r00 + dy * r01 + dz * r02;
  99150. py = dx * r10 + dy * r11 + dz * r12;
  99151. pz = dx * r20 + dy * r21 + dz * r22;
  99152. px = (dx = px) + c1x;
  99153. py = (dy = py) + c1y;
  99154. pz = (dz = pz) + c1z;
  99155. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  99156. if (pd <= 0) {
  99157. tx = px - pd * nx - c2x;
  99158. ty = py - pd * ny - c2y;
  99159. tz = pz - pd * nz - c2z;
  99160. len = tx * tx + ty * ty + tz * tz;
  99161. if (len > r2 * r2) {
  99162. len = r2 / OIMO.sqrt(len);
  99163. tx *= len;
  99164. ty *= len;
  99165. tz *= len;
  99166. }
  99167. px = c2x + tx;
  99168. py = c2y + ty;
  99169. pz = c2z + tz;
  99170. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  99171. }
  99172. px = dx * r00 + dy * r01 + dz * r02;
  99173. py = dx * r10 + dy * r11 + dz * r12;
  99174. pz = dx * r20 + dy * r21 + dz * r22;
  99175. px = (dx = px) + c1x;
  99176. py = (dy = py) + c1y;
  99177. pz = (dz = pz) + c1z;
  99178. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  99179. if (pd <= 0) {
  99180. tx = px - pd * nx - c2x;
  99181. ty = py - pd * ny - c2y;
  99182. tz = pz - pd * nz - c2z;
  99183. len = tx * tx + ty * ty + tz * tz;
  99184. if (len > r2 * r2) {
  99185. len = r2 / OIMO.sqrt(len);
  99186. tx *= len;
  99187. ty *= len;
  99188. tz *= len;
  99189. }
  99190. px = c2x + tx;
  99191. py = c2y + ty;
  99192. pz = c2z + tz;
  99193. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  99194. }
  99195. } else {
  99196. sx = tx;
  99197. sy = ty;
  99198. sz = tz;
  99199. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  99200. sx -= depth1 * nx;
  99201. sy -= depth1 * ny;
  99202. sz -= depth1 * nz;
  99203. if (dot > 0) {
  99204. ex = tx + n1x * h1 * 2;
  99205. ey = ty + n1y * h1 * 2;
  99206. ez = tz + n1z * h1 * 2;
  99207. } else {
  99208. ex = tx - n1x * h1 * 2;
  99209. ey = ty - n1y * h1 * 2;
  99210. ez = tz - n1z * h1 * 2;
  99211. }
  99212. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  99213. ex -= depth2 * nx;
  99214. ey -= depth2 * ny;
  99215. ez -= depth2 * nz;
  99216. dx = c2x - sx;
  99217. dy = c2y - sy;
  99218. dz = c2z - sz;
  99219. tx = ex - sx;
  99220. ty = ey - sy;
  99221. tz = ez - sz;
  99222. a = dx * dx + dy * dy + dz * dz;
  99223. b = dx * tx + dy * ty + dz * tz;
  99224. e = tx * tx + ty * ty + tz * tz;
  99225. f = b * b - e * (a - r2 * r2);
  99226. if (f < 0) break;
  99227. f = OIMO.sqrt(f);
  99228. t1 = (b + f) / e;
  99229. t2 = (b - f) / e;
  99230. if (t2 < t1) {
  99231. len = t1;
  99232. t1 = t2;
  99233. t2 = len;
  99234. }
  99235. if (t2 > 1) t2 = 1;
  99236. if (t1 < 0) t1 = 0;
  99237. tx = sx + (ex - sx) * t1;
  99238. ty = sy + (ey - sy) * t1;
  99239. tz = sz + (ez - sz) * t1;
  99240. ex = sx + (ex - sx) * t2;
  99241. ey = sy + (ey - sy) * t2;
  99242. ez = sz + (ez - sz) * t2;
  99243. sx = tx;
  99244. sy = ty;
  99245. sz = tz;
  99246. len = depth1 + (depth2 - depth1) * t1;
  99247. depth2 = depth1 + (depth2 - depth1) * t2;
  99248. depth1 = len;
  99249. if (depth1 < 0) {
  99250. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  99251. }
  99252. if (depth2 < 0) {
  99253. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  99254. }
  99255. }
  99256. break;
  99257. }
  99258. };
  99259. OIMO.SphereCylinderCollisionDetector = function (flip) {
  99260. OIMO.CollisionDetector.call(this);
  99261. this.flip = flip;
  99262. };
  99263. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99264. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  99265. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99266. var s;
  99267. var c;
  99268. if (this.flip) {
  99269. s = shape2;
  99270. c = shape1;
  99271. } else {
  99272. s = shape1;
  99273. c = shape2;
  99274. }
  99275. var ps = s.position;
  99276. var psx = ps.x;
  99277. var psy = ps.y;
  99278. var psz = ps.z;
  99279. var pc = c.position;
  99280. var pcx = pc.x;
  99281. var pcy = pc.y;
  99282. var pcz = pc.z;
  99283. var dirx = c.normalDirection.x;
  99284. var diry = c.normalDirection.y;
  99285. var dirz = c.normalDirection.z;
  99286. var rads = s.radius;
  99287. var radc = c.radius;
  99288. var rad2 = rads + radc;
  99289. var halfh = c.halfHeight;
  99290. var dx = psx - pcx;
  99291. var dy = psy - pcy;
  99292. var dz = psz - pcz;
  99293. var dot = dx * dirx + dy * diry + dz * dirz;
  99294. if (dot < -halfh - rads || dot > halfh + rads) return;
  99295. var cx = pcx + dot * dirx;
  99296. var cy = pcy + dot * diry;
  99297. var cz = pcz + dot * dirz;
  99298. var d2x = psx - cx;
  99299. var d2y = psy - cy;
  99300. var d2z = psz - cz;
  99301. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  99302. if (len > rad2 * rad2) return;
  99303. if (len > radc * radc) {
  99304. len = radc / OIMO.sqrt(len);
  99305. d2x *= len;
  99306. d2y *= len;
  99307. d2z *= len;
  99308. }
  99309. if (dot < -halfh) dot = -halfh;
  99310. else if (dot > halfh) dot = halfh;
  99311. cx = pcx + dot * dirx + d2x;
  99312. cy = pcy + dot * diry + d2y;
  99313. cz = pcz + dot * dirz + d2z;
  99314. dx = cx - psx;
  99315. dy = cy - psy;
  99316. dz = cz - psz;
  99317. len = dx * dx + dy * dy + dz * dz;
  99318. var invLen;
  99319. if (len > 0 && len < rads * rads) {
  99320. len = OIMO.sqrt(len);
  99321. invLen = 1 / len;
  99322. dx *= invLen;
  99323. dy *= invLen;
  99324. dz *= invLen;
  99325. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  99326. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  99327. }
  99328. };
  99329. /**
  99330. * Class for checking collisions between 2 tetras,
  99331. * a shape that is made with 4 vertices and 4 faces
  99332. * arranged in triangles. With this algorigthm, soft
  99333. * body physics are possible and easier to implement.
  99334. * @author xprogram
  99335. */
  99336. OIMO.TetraTetraCollisionDetector = function () {
  99337. OIMO.CollisionDetector.call(this);
  99338. };
  99339. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99340. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  99341. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  99342. /*
  99343. * What we are doing:
  99344. * Each tetra is represented by four 3D triangles. The only
  99345. * quick way of finding if another tetra is within the other
  99346. * tetra is to see if a single vertex is within the triangles
  99347. * of the other tetra. So, for example, a tetra is represented
  99348. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  99349. * There is another tetra with a vertex A which was detected for
  99350. * collision by the broadphase. Now, if the point A is between ALL
  99351. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  99352. * is valid and we can pass point A to the manifold. Since the only
  99353. * points on the tetra are the 4 vertices, collision detection is
  99354. * not so complex. However, it can be time-consuming because we
  99355. * need to split the 3D triangles into three 2D triangles each for
  99356. * collision detection.
  99357. */
  99358. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  99359. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  99360. // fs is undeclared
  99361. var fs = fs1;
  99362. for (i = 0; i < 4; i++) {
  99363. vec = vs1[i];
  99364. for (j = 0; j < 4; j++) {
  99365. j1 = vs2[fs[i].a];
  99366. j2 = vs2[fs[i].b];
  99367. j3 = vs2[fs[i].c];
  99368. if (
  99369. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  99370. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  99371. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  99372. )
  99373. ts++;
  99374. if (ts === 4) // Only add point if it is inside all 4 triangles
  99375. manifold.addPoint(vec);
  99376. }
  99377. }
  99378. };
  99379. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  99380. function tricheck(p, p0, p1, p2) {
  99381. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  99382. var sg = A < 0 ? -1 : 1;
  99383. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  99384. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  99385. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  99386. }
  99387. function pt(x, y) { return { x: x, y: y }; }
  99388. /**
  99389. * An axis-aligned bounding box.
  99390. * @author saharan
  99391. * @author lo-th
  99392. */
  99393. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  99394. this.elements = new OIMO_ARRAY_TYPE(6);
  99395. var te = this.elements;
  99396. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  99397. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  99398. };
  99399. OIMO.AABB.prototype = {
  99400. constructor: OIMO.AABB,
  99401. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  99402. var te = this.elements;
  99403. te[0] = minX; te[3] = maxX;
  99404. te[1] = minY; te[4] = maxY;
  99405. te[2] = minZ; te[5] = maxZ;
  99406. return this;
  99407. },
  99408. intersectTest: function (aabb) {
  99409. var te = this.elements;
  99410. var ue = aabb.elements;
  99411. 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];
  99412. },
  99413. intersectTestTwo: function (aabb) {
  99414. var te = this.elements;
  99415. var ue = aabb.elements;
  99416. 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];
  99417. },
  99418. clone: function () {
  99419. return new this.constructor().fromArray(this.elements);
  99420. },
  99421. copy: function (aabb, margin) {
  99422. var m = margin || 0;
  99423. var me = aabb.elements;
  99424. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  99425. return this;
  99426. },
  99427. fromArray: function (array) {
  99428. this.elements.set(array);
  99429. return this;
  99430. },
  99431. // Set this AABB to the combined AABB of aabb1 and aabb2.
  99432. combine: function (aabb1, aabb2) {
  99433. var a = aabb1.elements;
  99434. var b = aabb2.elements;
  99435. var te = this.elements;
  99436. te[0] = a[0] < b[0] ? a[0] : b[0];
  99437. te[1] = a[1] < b[1] ? a[1] : b[1];
  99438. te[2] = a[2] < b[2] ? a[2] : b[2];
  99439. te[3] = a[3] > b[3] ? a[3] : b[3];
  99440. te[4] = a[4] > b[4] ? a[4] : b[4];
  99441. te[5] = a[5] > b[5] ? a[5] : b[5];
  99442. return this;
  99443. },
  99444. // Get the surface area.
  99445. surfaceArea: function () {
  99446. var te = this.elements;
  99447. var a = te[3] - te[0];
  99448. var h = te[4] - te[1];
  99449. var d = te[5] - te[2];
  99450. return 2 * (a * (h + d) + h * d);
  99451. },
  99452. // Get whether the AABB intersects with the point or not.
  99453. intersectsWithPoint: function (x, y, z) {
  99454. var te = this.elements;
  99455. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  99456. },
  99457. /**
  99458. * Set the AABB from an array
  99459. * of vertices. From THREE.
  99460. * @author mrdoob
  99461. * @author xprogram
  99462. */
  99463. setFromPoints: function (arr) {
  99464. this.makeEmpty();
  99465. for (var i = 0; i < arr.length; i++) {
  99466. this.expandByPoint(arr[i]);
  99467. }
  99468. },
  99469. makeEmpty: function () {
  99470. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  99471. },
  99472. expandByPoint: function (pt) {
  99473. var te = this.elements;
  99474. this.set(
  99475. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  99476. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  99477. );
  99478. }
  99479. };
  99480. /**
  99481. * A proxy is used for broad-phase collecting pairs that can be colliding.
  99482. */
  99483. OIMO.Proxy = function (shape) {
  99484. // The parent shape.
  99485. this.shape = shape;
  99486. // The axis-aligned bounding box.
  99487. this.aabb = shape.aabb;
  99488. };
  99489. OIMO.Proxy.prototype = {
  99490. constructor: OIMO.Proxy,
  99491. // Update the proxy.
  99492. update: function () {
  99493. OIMO.Error("Proxy", "Inheritance error.");
  99494. }
  99495. };
  99496. /**
  99497. * A basic implementation of proxies.
  99498. * @author saharan
  99499. */
  99500. OIMO.BasicProxy = function (shape) {
  99501. OIMO.Proxy.call(this, shape);
  99502. this.id = OIMO.proxyID++;
  99503. };
  99504. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  99505. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  99506. OIMO.BasicProxy.prototype.update = function () {
  99507. };
  99508. /**
  99509. * The broad-phase is used for collecting all possible pairs for collision.
  99510. */
  99511. OIMO.BroadPhase = function () {
  99512. this.types = OIMO.BR_NULL;
  99513. this.numPairChecks = 0;
  99514. this.numPairs = 0;
  99515. this.pairs = [];
  99516. };
  99517. OIMO.BroadPhase.prototype = {
  99518. constructor: OIMO.BroadPhase,
  99519. /**
  99520. * Create a new proxy.
  99521. * @param shape
  99522. * @return
  99523. */
  99524. createProxy: function (shape) {
  99525. OIMO.Error("BroadPhase", "Inheritance error.");
  99526. },
  99527. /**
  99528. * Add the proxy into the broad-phase.
  99529. * @param proxy
  99530. */
  99531. addProxy: function (proxy) {
  99532. OIMO.Error("BroadPhase", "Inheritance error.");
  99533. },
  99534. /**
  99535. * Remove the proxy from the broad-phase.
  99536. * @param proxy
  99537. */
  99538. removeProxy: function (proxy) {
  99539. OIMO.Error("BroadPhase", "Inheritance error.");
  99540. },
  99541. /**
  99542. * Returns whether the pair is available or not.
  99543. * @param s1
  99544. * @param s2
  99545. * @return
  99546. */
  99547. isAvailablePair: function (s1, s2) {
  99548. var b1 = s1.parent;
  99549. var b2 = s2.parent;
  99550. if (b1 == b2 || // same parents
  99551. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  99552. (s1.belongsTo & s2.collidesWith) == 0 ||
  99553. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  99554. ) { return false; }
  99555. var js;
  99556. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  99557. else js = b2.jointLink;
  99558. while (js !== null) {
  99559. var joint = js.joint;
  99560. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  99561. js = js.next;
  99562. }
  99563. return true;
  99564. },
  99565. // Detect overlapping pairs.
  99566. detectPairs: function () {
  99567. // clear old
  99568. this.pairs = [];
  99569. this.numPairs = 0;
  99570. this.numPairChecks = 0;
  99571. this.collectPairs();
  99572. },
  99573. collectPairs: function () {
  99574. OIMO.Error("BroadPhase", "Inheritance error.");
  99575. },
  99576. addPair: function (s1, s2) {
  99577. var pair = new OIMO.Pair(s1, s2);
  99578. this.pairs.push(pair);
  99579. this.numPairs++;
  99580. }
  99581. };
  99582. /**
  99583. * A broad-phase algorithm with brute-force search.
  99584. * This always checks for all possible pairs.
  99585. */
  99586. OIMO.BruteForceBroadPhase = function () {
  99587. OIMO.BroadPhase.call(this);
  99588. this.types = OIMO.BR_BRUTE_FORCE;;
  99589. //this.numProxies=0;
  99590. ///this.maxProxies = 256;
  99591. this.proxies = [];
  99592. //this.proxies.length = 256;
  99593. };
  99594. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  99595. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  99596. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  99597. return new OIMO.BasicProxy(shape);
  99598. };
  99599. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  99600. /*if(this.numProxies==this.maxProxies){
  99601. //this.maxProxies<<=1;
  99602. this.maxProxies*=2;
  99603. var newProxies=[];
  99604. newProxies.length = this.maxProxies;
  99605. var i = this.numProxies;
  99606. while(i--){
  99607. //for(var i=0, l=this.numProxies;i<l;i++){
  99608. newProxies[i]=this.proxies[i];
  99609. }
  99610. this.proxies=newProxies;
  99611. }*/
  99612. //this.proxies[this.numProxies++] = proxy;
  99613. this.proxies.push(proxy);
  99614. //this.numProxies++;
  99615. };
  99616. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  99617. var n = this.proxies.indexOf(proxy);
  99618. if (n > -1) {
  99619. this.proxies.splice(n, 1);
  99620. //this.numProxies--;
  99621. }
  99622. /*var i = this.numProxies;
  99623. while(i--){
  99624. //for(var i=0, l=this.numProxies;i<l;i++){
  99625. if(this.proxies[i] == proxy){
  99626. this.proxies[i] = this.proxies[--this.numProxies];
  99627. this.proxies[this.numProxies] = null;
  99628. return;
  99629. }
  99630. }*/
  99631. };
  99632. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  99633. var i = 0, j, p1, p2;
  99634. var px = this.proxies;
  99635. var l = px.length;//this.numProxies;
  99636. //var ar1 = [];
  99637. //var ar2 = [];
  99638. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  99639. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  99640. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  99641. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  99642. this.numPairChecks = l * (l - 1) >> 1;
  99643. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  99644. while (i < l) {
  99645. p1 = px[i++];
  99646. j = i + 1;
  99647. while (j < l) {
  99648. p2 = px[j++];
  99649. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  99650. this.addPair(p1.shape, p2.shape);
  99651. }
  99652. }
  99653. };
  99654. /**
  99655. * A pair of shapes that may collide.
  99656. * @author saharan
  99657. */
  99658. OIMO.Pair = function (s1, s2) {
  99659. // The first shape.
  99660. this.shape1 = s1 || null;
  99661. // The second shape.
  99662. this.shape2 = s2 || null;
  99663. };
  99664. /**
  99665. * A projection axis for sweep and prune broad-phase.
  99666. * @author saharan
  99667. */
  99668. OIMO.SAPAxis = function () {
  99669. this.numElements = 0;
  99670. this.bufferSize = 256;
  99671. this.elements = [];
  99672. this.elements.length = this.bufferSize;
  99673. this.stack = new OIMO_ARRAY_TYPE(64);
  99674. };
  99675. OIMO.SAPAxis.prototype = {
  99676. constructor: OIMO.SAPAxis,
  99677. addElements: function (min, max) {
  99678. if (this.numElements + 2 >= this.bufferSize) {
  99679. //this.bufferSize<<=1;
  99680. this.bufferSize *= 2;
  99681. var newElements = [];
  99682. var i = this.numElements;
  99683. while (i--) {
  99684. //for(var i=0, l=this.numElements; i<l; i++){
  99685. newElements[i] = this.elements[i];
  99686. }
  99687. }
  99688. this.elements[this.numElements++] = min;
  99689. this.elements[this.numElements++] = max;
  99690. },
  99691. removeElements: function (min, max) {
  99692. var minIndex = -1;
  99693. var maxIndex = -1;
  99694. for (var i = 0, l = this.numElements; i < l; i++) {
  99695. var e = this.elements[i];
  99696. if (e == min || e == max) {
  99697. if (minIndex == -1) {
  99698. minIndex = i;
  99699. } else {
  99700. maxIndex = i;
  99701. break;
  99702. }
  99703. }
  99704. }
  99705. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  99706. this.elements[i - 1] = this.elements[i];
  99707. }
  99708. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  99709. this.elements[i - 2] = this.elements[i];
  99710. }
  99711. this.elements[--this.numElements] = null;
  99712. this.elements[--this.numElements] = null;
  99713. },
  99714. sort: function () {
  99715. var count = 0;
  99716. var threshold = 1;
  99717. while ((this.numElements >> threshold) != 0) threshold++;
  99718. threshold = threshold * this.numElements >> 2;
  99719. count = 0;
  99720. var giveup = false;
  99721. var elements = this.elements;
  99722. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  99723. var tmp = elements[i];
  99724. var pivot = tmp.value;
  99725. var tmp2 = elements[i - 1];
  99726. if (tmp2.value > pivot) {
  99727. var j = i;
  99728. do {
  99729. elements[j] = tmp2;
  99730. if (--j == 0) break;
  99731. tmp2 = elements[j - 1];
  99732. } while (tmp2.value > pivot);
  99733. elements[j] = tmp;
  99734. count += i - j;
  99735. if (count > threshold) {
  99736. giveup = true; // stop and use quick sort
  99737. break;
  99738. }
  99739. }
  99740. }
  99741. if (!giveup) return;
  99742. count = 2; var stack = this.stack;
  99743. stack[0] = 0;
  99744. stack[1] = this.numElements - 1;
  99745. while (count > 0) {
  99746. var right = stack[--count];
  99747. var left = stack[--count];
  99748. var diff = right - left;
  99749. if (diff > 16) { // quick sort
  99750. //var mid=left+(diff>>1);
  99751. var mid = left + (OIMO.floor(diff * 0.5));
  99752. tmp = elements[mid];
  99753. elements[mid] = elements[right];
  99754. elements[right] = tmp;
  99755. pivot = tmp.value;
  99756. i = left - 1;
  99757. j = right;
  99758. while (true) {
  99759. var ei;
  99760. var ej;
  99761. do { ei = elements[++i]; } while (ei.value < pivot);
  99762. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  99763. if (i >= j) break;
  99764. elements[i] = ej;
  99765. elements[j] = ei;
  99766. }
  99767. elements[right] = elements[i];
  99768. elements[i] = tmp;
  99769. if (i - left > right - i) {
  99770. stack[count++] = left;
  99771. stack[count++] = i - 1;
  99772. stack[count++] = i + 1;
  99773. stack[count++] = right;
  99774. } else {
  99775. stack[count++] = i + 1;
  99776. stack[count++] = right;
  99777. stack[count++] = left;
  99778. stack[count++] = i - 1;
  99779. }
  99780. } else {
  99781. for (i = left + 1; i <= right; i++) {
  99782. tmp = elements[i];
  99783. pivot = tmp.value;
  99784. tmp2 = elements[i - 1];
  99785. if (tmp2.value > pivot) {
  99786. j = i;
  99787. do {
  99788. elements[j] = tmp2;
  99789. if (--j == 0) break;
  99790. tmp2 = elements[j - 1];
  99791. } while (tmp2.value > pivot);
  99792. elements[j] = tmp;
  99793. }
  99794. }
  99795. }
  99796. }
  99797. },
  99798. calculateTestCount: function () {
  99799. var num = 1;
  99800. var sum = 0;
  99801. for (var i = 1, l = this.numElements; i < l; i++) {
  99802. if (this.elements[i].max) {
  99803. num--;
  99804. } else {
  99805. sum += num;
  99806. num++;
  99807. }
  99808. }
  99809. return sum;
  99810. }
  99811. }
  99812. /**
  99813. * A broad-phase collision detection algorithm using sweep and prune.
  99814. * @author saharan
  99815. * @author lo-th
  99816. */
  99817. OIMO.SAPBroadPhase = function () {
  99818. OIMO.BroadPhase.call(this);
  99819. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  99820. this.numElementsD = 0;
  99821. this.numElementsS = 0;
  99822. // dynamic proxies
  99823. this.axesD = [
  99824. new OIMO.SAPAxis(),
  99825. new OIMO.SAPAxis(),
  99826. new OIMO.SAPAxis()
  99827. ];
  99828. // static or sleeping proxies
  99829. this.axesS = [
  99830. new OIMO.SAPAxis(),
  99831. new OIMO.SAPAxis(),
  99832. new OIMO.SAPAxis()
  99833. ];
  99834. this.index1 = 0;
  99835. this.index2 = 1;
  99836. };
  99837. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  99838. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  99839. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  99840. return new OIMO.SAPProxy(this, shape);
  99841. };
  99842. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  99843. var p = proxy;
  99844. if (p.isDynamic()) {
  99845. this.axesD[0].addElements(p.min[0], p.max[0]);
  99846. this.axesD[1].addElements(p.min[1], p.max[1]);
  99847. this.axesD[2].addElements(p.min[2], p.max[2]);
  99848. p.belongsTo = 1;
  99849. this.numElementsD += 2;
  99850. } else {
  99851. this.axesS[0].addElements(p.min[0], p.max[0]);
  99852. this.axesS[1].addElements(p.min[1], p.max[1]);
  99853. this.axesS[2].addElements(p.min[2], p.max[2]);
  99854. p.belongsTo = 2;
  99855. this.numElementsS += 2;
  99856. }
  99857. };
  99858. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  99859. var p = proxy;
  99860. if (p.belongsTo == 0) return;
  99861. /*else if ( p.belongsTo == 1 ) {
  99862. this.axesD[0].removeElements( p.min[0], p.max[0] );
  99863. this.axesD[1].removeElements( p.min[1], p.max[1] );
  99864. this.axesD[2].removeElements( p.min[2], p.max[2] );
  99865. this.numElementsD -= 2;
  99866. } else if ( p.belongsTo == 2 ) {
  99867. this.axesS[0].removeElements( p.min[0], p.max[0] );
  99868. this.axesS[1].removeElements( p.min[1], p.max[1] );
  99869. this.axesS[2].removeElements( p.min[2], p.max[2] );
  99870. this.numElementsS -= 2;
  99871. }*/
  99872. switch (p.belongsTo) {
  99873. case 1:
  99874. this.axesD[0].removeElements(p.min[0], p.max[0]);
  99875. this.axesD[1].removeElements(p.min[1], p.max[1]);
  99876. this.axesD[2].removeElements(p.min[2], p.max[2]);
  99877. this.numElementsD -= 2;
  99878. break;
  99879. case 2:
  99880. this.axesS[0].removeElements(p.min[0], p.max[0]);
  99881. this.axesS[1].removeElements(p.min[1], p.max[1]);
  99882. this.axesS[2].removeElements(p.min[2], p.max[2]);
  99883. this.numElementsS -= 2;
  99884. break;
  99885. }
  99886. p.belongsTo = 0;
  99887. };
  99888. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  99889. if (this.numElementsD == 0) return;
  99890. var axis1 = this.axesD[this.index1];
  99891. var axis2 = this.axesD[this.index2];
  99892. axis1.sort();
  99893. axis2.sort();
  99894. var count1 = axis1.calculateTestCount();
  99895. var count2 = axis2.calculateTestCount();
  99896. var elementsD;
  99897. var elementsS;
  99898. if (count1 <= count2) {// select the best axis
  99899. axis2 = this.axesS[this.index1];
  99900. axis2.sort();
  99901. elementsD = axis1.elements;
  99902. elementsS = axis2.elements;
  99903. } else {
  99904. axis1 = this.axesS[this.index2];
  99905. axis1.sort();
  99906. elementsD = axis2.elements;
  99907. elementsS = axis1.elements;
  99908. this.index1 ^= this.index2;
  99909. this.index2 ^= this.index1;
  99910. this.index1 ^= this.index2;
  99911. }
  99912. var activeD;
  99913. var activeS;
  99914. var p = 0;
  99915. var q = 0;
  99916. while (p < this.numElementsD) {
  99917. var e1;
  99918. var dyn;
  99919. if (q == this.numElementsS) {
  99920. e1 = elementsD[p];
  99921. dyn = true;
  99922. p++;
  99923. } else {
  99924. var d = elementsD[p];
  99925. var s = elementsS[q];
  99926. if (d.value < s.value) {
  99927. e1 = d;
  99928. dyn = true;
  99929. p++;
  99930. } else {
  99931. e1 = s;
  99932. dyn = false;
  99933. q++;
  99934. }
  99935. }
  99936. if (!e1.max) {
  99937. var s1 = e1.proxy.shape;
  99938. var min1 = e1.min1.value;
  99939. var max1 = e1.max1.value;
  99940. var min2 = e1.min2.value;
  99941. var max2 = e1.max2.value;
  99942. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  99943. var s2 = e2.proxy.shape;
  99944. this.numPairChecks++;
  99945. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  99946. this.addPair(s1, s2);
  99947. }
  99948. if (dyn) {
  99949. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  99950. s2 = e2.proxy.shape;
  99951. this.numPairChecks++;
  99952. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  99953. this.addPair(s1, s2);
  99954. }
  99955. e1.pair = activeD;
  99956. activeD = e1;
  99957. } else {
  99958. e1.pair = activeS;
  99959. activeS = e1;
  99960. }
  99961. } else {
  99962. var min = e1.pair;
  99963. if (dyn) {
  99964. if (min == activeD) {
  99965. activeD = activeD.pair;
  99966. continue;
  99967. } else {
  99968. e1 = activeD;
  99969. }
  99970. } else {
  99971. if (min == activeS) {
  99972. activeS = activeS.pair;
  99973. continue;
  99974. } else {
  99975. e1 = activeS;
  99976. }
  99977. }
  99978. do {
  99979. e2 = e1.pair;
  99980. if (e2 == min) {
  99981. e1.pair = e2.pair;
  99982. break;
  99983. }
  99984. e1 = e2;
  99985. } while (e1 != null);
  99986. }
  99987. }
  99988. this.index2 = (this.index1 | this.index2) ^ 3;
  99989. };
  99990. /**
  99991. * An element of proxies.
  99992. * @author saharan
  99993. */
  99994. OIMO.SAPElement = function (proxy, max) {
  99995. // The parent proxy
  99996. this.proxy = proxy;
  99997. // The pair element.
  99998. this.pair = null;
  99999. // The minimum element on other axis.
  100000. this.min1 = null;
  100001. // The maximum element on other axis.
  100002. this.max1 = null;
  100003. // The minimum element on other axis.
  100004. this.min2 = null;
  100005. // The maximum element on other axis.
  100006. this.max2 = null;
  100007. // Whether the element has maximum value or not.
  100008. this.max = max;
  100009. // The value of the element.
  100010. this.value = 0;
  100011. };
  100012. /**
  100013. * A proxy for sweep and prune broad-phase.
  100014. * @author saharan
  100015. * @author lo-th
  100016. */
  100017. OIMO.SAPProxy = function (sap, shape) {
  100018. OIMO.Proxy.call(this, shape);
  100019. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  100020. this.belongsTo = 0;
  100021. // The maximum elements on each axis.
  100022. this.max = [];
  100023. // The minimum elements on each axis.
  100024. this.min = [];
  100025. this.sap = sap;
  100026. this.min[0] = new OIMO.SAPElement(this, false);
  100027. this.max[0] = new OIMO.SAPElement(this, true);
  100028. this.min[1] = new OIMO.SAPElement(this, false);
  100029. this.max[1] = new OIMO.SAPElement(this, true);
  100030. this.min[2] = new OIMO.SAPElement(this, false);
  100031. this.max[2] = new OIMO.SAPElement(this, true);
  100032. this.max[0].pair = this.min[0];
  100033. this.max[1].pair = this.min[1];
  100034. this.max[2].pair = this.min[2];
  100035. this.min[0].min1 = this.min[1];
  100036. this.min[0].max1 = this.max[1];
  100037. this.min[0].min2 = this.min[2];
  100038. this.min[0].max2 = this.max[2];
  100039. this.min[1].min1 = this.min[0];
  100040. this.min[1].max1 = this.max[0];
  100041. this.min[1].min2 = this.min[2];
  100042. this.min[1].max2 = this.max[2];
  100043. this.min[2].min1 = this.min[0];
  100044. this.min[2].max1 = this.max[0];
  100045. this.min[2].min2 = this.min[1];
  100046. this.min[2].max2 = this.max[1];
  100047. };
  100048. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  100049. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  100050. // Returns whether the proxy is dynamic or not.
  100051. OIMO.SAPProxy.prototype.isDynamic = function () {
  100052. var body = this.shape.parent;
  100053. return body.isDynamic && !body.sleeping;
  100054. };
  100055. OIMO.SAPProxy.prototype.update = function () {
  100056. var te = this.aabb.elements;
  100057. this.min[0].value = te[0];
  100058. this.min[1].value = te[1];
  100059. this.min[2].value = te[2];
  100060. this.max[0].value = te[3];
  100061. this.max[1].value = te[4];
  100062. this.max[2].value = te[5];
  100063. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  100064. this.sap.removeProxy(this);
  100065. this.sap.addProxy(this);
  100066. }
  100067. };
  100068. /**
  100069. * A dynamic bounding volume tree for the broad-phase algorithm.
  100070. * @author saharan
  100071. * @author lo-th
  100072. */
  100073. OIMO.DBVT = function () {
  100074. // The root of the tree.
  100075. this.root = null;
  100076. this.freeNodes = [];
  100077. this.freeNodes.length = 16384;
  100078. this.numFreeNodes = 0;
  100079. this.aabb = new OIMO.AABB();
  100080. };
  100081. OIMO.DBVT.prototype = {
  100082. constructor: OIMO.DBVT,
  100083. /**
  100084. * Move a leaf.
  100085. * @param leaf
  100086. */
  100087. moveLeaf: function (leaf) {
  100088. this.deleteLeaf(leaf);
  100089. this.insertLeaf(leaf);
  100090. },
  100091. /**
  100092. * Insert a leaf to the tree.
  100093. * @param node
  100094. */
  100095. insertLeaf: function (leaf) {
  100096. if (this.root == null) {
  100097. this.root = leaf;
  100098. return;
  100099. }
  100100. var lb = leaf.aabb;
  100101. var sibling = this.root;
  100102. var oldArea;
  100103. var newArea;
  100104. while (sibling.proxy == null) { // descend the node to search the best pair
  100105. var c1 = sibling.child1;
  100106. var c2 = sibling.child2;
  100107. var b = sibling.aabb;
  100108. var c1b = c1.aabb;
  100109. var c2b = c2.aabb;
  100110. oldArea = b.surfaceArea();
  100111. this.aabb.combine(lb, b);
  100112. newArea = this.aabb.surfaceArea();
  100113. var creatingCost = newArea * 2;
  100114. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  100115. var discendingCost1 = incrementalCost;
  100116. this.aabb.combine(lb, c1b);
  100117. if (c1.proxy != null) {
  100118. // leaf cost = area(combined aabb)
  100119. discendingCost1 += this.aabb.surfaceArea();
  100120. } else {
  100121. // node cost = area(combined aabb) - area(old aabb)
  100122. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  100123. }
  100124. var discendingCost2 = incrementalCost;
  100125. this.aabb.combine(lb, c2b);
  100126. if (c2.proxy != null) {
  100127. // leaf cost = area(combined aabb)
  100128. discendingCost2 += this.aabb.surfaceArea();
  100129. } else {
  100130. // node cost = area(combined aabb) - area(old aabb)
  100131. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  100132. }
  100133. if (discendingCost1 < discendingCost2) {
  100134. if (creatingCost < discendingCost1) {
  100135. break;// stop descending
  100136. } else {
  100137. sibling = c1;// descend into first child
  100138. }
  100139. } else {
  100140. if (creatingCost < discendingCost2) {
  100141. break;// stop descending
  100142. } else {
  100143. sibling = c2;// descend into second child
  100144. }
  100145. }
  100146. }
  100147. var oldParent = sibling.parent;
  100148. var newParent;
  100149. if (this.numFreeNodes > 0) {
  100150. newParent = this.freeNodes[--this.numFreeNodes];
  100151. } else {
  100152. newParent = new OIMO.DBVTNode();
  100153. }
  100154. newParent.parent = oldParent;
  100155. newParent.child1 = leaf;
  100156. newParent.child2 = sibling;
  100157. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  100158. newParent.height = sibling.height + 1;
  100159. sibling.parent = newParent;
  100160. leaf.parent = newParent;
  100161. if (sibling == this.root) {
  100162. // replace root
  100163. this.root = newParent;
  100164. } else {
  100165. // replace child
  100166. if (oldParent.child1 == sibling) {
  100167. oldParent.child1 = newParent;
  100168. } else {
  100169. oldParent.child2 = newParent;
  100170. }
  100171. }
  100172. // update whole tree
  100173. do {
  100174. newParent = this.balance(newParent);
  100175. this.fix(newParent);
  100176. newParent = newParent.parent;
  100177. } while (newParent != null);
  100178. },
  100179. getBalance: function (node) {
  100180. if (node.proxy != null) return 0;
  100181. return node.child1.height - node.child2.height;
  100182. },
  100183. /*print:function(node,indent,text){
  100184. var hasChild=node.proxy==null;
  100185. if(hasChild)text=this.print(node.child1,indent+1,text);
  100186. for(var i=indent*2;i>=0;i--){
  100187. text+=" ";
  100188. }
  100189. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  100190. if(hasChild)text=this.print(node.child2,indent+1,text);
  100191. return text;
  100192. },*/
  100193. /**
  100194. * Delete a leaf from the tree.
  100195. * @param node
  100196. */
  100197. deleteLeaf: function (leaf) {
  100198. if (leaf == this.root) {
  100199. this.root = null;
  100200. return;
  100201. }
  100202. var parent = leaf.parent;
  100203. var sibling;
  100204. if (parent.child1 == leaf) {
  100205. sibling = parent.child2;
  100206. } else {
  100207. sibling = parent.child1;
  100208. }
  100209. if (parent == this.root) {
  100210. this.root = sibling;
  100211. sibling.parent = null;
  100212. return;
  100213. }
  100214. var grandParent = parent.parent;
  100215. sibling.parent = grandParent;
  100216. if (grandParent.child1 == parent) {
  100217. grandParent.child1 = sibling;
  100218. } else {
  100219. grandParent.child2 = sibling;
  100220. }
  100221. if (this.numFreeNodes < 16384) {
  100222. this.freeNodes[this.numFreeNodes++] = parent;
  100223. }
  100224. do {
  100225. grandParent = this.balance(grandParent);
  100226. this.fix(grandParent);
  100227. grandParent = grandParent.parent;
  100228. } while (grandParent != null);
  100229. },
  100230. balance: function (node) {
  100231. var nh = node.height;
  100232. if (nh < 2) {
  100233. return node;
  100234. }
  100235. var p = node.parent;
  100236. var l = node.child1;
  100237. var r = node.child2;
  100238. var lh = l.height;
  100239. var rh = r.height;
  100240. var balance = lh - rh;
  100241. var t;// for bit operation
  100242. // [ N ]
  100243. // / \
  100244. // [ L ] [ R ]
  100245. // / \ / \
  100246. // [L-L] [L-R] [R-L] [R-R]
  100247. // Is the tree balanced?
  100248. if (balance > 1) {
  100249. var ll = l.child1;
  100250. var lr = l.child2;
  100251. var llh = ll.height;
  100252. var lrh = lr.height;
  100253. // Is L-L higher than L-R?
  100254. if (llh > lrh) {
  100255. // set N to L-R
  100256. l.child2 = node;
  100257. node.parent = l;
  100258. // [ L ]
  100259. // / \
  100260. // [L-L] [ N ]
  100261. // / \ / \
  100262. // [...] [...] [ L ] [ R ]
  100263. // set L-R
  100264. node.child1 = lr;
  100265. lr.parent = node;
  100266. // [ L ]
  100267. // / \
  100268. // [L-L] [ N ]
  100269. // / \ / \
  100270. // [...] [...] [L-R] [ R ]
  100271. // fix bounds and heights
  100272. node.aabb.combine(lr.aabb, r.aabb);
  100273. t = lrh - rh;
  100274. node.height = lrh - (t & t >> 31) + 1;
  100275. l.aabb.combine(ll.aabb, node.aabb);
  100276. t = llh - nh;
  100277. l.height = llh - (t & t >> 31) + 1;
  100278. } else {
  100279. // set N to L-L
  100280. l.child1 = node;
  100281. node.parent = l;
  100282. // [ L ]
  100283. // / \
  100284. // [ N ] [L-R]
  100285. // / \ / \
  100286. // [ L ] [ R ] [...] [...]
  100287. // set L-L
  100288. node.child1 = ll;
  100289. ll.parent = node;
  100290. // [ L ]
  100291. // / \
  100292. // [ N ] [L-R]
  100293. // / \ / \
  100294. // [L-L] [ R ] [...] [...]
  100295. // fix bounds and heights
  100296. node.aabb.combine(ll.aabb, r.aabb);
  100297. t = llh - rh;
  100298. node.height = llh - (t & t >> 31) + 1;
  100299. l.aabb.combine(node.aabb, lr.aabb);
  100300. t = nh - lrh;
  100301. l.height = nh - (t & t >> 31) + 1;
  100302. }
  100303. // set new parent of L
  100304. if (p != null) {
  100305. if (p.child1 == node) {
  100306. p.child1 = l;
  100307. } else {
  100308. p.child2 = l;
  100309. }
  100310. } else {
  100311. this.root = l;
  100312. }
  100313. l.parent = p;
  100314. return l;
  100315. } else if (balance < -1) {
  100316. var rl = r.child1;
  100317. var rr = r.child2;
  100318. var rlh = rl.height;
  100319. var rrh = rr.height;
  100320. // Is R-L higher than R-R?
  100321. if (rlh > rrh) {
  100322. // set N to R-R
  100323. r.child2 = node;
  100324. node.parent = r;
  100325. // [ R ]
  100326. // / \
  100327. // [R-L] [ N ]
  100328. // / \ / \
  100329. // [...] [...] [ L ] [ R ]
  100330. // set R-R
  100331. node.child2 = rr;
  100332. rr.parent = node;
  100333. // [ R ]
  100334. // / \
  100335. // [R-L] [ N ]
  100336. // / \ / \
  100337. // [...] [...] [ L ] [R-R]
  100338. // fix bounds and heights
  100339. node.aabb.combine(l.aabb, rr.aabb);
  100340. t = lh - rrh;
  100341. node.height = lh - (t & t >> 31) + 1;
  100342. r.aabb.combine(rl.aabb, node.aabb);
  100343. t = rlh - nh;
  100344. r.height = rlh - (t & t >> 31) + 1;
  100345. } else {
  100346. // set N to R-L
  100347. r.child1 = node;
  100348. node.parent = r;
  100349. // [ R ]
  100350. // / \
  100351. // [ N ] [R-R]
  100352. // / \ / \
  100353. // [ L ] [ R ] [...] [...]
  100354. // set R-L
  100355. node.child2 = rl;
  100356. rl.parent = node;
  100357. // [ R ]
  100358. // / \
  100359. // [ N ] [R-R]
  100360. // / \ / \
  100361. // [ L ] [R-L] [...] [...]
  100362. // fix bounds and heights
  100363. node.aabb.combine(l.aabb, rl.aabb);
  100364. t = lh - rlh;
  100365. node.height = lh - (t & t >> 31) + 1;
  100366. r.aabb.combine(node.aabb, rr.aabb);
  100367. t = nh - rrh;
  100368. r.height = nh - (t & t >> 31) + 1;
  100369. }
  100370. // set new parent of R
  100371. if (p != null) {
  100372. if (p.child1 == node) {
  100373. p.child1 = r;
  100374. } else {
  100375. p.child2 = r;
  100376. }
  100377. } else {
  100378. this.root = r;
  100379. }
  100380. r.parent = p;
  100381. return r;
  100382. }
  100383. return node;
  100384. },
  100385. fix: function (node) {
  100386. var c1 = node.child1;
  100387. var c2 = node.child2;
  100388. node.aabb.combine(c1.aabb, c2.aabb);
  100389. //var h1 = c1.height;
  100390. //var h2 = c2.height;
  100391. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  100392. /*if( h1 < h2 ) {
  100393. node.height = h2+1;
  100394. }else{
  100395. node.height = h1+1;
  100396. }*/
  100397. }
  100398. }
  100399. /**
  100400. * A broad-phase algorithm using dynamic bounding volume tree.
  100401. * @author saharan
  100402. * @author lo-th
  100403. */
  100404. OIMO.DBVTBroadPhase = function () {
  100405. OIMO.BroadPhase.call(this);
  100406. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  100407. this.tree = new OIMO.DBVT();
  100408. this.stack = [];
  100409. this.leaves = [];
  100410. this.numLeaves = 0;
  100411. };
  100412. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  100413. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  100414. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  100415. return new OIMO.DBVTProxy(shape);
  100416. };
  100417. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  100418. this.tree.insertLeaf(proxy.leaf);
  100419. this.leaves.push(proxy.leaf);
  100420. this.numLeaves++;
  100421. };
  100422. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  100423. this.tree.deleteLeaf(proxy.leaf);
  100424. var n = this.leaves.indexOf(proxy.leaf);
  100425. if (n > -1) {
  100426. this.leaves.splice(n, 1);
  100427. this.numLeaves--;
  100428. }
  100429. };
  100430. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  100431. if (this.numLeaves < 2) return;
  100432. var leaf, margin = 0.1, i = this.numLeaves;
  100433. while (i--) {
  100434. leaf = this.leaves[i];
  100435. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  100436. leaf.aabb.copy(leaf.proxy.aabb, margin);
  100437. this.tree.deleteLeaf(leaf);
  100438. this.tree.insertLeaf(leaf);
  100439. this.collide(leaf, this.tree.root);
  100440. }
  100441. }
  100442. };
  100443. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  100444. var stackCount = 2;
  100445. var s1, s2, n1, n2, l1, l2;
  100446. this.stack[0] = node1;
  100447. this.stack[1] = node2;
  100448. while (stackCount > 0) {
  100449. n1 = this.stack[--stackCount];
  100450. n2 = this.stack[--stackCount];
  100451. l1 = n1.proxy != null;
  100452. l2 = n2.proxy != null;
  100453. this.numPairChecks++;
  100454. if (l1 && l2) {
  100455. s1 = n1.proxy.shape;
  100456. s2 = n2.proxy.shape;
  100457. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  100458. this.addPair(s1, s2);
  100459. } else {
  100460. if (n1.aabb.intersectTest(n2.aabb)) continue;
  100461. /*if(stackCount+4>=this.maxStack){// expand the stack
  100462. //this.maxStack<<=1;
  100463. this.maxStack*=2;
  100464. var newStack = [];// vector
  100465. newStack.length = this.maxStack;
  100466. for(var i=0;i<stackCount;i++){
  100467. newStack[i] = this.stack[i];
  100468. }
  100469. this.stack = newStack;
  100470. }*/
  100471. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  100472. this.stack[stackCount++] = n1.child1;
  100473. this.stack[stackCount++] = n2;
  100474. this.stack[stackCount++] = n1.child2;
  100475. this.stack[stackCount++] = n2;
  100476. } else {
  100477. this.stack[stackCount++] = n1;
  100478. this.stack[stackCount++] = n2.child1;
  100479. this.stack[stackCount++] = n1;
  100480. this.stack[stackCount++] = n2.child2;
  100481. }
  100482. }
  100483. }
  100484. };
  100485. /**
  100486. * A node of the dynamic bounding volume tree.
  100487. * @author saharan
  100488. */
  100489. OIMO.DBVTNode = function () {
  100490. // The first child node of this node.
  100491. this.child1 = null;
  100492. // The second child node of this node.
  100493. this.child2 = null;
  100494. // The parent node of this tree.
  100495. this.parent = null;
  100496. // The proxy of this node. This has no value if this node is not leaf.
  100497. this.proxy = null;
  100498. // The maximum distance from leaf nodes.
  100499. this.height = 0;
  100500. // The AABB of this node.
  100501. this.aabb = new OIMO.AABB();
  100502. };
  100503. /**
  100504. * A proxy for dynamic bounding volume tree broad-phase.
  100505. * @author saharan
  100506. */
  100507. OIMO.DBVTProxy = function (shape) {
  100508. OIMO.Proxy.call(this, shape);
  100509. // The leaf of the proxy.
  100510. this.leaf = new OIMO.DBVTNode();
  100511. this.leaf.proxy = this;
  100512. };
  100513. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  100514. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  100515. OIMO.DBVTProxy.prototype.update = function () {
  100516. };
  100517. OIMO.World.prototype.add = function (obj) {
  100518. obj = obj || {};
  100519. var type = obj.type || "box";
  100520. if (typeof type === 'string') type = [type];// single shape
  100521. if (type[0].substring(0, 5) == 'joint') { // is joint
  100522. if (type[0] === 'joint') type[0] = 'jointHinge';
  100523. var axe1 = obj.axe1 || [1, 0, 0];
  100524. var axe2 = obj.axe2 || [1, 0, 0];
  100525. var pos1 = obj.pos1 || [0, 0, 0];
  100526. var pos2 = obj.pos2 || [0, 0, 0];
  100527. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  100528. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  100529. var min, max;
  100530. if (type[0] === "jointDistance") {
  100531. min = obj.min || 0;
  100532. max = obj.max || 10;
  100533. min = min * OIMO.INV_SCALE;
  100534. max = max * OIMO.INV_SCALE;
  100535. } else {
  100536. min = obj.min || 57.29578;
  100537. max = obj.max || 0;
  100538. min = min * OIMO.degtorad;
  100539. max = max * OIMO.degtorad;
  100540. }
  100541. var limit = obj.limit || null;
  100542. var spring = obj.spring || null;
  100543. var motor = obj.motor || null;
  100544. // joint setting
  100545. var jc = new OIMO.JointConfig();
  100546. jc.allowCollision = obj.collision || false;;
  100547. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  100548. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  100549. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  100550. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  100551. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  100552. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  100553. jc.body1 = obj.body1;
  100554. jc.body2 = obj.body2;
  100555. var joint;
  100556. switch (type[0]) {
  100557. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  100558. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  100559. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  100560. break;
  100561. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  100562. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  100563. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  100564. break;
  100565. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  100566. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  100567. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  100568. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  100569. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  100570. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  100571. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  100572. break;
  100573. }
  100574. joint.name = obj.name || '';
  100575. // finaly add to physics world
  100576. this.addJoint(joint);
  100577. return joint;
  100578. } else { // is body
  100579. // I'm dynamique or not
  100580. var move = obj.move || false;
  100581. // I can sleep or not
  100582. var noSleep = obj.noSleep || false;
  100583. // My start position
  100584. var p = obj.pos || [0, 0, 0];
  100585. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  100586. // My size
  100587. var s = obj.size || [1, 1, 1];
  100588. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  100589. // My rotation in degre
  100590. var rot = obj.rot || [0, 0, 0];
  100591. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  100592. var r = [];
  100593. for (var i = 0; i < rot.length / 3; i++) {
  100594. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  100595. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  100596. }
  100597. // My physics setting
  100598. var sc = new OIMO.ShapeConfig();
  100599. if (obj.sc !== undefined) sc = obj.sc;
  100600. if (obj.config) {
  100601. // The density of the shape.
  100602. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  100603. // The coefficient of friction of the shape.
  100604. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  100605. // The coefficient of restitution of the shape.
  100606. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  100607. // The bits of the collision groups to which the shape belongs.
  100608. sc.belongsTo = obj.config[3] || 1;
  100609. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  100610. // The bits of the collision groups with which the shape collides.
  100611. sc.collidesWith = obj.config[4] || 0xffffffff;
  100612. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  100613. }
  100614. // direct physics setting
  100615. if (obj.density !== undefined) sc.density = obj.density;
  100616. if (obj.friction !== undefined) sc.friction = obj.friction;
  100617. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  100618. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  100619. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  100620. if (obj.massPos) {
  100621. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  100622. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  100623. }
  100624. if (obj.massRot) {
  100625. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  100626. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  100627. }
  100628. // My rigidbody
  100629. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  100630. // My shapes
  100631. var shapes = [];
  100632. //if( typeof type === 'string' ) type = [type];// single shape
  100633. var n, n2;
  100634. for (var i = 0; i < type.length; i++) {
  100635. n = i * 3;
  100636. n2 = i * 4;
  100637. switch (type[i]) {
  100638. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  100639. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  100640. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  100641. }
  100642. body.addShape(shapes[i]);
  100643. if (i > 0) {
  100644. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  100645. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  100646. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  100647. }
  100648. }
  100649. // I'm static or i move
  100650. if (move) {
  100651. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  100652. else body.setupMass(0x1, true);
  100653. if (noSleep) body.allowSleep = false;
  100654. else body.allowSleep = true;
  100655. } else {
  100656. body.setupMass(0x2);
  100657. }
  100658. body.name = obj.name || ' ';
  100659. // finaly add to physics world
  100660. this.addRigidBody(body);
  100661. return body;
  100662. }
  100663. }
  100664. //UMD simplified
  100665. var root = this;
  100666. if (!root['OIMO']) {
  100667. if (true)
  100668. module.exports = OIMO;
  100669. else if (typeof define === 'function' && define.amd)
  100670. define([], function () {
  100671. return OIMO;
  100672. });
  100673. else if (typeof exports === 'object')
  100674. exports["OIMO"] = OIMO;
  100675. else {
  100676. root["OIMO"] = OIMO;
  100677. }
  100678. }
  100679. /***/ }),
  100680. /* 17 */
  100681. /***/ (function(module, exports, __webpack_require__) {
  100682. "use strict";
  100683. Object.defineProperty(exports, "__esModule", { value: true });
  100684. var babylonjs_1 = __webpack_require__(0);
  100685. var helper_1 = __webpack_require__(5);
  100686. var TemplateManager = (function () {
  100687. function TemplateManager(containerElement) {
  100688. this.containerElement = containerElement;
  100689. this.templates = {};
  100690. this.onInit = new babylonjs_1.Observable();
  100691. this.onLoaded = new babylonjs_1.Observable();
  100692. this.onStateChange = new babylonjs_1.Observable();
  100693. this.onAllLoaded = new babylonjs_1.Observable();
  100694. }
  100695. TemplateManager.prototype.initTemplate = function (templates) {
  100696. var _this = this;
  100697. var internalInit = function (dependencyMap, name, parentTemplate) {
  100698. var template = _this.templates[name];
  100699. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  100700. return internalInit(dependencyMap[childName], childName, template);
  100701. });
  100702. var addToParent = function () {
  100703. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  100704. template.appendTo(containingElement);
  100705. _this.checkLoadedState();
  100706. };
  100707. if (parentTemplate && !parentTemplate.parent) {
  100708. parentTemplate.onAppended.add(function () {
  100709. addToParent();
  100710. });
  100711. }
  100712. else {
  100713. addToParent();
  100714. }
  100715. return template;
  100716. };
  100717. this.buildHTMLTree(templates).then(function (htmlTree) {
  100718. internalInit(htmlTree, 'main');
  100719. });
  100720. };
  100721. TemplateManager.prototype.buildHTMLTree = function (templates) {
  100722. var _this = this;
  100723. var promises = Object.keys(templates).map(function (name) {
  100724. var template = new Template(name, templates[name]);
  100725. _this.templates[name] = template;
  100726. return template.initPromise;
  100727. });
  100728. return Promise.all(promises).then(function () {
  100729. var templateStructure = {};
  100730. var buildTree = function (parentObject, name) {
  100731. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  100732. childNodes.forEach(function (element) {
  100733. parentObject[element] = {};
  100734. buildTree(parentObject[element], element);
  100735. });
  100736. };
  100737. buildTree(templateStructure, "main");
  100738. return templateStructure;
  100739. });
  100740. };
  100741. TemplateManager.prototype.getCanvas = function () {
  100742. return this.containerElement.querySelector('canvas');
  100743. };
  100744. TemplateManager.prototype.getTemplate = function (name) {
  100745. return this.templates[name];
  100746. };
  100747. TemplateManager.prototype.checkLoadedState = function () {
  100748. var _this = this;
  100749. var done = Object.keys(this.templates).every(function (key) {
  100750. return _this.templates[key].isLoaded && !!_this.templates[key].parent;
  100751. });
  100752. if (done) {
  100753. this.onAllLoaded.notifyObservers(this);
  100754. }
  100755. };
  100756. return TemplateManager;
  100757. }());
  100758. exports.TemplateManager = TemplateManager;
  100759. var Handlebars = __webpack_require__(18);
  100760. var Template = (function () {
  100761. function Template(name, _configuration) {
  100762. var _this = this;
  100763. this.name = name;
  100764. this._configuration = _configuration;
  100765. this.onInit = new babylonjs_1.Observable();
  100766. this.onLoaded = new babylonjs_1.Observable();
  100767. this.onAppended = new babylonjs_1.Observable();
  100768. this.onStateChange = new babylonjs_1.Observable();
  100769. this.onEventTriggered = new babylonjs_1.Observable();
  100770. this.isLoaded = false;
  100771. this.onInit.notifyObservers(this);
  100772. var htmlContentPromise = getTemplateAsHtml(_configuration);
  100773. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  100774. if (htmlTemplate) {
  100775. var compiledTemplate = Handlebars.compile(htmlTemplate);
  100776. var config = _this._configuration.params || {};
  100777. var rawHtml = compiledTemplate(config);
  100778. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  100779. _this.isLoaded = true;
  100780. _this.onLoaded.notifyObservers(_this);
  100781. }
  100782. return _this;
  100783. });
  100784. }
  100785. Object.defineProperty(Template.prototype, "configuration", {
  100786. get: function () {
  100787. return this._configuration;
  100788. },
  100789. enumerable: true,
  100790. configurable: true
  100791. });
  100792. Template.prototype.getChildElements = function () {
  100793. var childrenArray = [];
  100794. var children = this.fragment.children;
  100795. if (!children) {
  100796. children = this.fragment.querySelectorAll('*');
  100797. }
  100798. for (var i = 0; i < children.length; ++i) {
  100799. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  100800. }
  100801. return childrenArray;
  100802. };
  100803. Template.prototype.appendTo = function (parent) {
  100804. var _this = this;
  100805. if (this.parent) {
  100806. console.error('Already appanded to ', this.parent);
  100807. }
  100808. else {
  100809. this.parent = parent;
  100810. if (this._configuration.id) {
  100811. this.parent.id = this._configuration.id;
  100812. }
  100813. this.parent.appendChild(this.fragment);
  100814. setTimeout(function () {
  100815. _this.registerEvents();
  100816. _this.onAppended.notifyObservers(_this);
  100817. });
  100818. }
  100819. };
  100820. Template.prototype.show = function (visibilityFunction) {
  100821. var _this = this;
  100822. if (visibilityFunction) {
  100823. return visibilityFunction(this).then(function () {
  100824. _this.onStateChange.notifyObservers(_this);
  100825. return _this;
  100826. });
  100827. }
  100828. else {
  100829. this.parent.style.display = 'flex';
  100830. this.onStateChange.notifyObservers(this);
  100831. return Promise.resolve(this);
  100832. }
  100833. };
  100834. Template.prototype.hide = function (visibilityFunction) {
  100835. var _this = this;
  100836. if (visibilityFunction) {
  100837. return visibilityFunction(this).then(function () {
  100838. _this.onStateChange.notifyObservers(_this);
  100839. return _this;
  100840. });
  100841. }
  100842. else {
  100843. this.parent.style.display = 'none';
  100844. this.onStateChange.notifyObservers(this);
  100845. return Promise.resolve(this);
  100846. }
  100847. };
  100848. Template.prototype.registerEvents = function () {
  100849. var _this = this;
  100850. if (this._configuration.events) {
  100851. var _loop_1 = function (eventName) {
  100852. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  100853. var functionToFire_1 = function (selector, event) {
  100854. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  100855. };
  100856. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  100857. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  100858. }
  100859. else if (typeof this_1._configuration.events[eventName] === 'object') {
  100860. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  100861. var event_1 = this_1._configuration.events[eventName] || {};
  100862. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  100863. if (selector.indexOf('#') !== 0) {
  100864. selector = '#' + selector;
  100865. }
  100866. var htmlElement = _this.parent.querySelector(selector);
  100867. htmlElement && htmlElement.addEventListener(eventName, functionToFire_1.bind(_this, selector), false);
  100868. });
  100869. }
  100870. }
  100871. };
  100872. var this_1 = this;
  100873. for (var eventName in this._configuration.events) {
  100874. _loop_1(eventName);
  100875. }
  100876. }
  100877. };
  100878. return Template;
  100879. }());
  100880. exports.Template = Template;
  100881. function getTemplateAsHtml(templateConfig) {
  100882. if (!templateConfig) {
  100883. return Promise.reject('No templateConfig provided');
  100884. }
  100885. else if (templateConfig.html) {
  100886. return Promise.resolve(templateConfig.html);
  100887. }
  100888. else {
  100889. var location_1 = getTemplateLocation(templateConfig);
  100890. if (helper_1.isUrl(location_1)) {
  100891. return helper_1.loadFile(location_1);
  100892. }
  100893. else {
  100894. location_1 = location_1.replace('#', '');
  100895. var element = document.getElementById('#' + location_1);
  100896. if (element) {
  100897. return Promise.resolve(element.innerHTML);
  100898. }
  100899. else {
  100900. return Promise.reject('Template ID not found');
  100901. }
  100902. }
  100903. }
  100904. }
  100905. exports.getTemplateAsHtml = getTemplateAsHtml;
  100906. function getTemplateLocation(templateConfig) {
  100907. if (!templateConfig || typeof templateConfig === 'string') {
  100908. return templateConfig;
  100909. }
  100910. else {
  100911. return templateConfig.location;
  100912. }
  100913. }
  100914. exports.getTemplateLocation = getTemplateLocation;
  100915. /***/ }),
  100916. /* 18 */
  100917. /***/ (function(module, exports, __webpack_require__) {
  100918. /**!
  100919. @license
  100920. handlebars v4.0.11
  100921. Copyright (C) 2011-2017 by Yehuda Katz
  100922. Permission is hereby granted, free of charge, to any person obtaining a copy
  100923. of this software and associated documentation files (the "Software"), to deal
  100924. in the Software without restriction, including without limitation the rights
  100925. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  100926. copies of the Software, and to permit persons to whom the Software is
  100927. furnished to do so, subject to the following conditions:
  100928. The above copyright notice and this permission notice shall be included in
  100929. all copies or substantial portions of the Software.
  100930. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  100931. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  100932. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  100933. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  100934. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  100935. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  100936. THE SOFTWARE.
  100937. */
  100938. !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],
  100939. 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){
  100940. 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"]}])});
  100941. /***/ }),
  100942. /* 19 */
  100943. /***/ (function(module, exports, __webpack_require__) {
  100944. "use strict";
  100945. Object.defineProperty(exports, "__esModule", { value: true });
  100946. var mappers_1 = __webpack_require__(6);
  100947. var types_1 = __webpack_require__(20);
  100948. var merge = __webpack_require__(27);
  100949. var ConfigurationLoader = (function () {
  100950. function ConfigurationLoader() {
  100951. }
  100952. ConfigurationLoader.prototype.loadConfiguration = function (initConfig) {
  100953. if (initConfig === void 0) { initConfig = {}; }
  100954. var loadedConfig = merge({}, initConfig);
  100955. var extendedConfiguration = types_1.getConfigurationType(loadedConfig && loadedConfig.extends);
  100956. loadedConfig = merge(extendedConfiguration, loadedConfig);
  100957. if (loadedConfig.configuration) {
  100958. var mapperType = "json";
  100959. var url = loadedConfig.configuration;
  100960. if (loadedConfig.configuration.url) {
  100961. url = loadedConfig.configuration.url;
  100962. mapperType = loadedConfig.configuration.mapper;
  100963. if (!mapperType) {
  100964. mapperType = loadedConfig.configuration.url.split('.').pop();
  100965. }
  100966. }
  100967. var mapper_1 = mappers_1.mapperManager.getMapper(mapperType);
  100968. return this.loadFile(url).then(function (data) {
  100969. var parsed = mapper_1.map(data);
  100970. return merge(loadedConfig, parsed);
  100971. });
  100972. }
  100973. else {
  100974. return Promise.resolve(loadedConfig);
  100975. }
  100976. };
  100977. ConfigurationLoader.prototype.getConfigurationType = function (type) {
  100978. };
  100979. ConfigurationLoader.prototype.loadFile = function (url) {
  100980. var cacheReference = this.configurationCache;
  100981. if (cacheReference[url]) {
  100982. return Promise.resolve(cacheReference[url]);
  100983. }
  100984. return new Promise(function (resolve, reject) {
  100985. var xhr = new XMLHttpRequest();
  100986. xhr.open('GET', url);
  100987. xhr.send();
  100988. xhr.onreadystatechange = function () {
  100989. var DONE = 4;
  100990. var OK = 200;
  100991. if (xhr.readyState === DONE) {
  100992. if (xhr.status === OK) {
  100993. cacheReference[url] = xhr.responseText;
  100994. resolve(xhr.responseText);
  100995. }
  100996. }
  100997. else {
  100998. console.log('Error: ' + xhr.status, url);
  100999. reject('Error: ' + xhr.status);
  101000. }
  101001. };
  101002. });
  101003. };
  101004. return ConfigurationLoader;
  101005. }());
  101006. exports.ConfigurationLoader = ConfigurationLoader;
  101007. exports.configurationLoader = new ConfigurationLoader();
  101008. exports.default = exports.configurationLoader;
  101009. /***/ }),
  101010. /* 20 */
  101011. /***/ (function(module, exports, __webpack_require__) {
  101012. "use strict";
  101013. Object.defineProperty(exports, "__esModule", { value: true });
  101014. var minimal_1 = __webpack_require__(21);
  101015. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  101016. var default_1 = __webpack_require__(22);
  101017. exports.defaultConfiguration = default_1.defaultConfiguration;
  101018. var getConfigurationType = function (type) {
  101019. switch (type) {
  101020. case 'default':
  101021. return default_1.defaultConfiguration;
  101022. case 'minimal':
  101023. return minimal_1.minimalConfiguration;
  101024. default:
  101025. return default_1.defaultConfiguration;
  101026. }
  101027. };
  101028. exports.getConfigurationType = getConfigurationType;
  101029. /***/ }),
  101030. /* 21 */
  101031. /***/ (function(module, exports, __webpack_require__) {
  101032. "use strict";
  101033. Object.defineProperty(exports, "__esModule", { value: true });
  101034. exports.minimalConfiguration = {
  101035. version: "0.1",
  101036. templates: {
  101037. main: {
  101038. html: __webpack_require__(7)
  101039. },
  101040. loadingScreen: {
  101041. html: __webpack_require__(8),
  101042. params: {
  101043. backgroundColor: "#000000",
  101044. loadingImage: __webpack_require__(9)
  101045. }
  101046. },
  101047. viewer: {
  101048. html: __webpack_require__(10),
  101049. },
  101050. overlay: {
  101051. html: __webpack_require__(11),
  101052. params: {
  101053. closeImage: __webpack_require__(12),
  101054. closeText: 'Close'
  101055. }
  101056. },
  101057. error: {
  101058. html: __webpack_require__(13)
  101059. }
  101060. },
  101061. engine: {
  101062. antialiasing: true
  101063. }
  101064. };
  101065. /***/ }),
  101066. /* 22 */
  101067. /***/ (function(module, exports, __webpack_require__) {
  101068. "use strict";
  101069. Object.defineProperty(exports, "__esModule", { value: true });
  101070. exports.defaultConfiguration = {
  101071. version: "0.1",
  101072. templates: {
  101073. main: {
  101074. html: __webpack_require__(7)
  101075. },
  101076. loadingScreen: {
  101077. html: __webpack_require__(8),
  101078. params: {
  101079. backgroundColor: "#000000",
  101080. loadingImage: __webpack_require__(9)
  101081. }
  101082. },
  101083. viewer: {
  101084. html: __webpack_require__(10),
  101085. },
  101086. navBar: {
  101087. html: __webpack_require__(23),
  101088. params: {
  101089. buttons: [
  101090. {
  101091. id: 'fullscreen-button',
  101092. altText: "Fullscreen",
  101093. image: __webpack_require__(24)
  101094. },
  101095. ],
  101096. visibilityTimeout: 2000
  101097. },
  101098. events: {
  101099. pointerdown: { 'fullscreen-button': true }
  101100. }
  101101. },
  101102. overlay: {
  101103. html: __webpack_require__(11),
  101104. params: {
  101105. closeImage: __webpack_require__(12),
  101106. closeText: 'Close'
  101107. }
  101108. },
  101109. help: {
  101110. html: __webpack_require__(25)
  101111. },
  101112. share: {
  101113. html: __webpack_require__(26)
  101114. },
  101115. error: {
  101116. html: __webpack_require__(13)
  101117. }
  101118. },
  101119. camera: {
  101120. behaviors: {
  101121. autoRotate: 0,
  101122. framing: {
  101123. type: 2,
  101124. zoomOnBoundingInfo: true,
  101125. zoomStopsAnimation: false
  101126. }
  101127. }
  101128. },
  101129. skybox: {
  101130. cubeTexture: {
  101131. url: 'https://playground.babylonjs.com/textures/environment.dds',
  101132. gammaSpace: false
  101133. },
  101134. pbr: true,
  101135. blur: 0.7,
  101136. infiniteDIstance: false,
  101137. material: {
  101138. imageProcessingConfiguration: {
  101139. colorCurves: {
  101140. globalDensity: 89,
  101141. globalHue: 58.88,
  101142. globalSaturation: 94
  101143. },
  101144. colorCurvesEnabled: true,
  101145. exposure: 1.5,
  101146. contrast: 1.66,
  101147. toneMappingEnabled: true,
  101148. vignetteEnabled: true,
  101149. vignetteWeight: 5,
  101150. vignetteColor: { r: 0.8, g: 0.6, b: 0.4 },
  101151. vignetteM: true
  101152. }
  101153. }
  101154. },
  101155. ground: true,
  101156. engine: {
  101157. antialiasing: true
  101158. },
  101159. scene: {
  101160. imageProcessingConfiguration: {
  101161. exposure: 1.4,
  101162. contrast: 1.66,
  101163. toneMappingEnabled: true
  101164. }
  101165. }
  101166. };
  101167. /***/ }),
  101168. /* 23 */
  101169. /***/ (function(module, exports) {
  101170. module.exports = "<style>\r\n nav-bar {\r\n position: absolute;\r\n height: 160px;\r\n width: 100%;\r\n bottom: 0;\r\n background-color: rgba(0, 0, 0, 0.3);\r\n color: white;\r\n transition: 1s;\r\n align-items: flex-start;\r\n justify-content: space-around;\r\n display: flex;\r\n\r\n flex-direction: column;\r\n }\r\n\r\n /* Big screens have room for the entire navbar */\r\n\r\n @media screen and (min-width: 768px) {\r\n nav-bar {\r\n align-items: center;\r\n flex-direction: row;\r\n justify-content: space-between;\r\n height: 80px;\r\n }\r\n }\r\n\r\n div.flex-container {\r\n display: flex;\r\n width: 100%;\r\n }\r\n\r\n div.thumbnail {\r\n position: relative;\r\n overflow: hidden;\r\n display: block;\r\n width: 40px;\r\n height: 40px;\r\n background-size: cover;\r\n background-position: center;\r\n border-radius: 20px;\r\n margin: 0 10px;\r\n }\r\n\r\n div.title-container {\r\n flex-direction: column;\r\n display: flex;\r\n justify-content: space-between;\r\n }\r\n\r\n span.model-title {\r\n font-size: 125%;\r\n }\r\n\r\n span.model-subtitle {\r\n font-size: 90%;\r\n }\r\n\r\n div.button-container {\r\n align-items: center;\r\n justify-content: flex-end;\r\n }\r\n\r\n div.button {\r\n cursor: pointer;\r\n height: 30px;\r\n margin: 0 10px;\r\n }\r\n\r\n div.button img {\r\n height: 100%;\r\n }\r\n</style>\r\n\r\n{{#if disableOnFullscreen}}\r\n<style>\r\n viewer:fullscreen nav-bar {\r\n display: none;\r\n }\r\n\r\n viewer:-moz-full-screen nav-bar {\r\n display: none;\r\n }\r\n\r\n viewer:-webkit-full-screen nav-bar {\r\n display: none;\r\n }\r\n</style>\r\n{{/if}}\r\n\r\n<div class=\"flex-container\" id=\"model-metadata\">\r\n <!-- holding the description -->\r\n <div class=\"thumbnail\">\r\n <!-- holding the thumbnail \r\n <img src=\"{{thumbnail}}\" alt=\"{{title}}\">-->\r\n </div>\r\n <div class=\"title-container\">\r\n\r\n <span class=\"model-title\">{{#if title}}{{title}}{{/if}}</span>\r\n <span class=\"model-subtitle\"> {{#if subtitle}}{{subtitle}} {{/if}}</span>\r\n </div>\r\n</div>\r\n<div class=\"button-container flex-container\">\r\n <!-- holding the buttons -->\r\n {{#each buttons}}\r\n <div id=\"{{id}}\" class=\"button\">\r\n {{#if text}}\r\n <span>{{text}}</span>> {{/if}} {{#if image}}\r\n <img src=\"{{image}}\" alt=\"{{altText}}\"> {{/if}}\r\n </div>\r\n {{/each}}\r\n</div>";
  101171. /***/ }),
  101172. /* 24 */
  101173. /***/ (function(module, exports) {
  101174. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAAASAAAAEgARslrPgAAAG5JREFUaN7t2NEKgCAMBVAX/f8v21MvQTDEHNI5z21wU7HVGgBQJ7IP9t57qmFErOhzO758OysIUO0cLczu0Wxd9mw8bb8CAlQTAAAqDU9ko1+js/tvfxMLUE2AasMz8dsMO+u/UNb2KyAAAPBnFyAoHCsn18AtAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE3LTEwLTI0VDA5OjI5OjA3KzAwOjAwnIEg5AAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNy0xMC0yNFQwOToyOTowNyswMDowMO3cmFgAAAAodEVYdHN2ZzpiYXNlLXVyaQBmaWxlOi8vL3RtcC9tYWdpY2stYU9TenZXZUYevZw/AAAAAElFTkSuQmCC"
  101175. /***/ }),
  101176. /* 25 */
  101177. /***/ (function(module, exports) {
  101178. module.exports = "HELP";
  101179. /***/ }),
  101180. /* 26 */
  101181. /***/ (function(module, exports) {
  101182. module.exports = "SHARE";
  101183. /***/ }),
  101184. /* 27 */
  101185. /***/ (function(module, exports, __webpack_require__) {
  101186. /* WEBPACK VAR INJECTION */(function(global, module) {/**
  101187. * lodash (Custom Build) <https://lodash.com/>
  101188. * Build: `lodash modularize exports="npm" -o ./`
  101189. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  101190. * Released under MIT license <https://lodash.com/license>
  101191. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  101192. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  101193. */
  101194. /** Used as the size to enable large array optimizations. */
  101195. var LARGE_ARRAY_SIZE = 200;
  101196. /** Used to stand-in for `undefined` hash values. */
  101197. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  101198. /** Used as references for various `Number` constants. */
  101199. var MAX_SAFE_INTEGER = 9007199254740991;
  101200. /** `Object#toString` result references. */
  101201. var argsTag = '[object Arguments]',
  101202. arrayTag = '[object Array]',
  101203. boolTag = '[object Boolean]',
  101204. dateTag = '[object Date]',
  101205. errorTag = '[object Error]',
  101206. funcTag = '[object Function]',
  101207. genTag = '[object GeneratorFunction]',
  101208. mapTag = '[object Map]',
  101209. numberTag = '[object Number]',
  101210. objectTag = '[object Object]',
  101211. promiseTag = '[object Promise]',
  101212. regexpTag = '[object RegExp]',
  101213. setTag = '[object Set]',
  101214. stringTag = '[object String]',
  101215. symbolTag = '[object Symbol]',
  101216. weakMapTag = '[object WeakMap]';
  101217. var arrayBufferTag = '[object ArrayBuffer]',
  101218. dataViewTag = '[object DataView]',
  101219. float32Tag = '[object Float32Array]',
  101220. float64Tag = '[object Float64Array]',
  101221. int8Tag = '[object Int8Array]',
  101222. int16Tag = '[object Int16Array]',
  101223. int32Tag = '[object Int32Array]',
  101224. uint8Tag = '[object Uint8Array]',
  101225. uint8ClampedTag = '[object Uint8ClampedArray]',
  101226. uint16Tag = '[object Uint16Array]',
  101227. uint32Tag = '[object Uint32Array]';
  101228. /**
  101229. * Used to match `RegExp`
  101230. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  101231. */
  101232. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  101233. /** Used to match `RegExp` flags from their coerced string values. */
  101234. var reFlags = /\w*$/;
  101235. /** Used to detect host constructors (Safari). */
  101236. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  101237. /** Used to detect unsigned integer values. */
  101238. var reIsUint = /^(?:0|[1-9]\d*)$/;
  101239. /** Used to identify `toStringTag` values of typed arrays. */
  101240. var typedArrayTags = {};
  101241. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  101242. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  101243. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  101244. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  101245. typedArrayTags[uint32Tag] = true;
  101246. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  101247. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  101248. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  101249. typedArrayTags[errorTag] = typedArrayTags[funcTag] =
  101250. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  101251. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  101252. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  101253. typedArrayTags[weakMapTag] = false;
  101254. /** Used to identify `toStringTag` values supported by `_.clone`. */
  101255. var cloneableTags = {};
  101256. cloneableTags[argsTag] = cloneableTags[arrayTag] =
  101257. cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
  101258. cloneableTags[boolTag] = cloneableTags[dateTag] =
  101259. cloneableTags[float32Tag] = cloneableTags[float64Tag] =
  101260. cloneableTags[int8Tag] = cloneableTags[int16Tag] =
  101261. cloneableTags[int32Tag] = cloneableTags[mapTag] =
  101262. cloneableTags[numberTag] = cloneableTags[objectTag] =
  101263. cloneableTags[regexpTag] = cloneableTags[setTag] =
  101264. cloneableTags[stringTag] = cloneableTags[symbolTag] =
  101265. cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
  101266. cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
  101267. cloneableTags[errorTag] = cloneableTags[funcTag] =
  101268. cloneableTags[weakMapTag] = false;
  101269. /** Detect free variable `global` from Node.js. */
  101270. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  101271. /** Detect free variable `self`. */
  101272. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  101273. /** Used as a reference to the global object. */
  101274. var root = freeGlobal || freeSelf || Function('return this')();
  101275. /** Detect free variable `exports`. */
  101276. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  101277. /** Detect free variable `module`. */
  101278. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  101279. /** Detect the popular CommonJS extension `module.exports`. */
  101280. var moduleExports = freeModule && freeModule.exports === freeExports;
  101281. /** Detect free variable `process` from Node.js. */
  101282. var freeProcess = moduleExports && freeGlobal.process;
  101283. /** Used to access faster Node.js helpers. */
  101284. var nodeUtil = (function() {
  101285. try {
  101286. return freeProcess && freeProcess.binding('util');
  101287. } catch (e) {}
  101288. }());
  101289. /* Node.js helper references. */
  101290. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  101291. /**
  101292. * Adds the key-value `pair` to `map`.
  101293. *
  101294. * @private
  101295. * @param {Object} map The map to modify.
  101296. * @param {Array} pair The key-value pair to add.
  101297. * @returns {Object} Returns `map`.
  101298. */
  101299. function addMapEntry(map, pair) {
  101300. // Don't return `map.set` because it's not chainable in IE 11.
  101301. map.set(pair[0], pair[1]);
  101302. return map;
  101303. }
  101304. /**
  101305. * Adds `value` to `set`.
  101306. *
  101307. * @private
  101308. * @param {Object} set The set to modify.
  101309. * @param {*} value The value to add.
  101310. * @returns {Object} Returns `set`.
  101311. */
  101312. function addSetEntry(set, value) {
  101313. // Don't return `set.add` because it's not chainable in IE 11.
  101314. set.add(value);
  101315. return set;
  101316. }
  101317. /**
  101318. * A faster alternative to `Function#apply`, this function invokes `func`
  101319. * with the `this` binding of `thisArg` and the arguments of `args`.
  101320. *
  101321. * @private
  101322. * @param {Function} func The function to invoke.
  101323. * @param {*} thisArg The `this` binding of `func`.
  101324. * @param {Array} args The arguments to invoke `func` with.
  101325. * @returns {*} Returns the result of `func`.
  101326. */
  101327. function apply(func, thisArg, args) {
  101328. switch (args.length) {
  101329. case 0: return func.call(thisArg);
  101330. case 1: return func.call(thisArg, args[0]);
  101331. case 2: return func.call(thisArg, args[0], args[1]);
  101332. case 3: return func.call(thisArg, args[0], args[1], args[2]);
  101333. }
  101334. return func.apply(thisArg, args);
  101335. }
  101336. /**
  101337. * A specialized version of `_.forEach` for arrays without support for
  101338. * iteratee shorthands.
  101339. *
  101340. * @private
  101341. * @param {Array} [array] The array to iterate over.
  101342. * @param {Function} iteratee The function invoked per iteration.
  101343. * @returns {Array} Returns `array`.
  101344. */
  101345. function arrayEach(array, iteratee) {
  101346. var index = -1,
  101347. length = array ? array.length : 0;
  101348. while (++index < length) {
  101349. if (iteratee(array[index], index, array) === false) {
  101350. break;
  101351. }
  101352. }
  101353. return array;
  101354. }
  101355. /**
  101356. * Appends the elements of `values` to `array`.
  101357. *
  101358. * @private
  101359. * @param {Array} array The array to modify.
  101360. * @param {Array} values The values to append.
  101361. * @returns {Array} Returns `array`.
  101362. */
  101363. function arrayPush(array, values) {
  101364. var index = -1,
  101365. length = values.length,
  101366. offset = array.length;
  101367. while (++index < length) {
  101368. array[offset + index] = values[index];
  101369. }
  101370. return array;
  101371. }
  101372. /**
  101373. * A specialized version of `_.reduce` for arrays without support for
  101374. * iteratee shorthands.
  101375. *
  101376. * @private
  101377. * @param {Array} [array] The array to iterate over.
  101378. * @param {Function} iteratee The function invoked per iteration.
  101379. * @param {*} [accumulator] The initial value.
  101380. * @param {boolean} [initAccum] Specify using the first element of `array` as
  101381. * the initial value.
  101382. * @returns {*} Returns the accumulated value.
  101383. */
  101384. function arrayReduce(array, iteratee, accumulator, initAccum) {
  101385. var index = -1,
  101386. length = array ? array.length : 0;
  101387. if (initAccum && length) {
  101388. accumulator = array[++index];
  101389. }
  101390. while (++index < length) {
  101391. accumulator = iteratee(accumulator, array[index], index, array);
  101392. }
  101393. return accumulator;
  101394. }
  101395. /**
  101396. * The base implementation of `_.times` without support for iteratee shorthands
  101397. * or max array length checks.
  101398. *
  101399. * @private
  101400. * @param {number} n The number of times to invoke `iteratee`.
  101401. * @param {Function} iteratee The function invoked per iteration.
  101402. * @returns {Array} Returns the array of results.
  101403. */
  101404. function baseTimes(n, iteratee) {
  101405. var index = -1,
  101406. result = Array(n);
  101407. while (++index < n) {
  101408. result[index] = iteratee(index);
  101409. }
  101410. return result;
  101411. }
  101412. /**
  101413. * The base implementation of `_.unary` without support for storing metadata.
  101414. *
  101415. * @private
  101416. * @param {Function} func The function to cap arguments for.
  101417. * @returns {Function} Returns the new capped function.
  101418. */
  101419. function baseUnary(func) {
  101420. return function(value) {
  101421. return func(value);
  101422. };
  101423. }
  101424. /**
  101425. * Gets the value at `key` of `object`.
  101426. *
  101427. * @private
  101428. * @param {Object} [object] The object to query.
  101429. * @param {string} key The key of the property to get.
  101430. * @returns {*} Returns the property value.
  101431. */
  101432. function getValue(object, key) {
  101433. return object == null ? undefined : object[key];
  101434. }
  101435. /**
  101436. * Checks if `value` is a host object in IE < 9.
  101437. *
  101438. * @private
  101439. * @param {*} value The value to check.
  101440. * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
  101441. */
  101442. function isHostObject(value) {
  101443. // Many host objects are `Object` objects that can coerce to strings
  101444. // despite having improperly defined `toString` methods.
  101445. var result = false;
  101446. if (value != null && typeof value.toString != 'function') {
  101447. try {
  101448. result = !!(value + '');
  101449. } catch (e) {}
  101450. }
  101451. return result;
  101452. }
  101453. /**
  101454. * Converts `map` to its key-value pairs.
  101455. *
  101456. * @private
  101457. * @param {Object} map The map to convert.
  101458. * @returns {Array} Returns the key-value pairs.
  101459. */
  101460. function mapToArray(map) {
  101461. var index = -1,
  101462. result = Array(map.size);
  101463. map.forEach(function(value, key) {
  101464. result[++index] = [key, value];
  101465. });
  101466. return result;
  101467. }
  101468. /**
  101469. * Creates a unary function that invokes `func` with its argument transformed.
  101470. *
  101471. * @private
  101472. * @param {Function} func The function to wrap.
  101473. * @param {Function} transform The argument transform.
  101474. * @returns {Function} Returns the new function.
  101475. */
  101476. function overArg(func, transform) {
  101477. return function(arg) {
  101478. return func(transform(arg));
  101479. };
  101480. }
  101481. /**
  101482. * Converts `set` to an array of its values.
  101483. *
  101484. * @private
  101485. * @param {Object} set The set to convert.
  101486. * @returns {Array} Returns the values.
  101487. */
  101488. function setToArray(set) {
  101489. var index = -1,
  101490. result = Array(set.size);
  101491. set.forEach(function(value) {
  101492. result[++index] = value;
  101493. });
  101494. return result;
  101495. }
  101496. /** Used for built-in method references. */
  101497. var arrayProto = Array.prototype,
  101498. funcProto = Function.prototype,
  101499. objectProto = Object.prototype;
  101500. /** Used to detect overreaching core-js shims. */
  101501. var coreJsData = root['__core-js_shared__'];
  101502. /** Used to detect methods masquerading as native. */
  101503. var maskSrcKey = (function() {
  101504. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  101505. return uid ? ('Symbol(src)_1.' + uid) : '';
  101506. }());
  101507. /** Used to resolve the decompiled source of functions. */
  101508. var funcToString = funcProto.toString;
  101509. /** Used to check objects for own properties. */
  101510. var hasOwnProperty = objectProto.hasOwnProperty;
  101511. /** Used to infer the `Object` constructor. */
  101512. var objectCtorString = funcToString.call(Object);
  101513. /**
  101514. * Used to resolve the
  101515. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  101516. * of values.
  101517. */
  101518. var objectToString = objectProto.toString;
  101519. /** Used to detect if a method is native. */
  101520. var reIsNative = RegExp('^' +
  101521. funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  101522. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  101523. );
  101524. /** Built-in value references. */
  101525. var Buffer = moduleExports ? root.Buffer : undefined,
  101526. Symbol = root.Symbol,
  101527. Uint8Array = root.Uint8Array,
  101528. getPrototype = overArg(Object.getPrototypeOf, Object),
  101529. objectCreate = Object.create,
  101530. propertyIsEnumerable = objectProto.propertyIsEnumerable,
  101531. splice = arrayProto.splice;
  101532. /* Built-in method references for those with the same name as other `lodash` methods. */
  101533. var nativeGetSymbols = Object.getOwnPropertySymbols,
  101534. nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
  101535. nativeKeys = overArg(Object.keys, Object),
  101536. nativeMax = Math.max;
  101537. /* Built-in method references that are verified to be native. */
  101538. var DataView = getNative(root, 'DataView'),
  101539. Map = getNative(root, 'Map'),
  101540. Promise = getNative(root, 'Promise'),
  101541. Set = getNative(root, 'Set'),
  101542. WeakMap = getNative(root, 'WeakMap'),
  101543. nativeCreate = getNative(Object, 'create');
  101544. /** Used to detect maps, sets, and weakmaps. */
  101545. var dataViewCtorString = toSource(DataView),
  101546. mapCtorString = toSource(Map),
  101547. promiseCtorString = toSource(Promise),
  101548. setCtorString = toSource(Set),
  101549. weakMapCtorString = toSource(WeakMap);
  101550. /** Used to convert symbols to primitives and strings. */
  101551. var symbolProto = Symbol ? Symbol.prototype : undefined,
  101552. symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
  101553. /**
  101554. * Creates a hash object.
  101555. *
  101556. * @private
  101557. * @constructor
  101558. * @param {Array} [entries] The key-value pairs to cache.
  101559. */
  101560. function Hash(entries) {
  101561. var index = -1,
  101562. length = entries ? entries.length : 0;
  101563. this.clear();
  101564. while (++index < length) {
  101565. var entry = entries[index];
  101566. this.set(entry[0], entry[1]);
  101567. }
  101568. }
  101569. /**
  101570. * Removes all key-value entries from the hash.
  101571. *
  101572. * @private
  101573. * @name clear
  101574. * @memberOf Hash
  101575. */
  101576. function hashClear() {
  101577. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  101578. }
  101579. /**
  101580. * Removes `key` and its value from the hash.
  101581. *
  101582. * @private
  101583. * @name delete
  101584. * @memberOf Hash
  101585. * @param {Object} hash The hash to modify.
  101586. * @param {string} key The key of the value to remove.
  101587. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  101588. */
  101589. function hashDelete(key) {
  101590. return this.has(key) && delete this.__data__[key];
  101591. }
  101592. /**
  101593. * Gets the hash value for `key`.
  101594. *
  101595. * @private
  101596. * @name get
  101597. * @memberOf Hash
  101598. * @param {string} key The key of the value to get.
  101599. * @returns {*} Returns the entry value.
  101600. */
  101601. function hashGet(key) {
  101602. var data = this.__data__;
  101603. if (nativeCreate) {
  101604. var result = data[key];
  101605. return result === HASH_UNDEFINED ? undefined : result;
  101606. }
  101607. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  101608. }
  101609. /**
  101610. * Checks if a hash value for `key` exists.
  101611. *
  101612. * @private
  101613. * @name has
  101614. * @memberOf Hash
  101615. * @param {string} key The key of the entry to check.
  101616. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  101617. */
  101618. function hashHas(key) {
  101619. var data = this.__data__;
  101620. return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
  101621. }
  101622. /**
  101623. * Sets the hash `key` to `value`.
  101624. *
  101625. * @private
  101626. * @name set
  101627. * @memberOf Hash
  101628. * @param {string} key The key of the value to set.
  101629. * @param {*} value The value to set.
  101630. * @returns {Object} Returns the hash instance.
  101631. */
  101632. function hashSet(key, value) {
  101633. var data = this.__data__;
  101634. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  101635. return this;
  101636. }
  101637. // Add methods to `Hash`.
  101638. Hash.prototype.clear = hashClear;
  101639. Hash.prototype['delete'] = hashDelete;
  101640. Hash.prototype.get = hashGet;
  101641. Hash.prototype.has = hashHas;
  101642. Hash.prototype.set = hashSet;
  101643. /**
  101644. * Creates an list cache object.
  101645. *
  101646. * @private
  101647. * @constructor
  101648. * @param {Array} [entries] The key-value pairs to cache.
  101649. */
  101650. function ListCache(entries) {
  101651. var index = -1,
  101652. length = entries ? entries.length : 0;
  101653. this.clear();
  101654. while (++index < length) {
  101655. var entry = entries[index];
  101656. this.set(entry[0], entry[1]);
  101657. }
  101658. }
  101659. /**
  101660. * Removes all key-value entries from the list cache.
  101661. *
  101662. * @private
  101663. * @name clear
  101664. * @memberOf ListCache
  101665. */
  101666. function listCacheClear() {
  101667. this.__data__ = [];
  101668. }
  101669. /**
  101670. * Removes `key` and its value from the list cache.
  101671. *
  101672. * @private
  101673. * @name delete
  101674. * @memberOf ListCache
  101675. * @param {string} key The key of the value to remove.
  101676. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  101677. */
  101678. function listCacheDelete(key) {
  101679. var data = this.__data__,
  101680. index = assocIndexOf(data, key);
  101681. if (index < 0) {
  101682. return false;
  101683. }
  101684. var lastIndex = data.length - 1;
  101685. if (index == lastIndex) {
  101686. data.pop();
  101687. } else {
  101688. splice.call(data, index, 1);
  101689. }
  101690. return true;
  101691. }
  101692. /**
  101693. * Gets the list cache value for `key`.
  101694. *
  101695. * @private
  101696. * @name get
  101697. * @memberOf ListCache
  101698. * @param {string} key The key of the value to get.
  101699. * @returns {*} Returns the entry value.
  101700. */
  101701. function listCacheGet(key) {
  101702. var data = this.__data__,
  101703. index = assocIndexOf(data, key);
  101704. return index < 0 ? undefined : data[index][1];
  101705. }
  101706. /**
  101707. * Checks if a list cache value for `key` exists.
  101708. *
  101709. * @private
  101710. * @name has
  101711. * @memberOf ListCache
  101712. * @param {string} key The key of the entry to check.
  101713. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  101714. */
  101715. function listCacheHas(key) {
  101716. return assocIndexOf(this.__data__, key) > -1;
  101717. }
  101718. /**
  101719. * Sets the list cache `key` to `value`.
  101720. *
  101721. * @private
  101722. * @name set
  101723. * @memberOf ListCache
  101724. * @param {string} key The key of the value to set.
  101725. * @param {*} value The value to set.
  101726. * @returns {Object} Returns the list cache instance.
  101727. */
  101728. function listCacheSet(key, value) {
  101729. var data = this.__data__,
  101730. index = assocIndexOf(data, key);
  101731. if (index < 0) {
  101732. data.push([key, value]);
  101733. } else {
  101734. data[index][1] = value;
  101735. }
  101736. return this;
  101737. }
  101738. // Add methods to `ListCache`.
  101739. ListCache.prototype.clear = listCacheClear;
  101740. ListCache.prototype['delete'] = listCacheDelete;
  101741. ListCache.prototype.get = listCacheGet;
  101742. ListCache.prototype.has = listCacheHas;
  101743. ListCache.prototype.set = listCacheSet;
  101744. /**
  101745. * Creates a map cache object to store key-value pairs.
  101746. *
  101747. * @private
  101748. * @constructor
  101749. * @param {Array} [entries] The key-value pairs to cache.
  101750. */
  101751. function MapCache(entries) {
  101752. var index = -1,
  101753. length = entries ? entries.length : 0;
  101754. this.clear();
  101755. while (++index < length) {
  101756. var entry = entries[index];
  101757. this.set(entry[0], entry[1]);
  101758. }
  101759. }
  101760. /**
  101761. * Removes all key-value entries from the map.
  101762. *
  101763. * @private
  101764. * @name clear
  101765. * @memberOf MapCache
  101766. */
  101767. function mapCacheClear() {
  101768. this.__data__ = {
  101769. 'hash': new Hash,
  101770. 'map': new (Map || ListCache),
  101771. 'string': new Hash
  101772. };
  101773. }
  101774. /**
  101775. * Removes `key` and its value from the map.
  101776. *
  101777. * @private
  101778. * @name delete
  101779. * @memberOf MapCache
  101780. * @param {string} key The key of the value to remove.
  101781. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  101782. */
  101783. function mapCacheDelete(key) {
  101784. return getMapData(this, key)['delete'](key);
  101785. }
  101786. /**
  101787. * Gets the map value for `key`.
  101788. *
  101789. * @private
  101790. * @name get
  101791. * @memberOf MapCache
  101792. * @param {string} key The key of the value to get.
  101793. * @returns {*} Returns the entry value.
  101794. */
  101795. function mapCacheGet(key) {
  101796. return getMapData(this, key).get(key);
  101797. }
  101798. /**
  101799. * Checks if a map value for `key` exists.
  101800. *
  101801. * @private
  101802. * @name has
  101803. * @memberOf MapCache
  101804. * @param {string} key The key of the entry to check.
  101805. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  101806. */
  101807. function mapCacheHas(key) {
  101808. return getMapData(this, key).has(key);
  101809. }
  101810. /**
  101811. * Sets the map `key` to `value`.
  101812. *
  101813. * @private
  101814. * @name set
  101815. * @memberOf MapCache
  101816. * @param {string} key The key of the value to set.
  101817. * @param {*} value The value to set.
  101818. * @returns {Object} Returns the map cache instance.
  101819. */
  101820. function mapCacheSet(key, value) {
  101821. getMapData(this, key).set(key, value);
  101822. return this;
  101823. }
  101824. // Add methods to `MapCache`.
  101825. MapCache.prototype.clear = mapCacheClear;
  101826. MapCache.prototype['delete'] = mapCacheDelete;
  101827. MapCache.prototype.get = mapCacheGet;
  101828. MapCache.prototype.has = mapCacheHas;
  101829. MapCache.prototype.set = mapCacheSet;
  101830. /**
  101831. * Creates a stack cache object to store key-value pairs.
  101832. *
  101833. * @private
  101834. * @constructor
  101835. * @param {Array} [entries] The key-value pairs to cache.
  101836. */
  101837. function Stack(entries) {
  101838. this.__data__ = new ListCache(entries);
  101839. }
  101840. /**
  101841. * Removes all key-value entries from the stack.
  101842. *
  101843. * @private
  101844. * @name clear
  101845. * @memberOf Stack
  101846. */
  101847. function stackClear() {
  101848. this.__data__ = new ListCache;
  101849. }
  101850. /**
  101851. * Removes `key` and its value from the stack.
  101852. *
  101853. * @private
  101854. * @name delete
  101855. * @memberOf Stack
  101856. * @param {string} key The key of the value to remove.
  101857. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  101858. */
  101859. function stackDelete(key) {
  101860. return this.__data__['delete'](key);
  101861. }
  101862. /**
  101863. * Gets the stack value for `key`.
  101864. *
  101865. * @private
  101866. * @name get
  101867. * @memberOf Stack
  101868. * @param {string} key The key of the value to get.
  101869. * @returns {*} Returns the entry value.
  101870. */
  101871. function stackGet(key) {
  101872. return this.__data__.get(key);
  101873. }
  101874. /**
  101875. * Checks if a stack value for `key` exists.
  101876. *
  101877. * @private
  101878. * @name has
  101879. * @memberOf Stack
  101880. * @param {string} key The key of the entry to check.
  101881. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  101882. */
  101883. function stackHas(key) {
  101884. return this.__data__.has(key);
  101885. }
  101886. /**
  101887. * Sets the stack `key` to `value`.
  101888. *
  101889. * @private
  101890. * @name set
  101891. * @memberOf Stack
  101892. * @param {string} key The key of the value to set.
  101893. * @param {*} value The value to set.
  101894. * @returns {Object} Returns the stack cache instance.
  101895. */
  101896. function stackSet(key, value) {
  101897. var cache = this.__data__;
  101898. if (cache instanceof ListCache) {
  101899. var pairs = cache.__data__;
  101900. if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  101901. pairs.push([key, value]);
  101902. return this;
  101903. }
  101904. cache = this.__data__ = new MapCache(pairs);
  101905. }
  101906. cache.set(key, value);
  101907. return this;
  101908. }
  101909. // Add methods to `Stack`.
  101910. Stack.prototype.clear = stackClear;
  101911. Stack.prototype['delete'] = stackDelete;
  101912. Stack.prototype.get = stackGet;
  101913. Stack.prototype.has = stackHas;
  101914. Stack.prototype.set = stackSet;
  101915. /**
  101916. * Creates an array of the enumerable property names of the array-like `value`.
  101917. *
  101918. * @private
  101919. * @param {*} value The value to query.
  101920. * @param {boolean} inherited Specify returning inherited property names.
  101921. * @returns {Array} Returns the array of property names.
  101922. */
  101923. function arrayLikeKeys(value, inherited) {
  101924. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  101925. // Safari 9 makes `arguments.length` enumerable in strict mode.
  101926. var result = (isArray(value) || isArguments(value))
  101927. ? baseTimes(value.length, String)
  101928. : [];
  101929. var length = result.length,
  101930. skipIndexes = !!length;
  101931. for (var key in value) {
  101932. if ((inherited || hasOwnProperty.call(value, key)) &&
  101933. !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
  101934. result.push(key);
  101935. }
  101936. }
  101937. return result;
  101938. }
  101939. /**
  101940. * This function is like `assignValue` except that it doesn't assign
  101941. * `undefined` values.
  101942. *
  101943. * @private
  101944. * @param {Object} object The object to modify.
  101945. * @param {string} key The key of the property to assign.
  101946. * @param {*} value The value to assign.
  101947. */
  101948. function assignMergeValue(object, key, value) {
  101949. if ((value !== undefined && !eq(object[key], value)) ||
  101950. (typeof key == 'number' && value === undefined && !(key in object))) {
  101951. object[key] = value;
  101952. }
  101953. }
  101954. /**
  101955. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  101956. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  101957. * for equality comparisons.
  101958. *
  101959. * @private
  101960. * @param {Object} object The object to modify.
  101961. * @param {string} key The key of the property to assign.
  101962. * @param {*} value The value to assign.
  101963. */
  101964. function assignValue(object, key, value) {
  101965. var objValue = object[key];
  101966. if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
  101967. (value === undefined && !(key in object))) {
  101968. object[key] = value;
  101969. }
  101970. }
  101971. /**
  101972. * Gets the index at which the `key` is found in `array` of key-value pairs.
  101973. *
  101974. * @private
  101975. * @param {Array} array The array to inspect.
  101976. * @param {*} key The key to search for.
  101977. * @returns {number} Returns the index of the matched value, else `-1`.
  101978. */
  101979. function assocIndexOf(array, key) {
  101980. var length = array.length;
  101981. while (length--) {
  101982. if (eq(array[length][0], key)) {
  101983. return length;
  101984. }
  101985. }
  101986. return -1;
  101987. }
  101988. /**
  101989. * The base implementation of `_.assign` without support for multiple sources
  101990. * or `customizer` functions.
  101991. *
  101992. * @private
  101993. * @param {Object} object The destination object.
  101994. * @param {Object} source The source object.
  101995. * @returns {Object} Returns `object`.
  101996. */
  101997. function baseAssign(object, source) {
  101998. return object && copyObject(source, keys(source), object);
  101999. }
  102000. /**
  102001. * The base implementation of `_.clone` and `_.cloneDeep` which tracks
  102002. * traversed objects.
  102003. *
  102004. * @private
  102005. * @param {*} value The value to clone.
  102006. * @param {boolean} [isDeep] Specify a deep clone.
  102007. * @param {boolean} [isFull] Specify a clone including symbols.
  102008. * @param {Function} [customizer] The function to customize cloning.
  102009. * @param {string} [key] The key of `value`.
  102010. * @param {Object} [object] The parent object of `value`.
  102011. * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
  102012. * @returns {*} Returns the cloned value.
  102013. */
  102014. function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
  102015. var result;
  102016. if (customizer) {
  102017. result = object ? customizer(value, key, object, stack) : customizer(value);
  102018. }
  102019. if (result !== undefined) {
  102020. return result;
  102021. }
  102022. if (!isObject(value)) {
  102023. return value;
  102024. }
  102025. var isArr = isArray(value);
  102026. if (isArr) {
  102027. result = initCloneArray(value);
  102028. if (!isDeep) {
  102029. return copyArray(value, result);
  102030. }
  102031. } else {
  102032. var tag = getTag(value),
  102033. isFunc = tag == funcTag || tag == genTag;
  102034. if (isBuffer(value)) {
  102035. return cloneBuffer(value, isDeep);
  102036. }
  102037. if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
  102038. if (isHostObject(value)) {
  102039. return object ? value : {};
  102040. }
  102041. result = initCloneObject(isFunc ? {} : value);
  102042. if (!isDeep) {
  102043. return copySymbols(value, baseAssign(result, value));
  102044. }
  102045. } else {
  102046. if (!cloneableTags[tag]) {
  102047. return object ? value : {};
  102048. }
  102049. result = initCloneByTag(value, tag, baseClone, isDeep);
  102050. }
  102051. }
  102052. // Check for circular references and return its corresponding clone.
  102053. stack || (stack = new Stack);
  102054. var stacked = stack.get(value);
  102055. if (stacked) {
  102056. return stacked;
  102057. }
  102058. stack.set(value, result);
  102059. if (!isArr) {
  102060. var props = isFull ? getAllKeys(value) : keys(value);
  102061. }
  102062. arrayEach(props || value, function(subValue, key) {
  102063. if (props) {
  102064. key = subValue;
  102065. subValue = value[key];
  102066. }
  102067. // Recursively populate clone (susceptible to call stack limits).
  102068. assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
  102069. });
  102070. return result;
  102071. }
  102072. /**
  102073. * The base implementation of `_.create` without support for assigning
  102074. * properties to the created object.
  102075. *
  102076. * @private
  102077. * @param {Object} prototype The object to inherit from.
  102078. * @returns {Object} Returns the new object.
  102079. */
  102080. function baseCreate(proto) {
  102081. return isObject(proto) ? objectCreate(proto) : {};
  102082. }
  102083. /**
  102084. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  102085. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  102086. * symbols of `object`.
  102087. *
  102088. * @private
  102089. * @param {Object} object The object to query.
  102090. * @param {Function} keysFunc The function to get the keys of `object`.
  102091. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  102092. * @returns {Array} Returns the array of property names and symbols.
  102093. */
  102094. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  102095. var result = keysFunc(object);
  102096. return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
  102097. }
  102098. /**
  102099. * The base implementation of `getTag`.
  102100. *
  102101. * @private
  102102. * @param {*} value The value to query.
  102103. * @returns {string} Returns the `toStringTag`.
  102104. */
  102105. function baseGetTag(value) {
  102106. return objectToString.call(value);
  102107. }
  102108. /**
  102109. * The base implementation of `_.isNative` without bad shim checks.
  102110. *
  102111. * @private
  102112. * @param {*} value The value to check.
  102113. * @returns {boolean} Returns `true` if `value` is a native function,
  102114. * else `false`.
  102115. */
  102116. function baseIsNative(value) {
  102117. if (!isObject(value) || isMasked(value)) {
  102118. return false;
  102119. }
  102120. var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
  102121. return pattern.test(toSource(value));
  102122. }
  102123. /**
  102124. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  102125. *
  102126. * @private
  102127. * @param {*} value The value to check.
  102128. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  102129. */
  102130. function baseIsTypedArray(value) {
  102131. return isObjectLike(value) &&
  102132. isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
  102133. }
  102134. /**
  102135. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  102136. *
  102137. * @private
  102138. * @param {Object} object The object to query.
  102139. * @returns {Array} Returns the array of property names.
  102140. */
  102141. function baseKeys(object) {
  102142. if (!isPrototype(object)) {
  102143. return nativeKeys(object);
  102144. }
  102145. var result = [];
  102146. for (var key in Object(object)) {
  102147. if (hasOwnProperty.call(object, key) && key != 'constructor') {
  102148. result.push(key);
  102149. }
  102150. }
  102151. return result;
  102152. }
  102153. /**
  102154. * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
  102155. *
  102156. * @private
  102157. * @param {Object} object The object to query.
  102158. * @returns {Array} Returns the array of property names.
  102159. */
  102160. function baseKeysIn(object) {
  102161. if (!isObject(object)) {
  102162. return nativeKeysIn(object);
  102163. }
  102164. var isProto = isPrototype(object),
  102165. result = [];
  102166. for (var key in object) {
  102167. if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
  102168. result.push(key);
  102169. }
  102170. }
  102171. return result;
  102172. }
  102173. /**
  102174. * The base implementation of `_.merge` without support for multiple sources.
  102175. *
  102176. * @private
  102177. * @param {Object} object The destination object.
  102178. * @param {Object} source The source object.
  102179. * @param {number} srcIndex The index of `source`.
  102180. * @param {Function} [customizer] The function to customize merged values.
  102181. * @param {Object} [stack] Tracks traversed source values and their merged
  102182. * counterparts.
  102183. */
  102184. function baseMerge(object, source, srcIndex, customizer, stack) {
  102185. if (object === source) {
  102186. return;
  102187. }
  102188. if (!(isArray(source) || isTypedArray(source))) {
  102189. var props = baseKeysIn(source);
  102190. }
  102191. arrayEach(props || source, function(srcValue, key) {
  102192. if (props) {
  102193. key = srcValue;
  102194. srcValue = source[key];
  102195. }
  102196. if (isObject(srcValue)) {
  102197. stack || (stack = new Stack);
  102198. baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
  102199. }
  102200. else {
  102201. var newValue = customizer
  102202. ? customizer(object[key], srcValue, (key + ''), object, source, stack)
  102203. : undefined;
  102204. if (newValue === undefined) {
  102205. newValue = srcValue;
  102206. }
  102207. assignMergeValue(object, key, newValue);
  102208. }
  102209. });
  102210. }
  102211. /**
  102212. * A specialized version of `baseMerge` for arrays and objects which performs
  102213. * deep merges and tracks traversed objects enabling objects with circular
  102214. * references to be merged.
  102215. *
  102216. * @private
  102217. * @param {Object} object The destination object.
  102218. * @param {Object} source The source object.
  102219. * @param {string} key The key of the value to merge.
  102220. * @param {number} srcIndex The index of `source`.
  102221. * @param {Function} mergeFunc The function to merge values.
  102222. * @param {Function} [customizer] The function to customize assigned values.
  102223. * @param {Object} [stack] Tracks traversed source values and their merged
  102224. * counterparts.
  102225. */
  102226. function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
  102227. var objValue = object[key],
  102228. srcValue = source[key],
  102229. stacked = stack.get(srcValue);
  102230. if (stacked) {
  102231. assignMergeValue(object, key, stacked);
  102232. return;
  102233. }
  102234. var newValue = customizer
  102235. ? customizer(objValue, srcValue, (key + ''), object, source, stack)
  102236. : undefined;
  102237. var isCommon = newValue === undefined;
  102238. if (isCommon) {
  102239. newValue = srcValue;
  102240. if (isArray(srcValue) || isTypedArray(srcValue)) {
  102241. if (isArray(objValue)) {
  102242. newValue = objValue;
  102243. }
  102244. else if (isArrayLikeObject(objValue)) {
  102245. newValue = copyArray(objValue);
  102246. }
  102247. else {
  102248. isCommon = false;
  102249. newValue = baseClone(srcValue, true);
  102250. }
  102251. }
  102252. else if (isPlainObject(srcValue) || isArguments(srcValue)) {
  102253. if (isArguments(objValue)) {
  102254. newValue = toPlainObject(objValue);
  102255. }
  102256. else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
  102257. isCommon = false;
  102258. newValue = baseClone(srcValue, true);
  102259. }
  102260. else {
  102261. newValue = objValue;
  102262. }
  102263. }
  102264. else {
  102265. isCommon = false;
  102266. }
  102267. }
  102268. if (isCommon) {
  102269. // Recursively merge objects and arrays (susceptible to call stack limits).
  102270. stack.set(srcValue, newValue);
  102271. mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
  102272. stack['delete'](srcValue);
  102273. }
  102274. assignMergeValue(object, key, newValue);
  102275. }
  102276. /**
  102277. * The base implementation of `_.rest` which doesn't validate or coerce arguments.
  102278. *
  102279. * @private
  102280. * @param {Function} func The function to apply a rest parameter to.
  102281. * @param {number} [start=func.length-1] The start position of the rest parameter.
  102282. * @returns {Function} Returns the new function.
  102283. */
  102284. function baseRest(func, start) {
  102285. start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  102286. return function() {
  102287. var args = arguments,
  102288. index = -1,
  102289. length = nativeMax(args.length - start, 0),
  102290. array = Array(length);
  102291. while (++index < length) {
  102292. array[index] = args[start + index];
  102293. }
  102294. index = -1;
  102295. var otherArgs = Array(start + 1);
  102296. while (++index < start) {
  102297. otherArgs[index] = args[index];
  102298. }
  102299. otherArgs[start] = array;
  102300. return apply(func, this, otherArgs);
  102301. };
  102302. }
  102303. /**
  102304. * Creates a clone of `buffer`.
  102305. *
  102306. * @private
  102307. * @param {Buffer} buffer The buffer to clone.
  102308. * @param {boolean} [isDeep] Specify a deep clone.
  102309. * @returns {Buffer} Returns the cloned buffer.
  102310. */
  102311. function cloneBuffer(buffer, isDeep) {
  102312. if (isDeep) {
  102313. return buffer.slice();
  102314. }
  102315. var result = new buffer.constructor(buffer.length);
  102316. buffer.copy(result);
  102317. return result;
  102318. }
  102319. /**
  102320. * Creates a clone of `arrayBuffer`.
  102321. *
  102322. * @private
  102323. * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
  102324. * @returns {ArrayBuffer} Returns the cloned array buffer.
  102325. */
  102326. function cloneArrayBuffer(arrayBuffer) {
  102327. var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  102328. new Uint8Array(result).set(new Uint8Array(arrayBuffer));
  102329. return result;
  102330. }
  102331. /**
  102332. * Creates a clone of `dataView`.
  102333. *
  102334. * @private
  102335. * @param {Object} dataView The data view to clone.
  102336. * @param {boolean} [isDeep] Specify a deep clone.
  102337. * @returns {Object} Returns the cloned data view.
  102338. */
  102339. function cloneDataView(dataView, isDeep) {
  102340. var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  102341. return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
  102342. }
  102343. /**
  102344. * Creates a clone of `map`.
  102345. *
  102346. * @private
  102347. * @param {Object} map The map to clone.
  102348. * @param {Function} cloneFunc The function to clone values.
  102349. * @param {boolean} [isDeep] Specify a deep clone.
  102350. * @returns {Object} Returns the cloned map.
  102351. */
  102352. function cloneMap(map, isDeep, cloneFunc) {
  102353. var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
  102354. return arrayReduce(array, addMapEntry, new map.constructor);
  102355. }
  102356. /**
  102357. * Creates a clone of `regexp`.
  102358. *
  102359. * @private
  102360. * @param {Object} regexp The regexp to clone.
  102361. * @returns {Object} Returns the cloned regexp.
  102362. */
  102363. function cloneRegExp(regexp) {
  102364. var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  102365. result.lastIndex = regexp.lastIndex;
  102366. return result;
  102367. }
  102368. /**
  102369. * Creates a clone of `set`.
  102370. *
  102371. * @private
  102372. * @param {Object} set The set to clone.
  102373. * @param {Function} cloneFunc The function to clone values.
  102374. * @param {boolean} [isDeep] Specify a deep clone.
  102375. * @returns {Object} Returns the cloned set.
  102376. */
  102377. function cloneSet(set, isDeep, cloneFunc) {
  102378. var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
  102379. return arrayReduce(array, addSetEntry, new set.constructor);
  102380. }
  102381. /**
  102382. * Creates a clone of the `symbol` object.
  102383. *
  102384. * @private
  102385. * @param {Object} symbol The symbol object to clone.
  102386. * @returns {Object} Returns the cloned symbol object.
  102387. */
  102388. function cloneSymbol(symbol) {
  102389. return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
  102390. }
  102391. /**
  102392. * Creates a clone of `typedArray`.
  102393. *
  102394. * @private
  102395. * @param {Object} typedArray The typed array to clone.
  102396. * @param {boolean} [isDeep] Specify a deep clone.
  102397. * @returns {Object} Returns the cloned typed array.
  102398. */
  102399. function cloneTypedArray(typedArray, isDeep) {
  102400. var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  102401. return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
  102402. }
  102403. /**
  102404. * Copies the values of `source` to `array`.
  102405. *
  102406. * @private
  102407. * @param {Array} source The array to copy values from.
  102408. * @param {Array} [array=[]] The array to copy values to.
  102409. * @returns {Array} Returns `array`.
  102410. */
  102411. function copyArray(source, array) {
  102412. var index = -1,
  102413. length = source.length;
  102414. array || (array = Array(length));
  102415. while (++index < length) {
  102416. array[index] = source[index];
  102417. }
  102418. return array;
  102419. }
  102420. /**
  102421. * Copies properties of `source` to `object`.
  102422. *
  102423. * @private
  102424. * @param {Object} source The object to copy properties from.
  102425. * @param {Array} props The property identifiers to copy.
  102426. * @param {Object} [object={}] The object to copy properties to.
  102427. * @param {Function} [customizer] The function to customize copied values.
  102428. * @returns {Object} Returns `object`.
  102429. */
  102430. function copyObject(source, props, object, customizer) {
  102431. object || (object = {});
  102432. var index = -1,
  102433. length = props.length;
  102434. while (++index < length) {
  102435. var key = props[index];
  102436. var newValue = customizer
  102437. ? customizer(object[key], source[key], key, object, source)
  102438. : undefined;
  102439. assignValue(object, key, newValue === undefined ? source[key] : newValue);
  102440. }
  102441. return object;
  102442. }
  102443. /**
  102444. * Copies own symbol properties of `source` to `object`.
  102445. *
  102446. * @private
  102447. * @param {Object} source The object to copy symbols from.
  102448. * @param {Object} [object={}] The object to copy symbols to.
  102449. * @returns {Object} Returns `object`.
  102450. */
  102451. function copySymbols(source, object) {
  102452. return copyObject(source, getSymbols(source), object);
  102453. }
  102454. /**
  102455. * Creates a function like `_.assign`.
  102456. *
  102457. * @private
  102458. * @param {Function} assigner The function to assign values.
  102459. * @returns {Function} Returns the new assigner function.
  102460. */
  102461. function createAssigner(assigner) {
  102462. return baseRest(function(object, sources) {
  102463. var index = -1,
  102464. length = sources.length,
  102465. customizer = length > 1 ? sources[length - 1] : undefined,
  102466. guard = length > 2 ? sources[2] : undefined;
  102467. customizer = (assigner.length > 3 && typeof customizer == 'function')
  102468. ? (length--, customizer)
  102469. : undefined;
  102470. if (guard && isIterateeCall(sources[0], sources[1], guard)) {
  102471. customizer = length < 3 ? undefined : customizer;
  102472. length = 1;
  102473. }
  102474. object = Object(object);
  102475. while (++index < length) {
  102476. var source = sources[index];
  102477. if (source) {
  102478. assigner(object, source, index, customizer);
  102479. }
  102480. }
  102481. return object;
  102482. });
  102483. }
  102484. /**
  102485. * Creates an array of own enumerable property names and symbols of `object`.
  102486. *
  102487. * @private
  102488. * @param {Object} object The object to query.
  102489. * @returns {Array} Returns the array of property names and symbols.
  102490. */
  102491. function getAllKeys(object) {
  102492. return baseGetAllKeys(object, keys, getSymbols);
  102493. }
  102494. /**
  102495. * Gets the data for `map`.
  102496. *
  102497. * @private
  102498. * @param {Object} map The map to query.
  102499. * @param {string} key The reference key.
  102500. * @returns {*} Returns the map data.
  102501. */
  102502. function getMapData(map, key) {
  102503. var data = map.__data__;
  102504. return isKeyable(key)
  102505. ? data[typeof key == 'string' ? 'string' : 'hash']
  102506. : data.map;
  102507. }
  102508. /**
  102509. * Gets the native function at `key` of `object`.
  102510. *
  102511. * @private
  102512. * @param {Object} object The object to query.
  102513. * @param {string} key The key of the method to get.
  102514. * @returns {*} Returns the function if it's native, else `undefined`.
  102515. */
  102516. function getNative(object, key) {
  102517. var value = getValue(object, key);
  102518. return baseIsNative(value) ? value : undefined;
  102519. }
  102520. /**
  102521. * Creates an array of the own enumerable symbol properties of `object`.
  102522. *
  102523. * @private
  102524. * @param {Object} object The object to query.
  102525. * @returns {Array} Returns the array of symbols.
  102526. */
  102527. var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
  102528. /**
  102529. * Gets the `toStringTag` of `value`.
  102530. *
  102531. * @private
  102532. * @param {*} value The value to query.
  102533. * @returns {string} Returns the `toStringTag`.
  102534. */
  102535. var getTag = baseGetTag;
  102536. // Fallback for data views, maps, sets, and weak maps in IE 11,
  102537. // for data views in Edge < 14, and promises in Node.js.
  102538. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
  102539. (Map && getTag(new Map) != mapTag) ||
  102540. (Promise && getTag(Promise.resolve()) != promiseTag) ||
  102541. (Set && getTag(new Set) != setTag) ||
  102542. (WeakMap && getTag(new WeakMap) != weakMapTag)) {
  102543. getTag = function(value) {
  102544. var result = objectToString.call(value),
  102545. Ctor = result == objectTag ? value.constructor : undefined,
  102546. ctorString = Ctor ? toSource(Ctor) : undefined;
  102547. if (ctorString) {
  102548. switch (ctorString) {
  102549. case dataViewCtorString: return dataViewTag;
  102550. case mapCtorString: return mapTag;
  102551. case promiseCtorString: return promiseTag;
  102552. case setCtorString: return setTag;
  102553. case weakMapCtorString: return weakMapTag;
  102554. }
  102555. }
  102556. return result;
  102557. };
  102558. }
  102559. /**
  102560. * Initializes an array clone.
  102561. *
  102562. * @private
  102563. * @param {Array} array The array to clone.
  102564. * @returns {Array} Returns the initialized clone.
  102565. */
  102566. function initCloneArray(array) {
  102567. var length = array.length,
  102568. result = array.constructor(length);
  102569. // Add properties assigned by `RegExp#exec`.
  102570. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
  102571. result.index = array.index;
  102572. result.input = array.input;
  102573. }
  102574. return result;
  102575. }
  102576. /**
  102577. * Initializes an object clone.
  102578. *
  102579. * @private
  102580. * @param {Object} object The object to clone.
  102581. * @returns {Object} Returns the initialized clone.
  102582. */
  102583. function initCloneObject(object) {
  102584. return (typeof object.constructor == 'function' && !isPrototype(object))
  102585. ? baseCreate(getPrototype(object))
  102586. : {};
  102587. }
  102588. /**
  102589. * Initializes an object clone based on its `toStringTag`.
  102590. *
  102591. * **Note:** This function only supports cloning values with tags of
  102592. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  102593. *
  102594. * @private
  102595. * @param {Object} object The object to clone.
  102596. * @param {string} tag The `toStringTag` of the object to clone.
  102597. * @param {Function} cloneFunc The function to clone values.
  102598. * @param {boolean} [isDeep] Specify a deep clone.
  102599. * @returns {Object} Returns the initialized clone.
  102600. */
  102601. function initCloneByTag(object, tag, cloneFunc, isDeep) {
  102602. var Ctor = object.constructor;
  102603. switch (tag) {
  102604. case arrayBufferTag:
  102605. return cloneArrayBuffer(object);
  102606. case boolTag:
  102607. case dateTag:
  102608. return new Ctor(+object);
  102609. case dataViewTag:
  102610. return cloneDataView(object, isDeep);
  102611. case float32Tag: case float64Tag:
  102612. case int8Tag: case int16Tag: case int32Tag:
  102613. case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
  102614. return cloneTypedArray(object, isDeep);
  102615. case mapTag:
  102616. return cloneMap(object, isDeep, cloneFunc);
  102617. case numberTag:
  102618. case stringTag:
  102619. return new Ctor(object);
  102620. case regexpTag:
  102621. return cloneRegExp(object);
  102622. case setTag:
  102623. return cloneSet(object, isDeep, cloneFunc);
  102624. case symbolTag:
  102625. return cloneSymbol(object);
  102626. }
  102627. }
  102628. /**
  102629. * Checks if `value` is a valid array-like index.
  102630. *
  102631. * @private
  102632. * @param {*} value The value to check.
  102633. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  102634. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  102635. */
  102636. function isIndex(value, length) {
  102637. length = length == null ? MAX_SAFE_INTEGER : length;
  102638. return !!length &&
  102639. (typeof value == 'number' || reIsUint.test(value)) &&
  102640. (value > -1 && value % 1 == 0 && value < length);
  102641. }
  102642. /**
  102643. * Checks if the given arguments are from an iteratee call.
  102644. *
  102645. * @private
  102646. * @param {*} value The potential iteratee value argument.
  102647. * @param {*} index The potential iteratee index or key argument.
  102648. * @param {*} object The potential iteratee object argument.
  102649. * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
  102650. * else `false`.
  102651. */
  102652. function isIterateeCall(value, index, object) {
  102653. if (!isObject(object)) {
  102654. return false;
  102655. }
  102656. var type = typeof index;
  102657. if (type == 'number'
  102658. ? (isArrayLike(object) && isIndex(index, object.length))
  102659. : (type == 'string' && index in object)
  102660. ) {
  102661. return eq(object[index], value);
  102662. }
  102663. return false;
  102664. }
  102665. /**
  102666. * Checks if `value` is suitable for use as unique object key.
  102667. *
  102668. * @private
  102669. * @param {*} value The value to check.
  102670. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  102671. */
  102672. function isKeyable(value) {
  102673. var type = typeof value;
  102674. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  102675. ? (value !== '__proto__')
  102676. : (value === null);
  102677. }
  102678. /**
  102679. * Checks if `func` has its source masked.
  102680. *
  102681. * @private
  102682. * @param {Function} func The function to check.
  102683. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  102684. */
  102685. function isMasked(func) {
  102686. return !!maskSrcKey && (maskSrcKey in func);
  102687. }
  102688. /**
  102689. * Checks if `value` is likely a prototype object.
  102690. *
  102691. * @private
  102692. * @param {*} value The value to check.
  102693. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  102694. */
  102695. function isPrototype(value) {
  102696. var Ctor = value && value.constructor,
  102697. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
  102698. return value === proto;
  102699. }
  102700. /**
  102701. * This function is like
  102702. * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  102703. * except that it includes inherited enumerable properties.
  102704. *
  102705. * @private
  102706. * @param {Object} object The object to query.
  102707. * @returns {Array} Returns the array of property names.
  102708. */
  102709. function nativeKeysIn(object) {
  102710. var result = [];
  102711. if (object != null) {
  102712. for (var key in Object(object)) {
  102713. result.push(key);
  102714. }
  102715. }
  102716. return result;
  102717. }
  102718. /**
  102719. * Converts `func` to its source code.
  102720. *
  102721. * @private
  102722. * @param {Function} func The function to process.
  102723. * @returns {string} Returns the source code.
  102724. */
  102725. function toSource(func) {
  102726. if (func != null) {
  102727. try {
  102728. return funcToString.call(func);
  102729. } catch (e) {}
  102730. try {
  102731. return (func + '');
  102732. } catch (e) {}
  102733. }
  102734. return '';
  102735. }
  102736. /**
  102737. * Performs a
  102738. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  102739. * comparison between two values to determine if they are equivalent.
  102740. *
  102741. * @static
  102742. * @memberOf _
  102743. * @since 4.0.0
  102744. * @category Lang
  102745. * @param {*} value The value to compare.
  102746. * @param {*} other The other value to compare.
  102747. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  102748. * @example
  102749. *
  102750. * var object = { 'a': 1 };
  102751. * var other = { 'a': 1 };
  102752. *
  102753. * _.eq(object, object);
  102754. * // => true
  102755. *
  102756. * _.eq(object, other);
  102757. * // => false
  102758. *
  102759. * _.eq('a', 'a');
  102760. * // => true
  102761. *
  102762. * _.eq('a', Object('a'));
  102763. * // => false
  102764. *
  102765. * _.eq(NaN, NaN);
  102766. * // => true
  102767. */
  102768. function eq(value, other) {
  102769. return value === other || (value !== value && other !== other);
  102770. }
  102771. /**
  102772. * Checks if `value` is likely an `arguments` object.
  102773. *
  102774. * @static
  102775. * @memberOf _
  102776. * @since 0.1.0
  102777. * @category Lang
  102778. * @param {*} value The value to check.
  102779. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  102780. * else `false`.
  102781. * @example
  102782. *
  102783. * _.isArguments(function() { return arguments; }());
  102784. * // => true
  102785. *
  102786. * _.isArguments([1, 2, 3]);
  102787. * // => false
  102788. */
  102789. function isArguments(value) {
  102790. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  102791. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
  102792. (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
  102793. }
  102794. /**
  102795. * Checks if `value` is classified as an `Array` object.
  102796. *
  102797. * @static
  102798. * @memberOf _
  102799. * @since 0.1.0
  102800. * @category Lang
  102801. * @param {*} value The value to check.
  102802. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  102803. * @example
  102804. *
  102805. * _.isArray([1, 2, 3]);
  102806. * // => true
  102807. *
  102808. * _.isArray(document.body.children);
  102809. * // => false
  102810. *
  102811. * _.isArray('abc');
  102812. * // => false
  102813. *
  102814. * _.isArray(_.noop);
  102815. * // => false
  102816. */
  102817. var isArray = Array.isArray;
  102818. /**
  102819. * Checks if `value` is array-like. A value is considered array-like if it's
  102820. * not a function and has a `value.length` that's an integer greater than or
  102821. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  102822. *
  102823. * @static
  102824. * @memberOf _
  102825. * @since 4.0.0
  102826. * @category Lang
  102827. * @param {*} value The value to check.
  102828. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  102829. * @example
  102830. *
  102831. * _.isArrayLike([1, 2, 3]);
  102832. * // => true
  102833. *
  102834. * _.isArrayLike(document.body.children);
  102835. * // => true
  102836. *
  102837. * _.isArrayLike('abc');
  102838. * // => true
  102839. *
  102840. * _.isArrayLike(_.noop);
  102841. * // => false
  102842. */
  102843. function isArrayLike(value) {
  102844. return value != null && isLength(value.length) && !isFunction(value);
  102845. }
  102846. /**
  102847. * This method is like `_.isArrayLike` except that it also checks if `value`
  102848. * is an object.
  102849. *
  102850. * @static
  102851. * @memberOf _
  102852. * @since 4.0.0
  102853. * @category Lang
  102854. * @param {*} value The value to check.
  102855. * @returns {boolean} Returns `true` if `value` is an array-like object,
  102856. * else `false`.
  102857. * @example
  102858. *
  102859. * _.isArrayLikeObject([1, 2, 3]);
  102860. * // => true
  102861. *
  102862. * _.isArrayLikeObject(document.body.children);
  102863. * // => true
  102864. *
  102865. * _.isArrayLikeObject('abc');
  102866. * // => false
  102867. *
  102868. * _.isArrayLikeObject(_.noop);
  102869. * // => false
  102870. */
  102871. function isArrayLikeObject(value) {
  102872. return isObjectLike(value) && isArrayLike(value);
  102873. }
  102874. /**
  102875. * Checks if `value` is a buffer.
  102876. *
  102877. * @static
  102878. * @memberOf _
  102879. * @since 4.3.0
  102880. * @category Lang
  102881. * @param {*} value The value to check.
  102882. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  102883. * @example
  102884. *
  102885. * _.isBuffer(new Buffer(2));
  102886. * // => true
  102887. *
  102888. * _.isBuffer(new Uint8Array(2));
  102889. * // => false
  102890. */
  102891. var isBuffer = nativeIsBuffer || stubFalse;
  102892. /**
  102893. * Checks if `value` is classified as a `Function` object.
  102894. *
  102895. * @static
  102896. * @memberOf _
  102897. * @since 0.1.0
  102898. * @category Lang
  102899. * @param {*} value The value to check.
  102900. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  102901. * @example
  102902. *
  102903. * _.isFunction(_);
  102904. * // => true
  102905. *
  102906. * _.isFunction(/abc/);
  102907. * // => false
  102908. */
  102909. function isFunction(value) {
  102910. // The use of `Object#toString` avoids issues with the `typeof` operator
  102911. // in Safari 8-9 which returns 'object' for typed array and other constructors.
  102912. var tag = isObject(value) ? objectToString.call(value) : '';
  102913. return tag == funcTag || tag == genTag;
  102914. }
  102915. /**
  102916. * Checks if `value` is a valid array-like length.
  102917. *
  102918. * **Note:** This method is loosely based on
  102919. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  102920. *
  102921. * @static
  102922. * @memberOf _
  102923. * @since 4.0.0
  102924. * @category Lang
  102925. * @param {*} value The value to check.
  102926. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  102927. * @example
  102928. *
  102929. * _.isLength(3);
  102930. * // => true
  102931. *
  102932. * _.isLength(Number.MIN_VALUE);
  102933. * // => false
  102934. *
  102935. * _.isLength(Infinity);
  102936. * // => false
  102937. *
  102938. * _.isLength('3');
  102939. * // => false
  102940. */
  102941. function isLength(value) {
  102942. return typeof value == 'number' &&
  102943. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  102944. }
  102945. /**
  102946. * Checks if `value` is the
  102947. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  102948. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  102949. *
  102950. * @static
  102951. * @memberOf _
  102952. * @since 0.1.0
  102953. * @category Lang
  102954. * @param {*} value The value to check.
  102955. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  102956. * @example
  102957. *
  102958. * _.isObject({});
  102959. * // => true
  102960. *
  102961. * _.isObject([1, 2, 3]);
  102962. * // => true
  102963. *
  102964. * _.isObject(_.noop);
  102965. * // => true
  102966. *
  102967. * _.isObject(null);
  102968. * // => false
  102969. */
  102970. function isObject(value) {
  102971. var type = typeof value;
  102972. return !!value && (type == 'object' || type == 'function');
  102973. }
  102974. /**
  102975. * Checks if `value` is object-like. A value is object-like if it's not `null`
  102976. * and has a `typeof` result of "object".
  102977. *
  102978. * @static
  102979. * @memberOf _
  102980. * @since 4.0.0
  102981. * @category Lang
  102982. * @param {*} value The value to check.
  102983. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  102984. * @example
  102985. *
  102986. * _.isObjectLike({});
  102987. * // => true
  102988. *
  102989. * _.isObjectLike([1, 2, 3]);
  102990. * // => true
  102991. *
  102992. * _.isObjectLike(_.noop);
  102993. * // => false
  102994. *
  102995. * _.isObjectLike(null);
  102996. * // => false
  102997. */
  102998. function isObjectLike(value) {
  102999. return !!value && typeof value == 'object';
  103000. }
  103001. /**
  103002. * Checks if `value` is a plain object, that is, an object created by the
  103003. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  103004. *
  103005. * @static
  103006. * @memberOf _
  103007. * @since 0.8.0
  103008. * @category Lang
  103009. * @param {*} value The value to check.
  103010. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  103011. * @example
  103012. *
  103013. * function Foo() {
  103014. * this.a = 1;
  103015. * }
  103016. *
  103017. * _.isPlainObject(new Foo);
  103018. * // => false
  103019. *
  103020. * _.isPlainObject([1, 2, 3]);
  103021. * // => false
  103022. *
  103023. * _.isPlainObject({ 'x': 0, 'y': 0 });
  103024. * // => true
  103025. *
  103026. * _.isPlainObject(Object.create(null));
  103027. * // => true
  103028. */
  103029. function isPlainObject(value) {
  103030. if (!isObjectLike(value) ||
  103031. objectToString.call(value) != objectTag || isHostObject(value)) {
  103032. return false;
  103033. }
  103034. var proto = getPrototype(value);
  103035. if (proto === null) {
  103036. return true;
  103037. }
  103038. var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
  103039. return (typeof Ctor == 'function' &&
  103040. Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
  103041. }
  103042. /**
  103043. * Checks if `value` is classified as a typed array.
  103044. *
  103045. * @static
  103046. * @memberOf _
  103047. * @since 3.0.0
  103048. * @category Lang
  103049. * @param {*} value The value to check.
  103050. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  103051. * @example
  103052. *
  103053. * _.isTypedArray(new Uint8Array);
  103054. * // => true
  103055. *
  103056. * _.isTypedArray([]);
  103057. * // => false
  103058. */
  103059. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  103060. /**
  103061. * Converts `value` to a plain object flattening inherited enumerable string
  103062. * keyed properties of `value` to own properties of the plain object.
  103063. *
  103064. * @static
  103065. * @memberOf _
  103066. * @since 3.0.0
  103067. * @category Lang
  103068. * @param {*} value The value to convert.
  103069. * @returns {Object} Returns the converted plain object.
  103070. * @example
  103071. *
  103072. * function Foo() {
  103073. * this.b = 2;
  103074. * }
  103075. *
  103076. * Foo.prototype.c = 3;
  103077. *
  103078. * _.assign({ 'a': 1 }, new Foo);
  103079. * // => { 'a': 1, 'b': 2 }
  103080. *
  103081. * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
  103082. * // => { 'a': 1, 'b': 2, 'c': 3 }
  103083. */
  103084. function toPlainObject(value) {
  103085. return copyObject(value, keysIn(value));
  103086. }
  103087. /**
  103088. * Creates an array of the own enumerable property names of `object`.
  103089. *
  103090. * **Note:** Non-object values are coerced to objects. See the
  103091. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  103092. * for more details.
  103093. *
  103094. * @static
  103095. * @since 0.1.0
  103096. * @memberOf _
  103097. * @category Object
  103098. * @param {Object} object The object to query.
  103099. * @returns {Array} Returns the array of property names.
  103100. * @example
  103101. *
  103102. * function Foo() {
  103103. * this.a = 1;
  103104. * this.b = 2;
  103105. * }
  103106. *
  103107. * Foo.prototype.c = 3;
  103108. *
  103109. * _.keys(new Foo);
  103110. * // => ['a', 'b'] (iteration order is not guaranteed)
  103111. *
  103112. * _.keys('hi');
  103113. * // => ['0', '1']
  103114. */
  103115. function keys(object) {
  103116. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  103117. }
  103118. /**
  103119. * Creates an array of the own and inherited enumerable property names of `object`.
  103120. *
  103121. * **Note:** Non-object values are coerced to objects.
  103122. *
  103123. * @static
  103124. * @memberOf _
  103125. * @since 3.0.0
  103126. * @category Object
  103127. * @param {Object} object The object to query.
  103128. * @returns {Array} Returns the array of property names.
  103129. * @example
  103130. *
  103131. * function Foo() {
  103132. * this.a = 1;
  103133. * this.b = 2;
  103134. * }
  103135. *
  103136. * Foo.prototype.c = 3;
  103137. *
  103138. * _.keysIn(new Foo);
  103139. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  103140. */
  103141. function keysIn(object) {
  103142. return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
  103143. }
  103144. /**
  103145. * This method is like `_.assign` except that it recursively merges own and
  103146. * inherited enumerable string keyed properties of source objects into the
  103147. * destination object. Source properties that resolve to `undefined` are
  103148. * skipped if a destination value exists. Array and plain object properties
  103149. * are merged recursively. Other objects and value types are overridden by
  103150. * assignment. Source objects are applied from left to right. Subsequent
  103151. * sources overwrite property assignments of previous sources.
  103152. *
  103153. * **Note:** This method mutates `object`.
  103154. *
  103155. * @static
  103156. * @memberOf _
  103157. * @since 0.5.0
  103158. * @category Object
  103159. * @param {Object} object The destination object.
  103160. * @param {...Object} [sources] The source objects.
  103161. * @returns {Object} Returns `object`.
  103162. * @example
  103163. *
  103164. * var object = {
  103165. * 'a': [{ 'b': 2 }, { 'd': 4 }]
  103166. * };
  103167. *
  103168. * var other = {
  103169. * 'a': [{ 'c': 3 }, { 'e': 5 }]
  103170. * };
  103171. *
  103172. * _.merge(object, other);
  103173. * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
  103174. */
  103175. var merge = createAssigner(function(object, source, srcIndex) {
  103176. baseMerge(object, source, srcIndex);
  103177. });
  103178. /**
  103179. * This method returns a new empty array.
  103180. *
  103181. * @static
  103182. * @memberOf _
  103183. * @since 4.13.0
  103184. * @category Util
  103185. * @returns {Array} Returns the new empty array.
  103186. * @example
  103187. *
  103188. * var arrays = _.times(2, _.stubArray);
  103189. *
  103190. * console.log(arrays);
  103191. * // => [[], []]
  103192. *
  103193. * console.log(arrays[0] === arrays[1]);
  103194. * // => false
  103195. */
  103196. function stubArray() {
  103197. return [];
  103198. }
  103199. /**
  103200. * This method returns `false`.
  103201. *
  103202. * @static
  103203. * @memberOf _
  103204. * @since 4.13.0
  103205. * @category Util
  103206. * @returns {boolean} Returns `false`.
  103207. * @example
  103208. *
  103209. * _.times(2, _.stubFalse);
  103210. * // => [false, false]
  103211. */
  103212. function stubFalse() {
  103213. return false;
  103214. }
  103215. module.exports = merge;
  103216. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(28)(module)))
  103217. /***/ }),
  103218. /* 28 */
  103219. /***/ (function(module, exports) {
  103220. module.exports = function(module) {
  103221. if(!module.webpackPolyfill) {
  103222. module.deprecate = function() {};
  103223. module.paths = [];
  103224. // module.parent = undefined by default
  103225. if(!module.children) module.children = [];
  103226. Object.defineProperty(module, "loaded", {
  103227. enumerable: true,
  103228. get: function() {
  103229. return module.l;
  103230. }
  103231. });
  103232. Object.defineProperty(module, "id", {
  103233. enumerable: true,
  103234. get: function() {
  103235. return module.i;
  103236. }
  103237. });
  103238. module.webpackPolyfill = 1;
  103239. }
  103240. return module;
  103241. };
  103242. /***/ }),
  103243. /* 29 */
  103244. /***/ (function(module, exports, __webpack_require__) {
  103245. "use strict";
  103246. var __extends = (this && this.__extends) || (function () {
  103247. var extendStatics = Object.setPrototypeOf ||
  103248. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  103249. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  103250. return function (d, b) {
  103251. extendStatics(d, b);
  103252. function __() { this.constructor = d; }
  103253. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  103254. };
  103255. })();
  103256. Object.defineProperty(exports, "__esModule", { value: true });
  103257. var babylonjs_1 = __webpack_require__(0);
  103258. var PromiseObservable = (function (_super) {
  103259. __extends(PromiseObservable, _super);
  103260. function PromiseObservable() {
  103261. return _super !== null && _super.apply(this, arguments) || this;
  103262. }
  103263. PromiseObservable.prototype.notifyWithPromise = function (eventData, mask, target, currentTarget) {
  103264. if (mask === void 0) { mask = -1; }
  103265. var p = Promise.resolve();
  103266. if (!this._observers.length) {
  103267. return p;
  103268. }
  103269. var state = this['_eventState'];
  103270. state.mask = mask;
  103271. state.target = target;
  103272. state.currentTarget = currentTarget;
  103273. state.skipNextObservers = false;
  103274. this._observers.forEach(function (obs) {
  103275. if (state.skipNextObservers) {
  103276. return;
  103277. }
  103278. if (obs.mask & mask) {
  103279. if (obs.scope) {
  103280. p = p.then(function () {
  103281. return obs.callback.apply(obs.scope, [eventData, state]);
  103282. });
  103283. }
  103284. else {
  103285. p = p.then(function () {
  103286. return obs.callback(eventData, state);
  103287. });
  103288. }
  103289. }
  103290. });
  103291. return p;
  103292. };
  103293. return PromiseObservable;
  103294. }(babylonjs_1.Observable));
  103295. exports.PromiseObservable = PromiseObservable;
  103296. /***/ }),
  103297. /* 30 */
  103298. /***/ (function(module, exports, __webpack_require__) {
  103299. /* WEBPACK VAR INJECTION */(function(global) {var globalObject="undefined"!=typeof global?global:"undefined"!=typeof window?window:this,babylonDependency=globalObject&&globalObject.BABYLON||BABYLON||"undefined"!="function"&&__webpack_require__(0),BABYLON=babylonDependency,__decorate=this&&this.__decorate||function(e,t,r,n){var o,a=arguments.length,i=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,r,n);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(i=(a<3?o(i):a>3?o(t,r,i):o(t,r))||i);return a>3&&i&&Object.defineProperty(t,r,i),i},__extends=this&&this.__extends||(function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};return function(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}})(),BABYLON;!(function(e){var t=(function(){function t(){this.solidPattern=/solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,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,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,this.name="stl",this.extensions={".stl":{isBinary:!0}}}return t.prototype.importMesh=function(t,r,n,o,a,i,s){var l;if(this.isBinary(n)){var u=new e.Mesh("stlmesh",r);return this.parseBinary(u,n),a&&a.push(u),!0}for(var c=new Uint8Array(n),f="",d=0;d<n.byteLength;d++)f+=String.fromCharCode(c[d]);for(n=f;l=this.solidPattern.exec(n);){var h=l[1];if(h!=l[3])return e.Tools.Error("Error in STL, solid name != endsolid name"),!1;if(t&&h)if(t instanceof Array){if(!t.indexOf(h))continue}else if(h!==t)continue;h=h||"stlmesh";var u=new e.Mesh(h,r);this.parseASCII(u,l[2]),a&&a.push(u)}return!0},t.prototype.load=function(e,t,r){var n=this.importMesh(null,e,t,r,null,null,null);return n&&e.createDefaultCameraOrLight(),n},t.prototype.isBinary=function(e){var t,r;if(r=new DataView(e),t=50,84+r.getUint32(80,!0)*t===r.byteLength)return!0;for(var n=r.byteLength,o=0;o<n;o++)if(r.getUint8(o)>127)return!0;return!1},t.prototype.parseBinary=function(t,r){for(var n=new DataView(r),o=n.getUint32(80,!0),a=0,i=new Float32Array(3*o*3),s=new Float32Array(3*o*3),l=new Uint32Array(3*o),u=0,c=0;c<o;c++){for(var f=84+50*c,d=n.getFloat32(f,!0),h=n.getFloat32(f+4,!0),p=n.getFloat32(f+8,!0),m=1;m<=3;m++){var E=f+12*m;i[a]=n.getFloat32(E,!0),i[a+2]=n.getFloat32(E+4,!0),i[a+1]=n.getFloat32(E+8,!0),s[a]=d,s[a+2]=h,s[a+1]=p,a+=3}l[u]=u++,l[u]=u++,l[u]=u++}t.setVerticesData(e.VertexBuffer.PositionKind,i),t.setVerticesData(e.VertexBuffer.NormalKind,s),t.setIndices(l),t.computeWorldMatrix(!0)},t.prototype.parseASCII=function(t,r){for(var n,o=[],a=[],i=[],s=0;n=this.facetsPattern.exec(r);){var l=n[1],u=this.normalPattern.exec(l);if(this.normalPattern.lastIndex=0,u){for(var c,f=[Number(u[1]),Number(u[5]),Number(u[3])];c=this.vertexPattern.exec(l);)o.push(Number(c[1]),Number(c[5]),Number(c[3])),a.push(f[0],f[1],f[2]);i.push(s++,s++,s++),this.vertexPattern.lastIndex=0}}this.facetsPattern.lastIndex=0,t.setVerticesData(e.VertexBuffer.PositionKind,o),t.setVerticesData(e.VertexBuffer.NormalKind,a),t.setIndices(i),t.computeWorldMatrix(!0)},t})();e.STLFileLoader=t,e.SceneLoader&&e.SceneLoader.RegisterPlugin(new t)})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.materials=[]}return t.prototype.parseMTL=function(r,n,o){for(var a,i=n.split("\n"),s=/\s+/,l=null,u=0;u<i.length;u++){var c=i[u].trim();if(0!==c.length&&"#"!==c.charAt(0)){var f=c.indexOf(" "),d=f>=0?c.substring(0,f):c;d=d.toLowerCase();var h=f>=0?c.substring(f+1).trim():"";"newmtl"===d?(l&&this.materials.push(l),l=new e.StandardMaterial(h,r)):"kd"===d&&l?(a=h.split(s,3).map(parseFloat),l.diffuseColor=e.Color3.FromArray(a)):"ka"===d&&l?(a=h.split(s,3).map(parseFloat),l.ambientColor=e.Color3.FromArray(a)):"ks"===d&&l?(a=h.split(s,3).map(parseFloat),l.specularColor=e.Color3.FromArray(a)):"ke"===d&&l?(a=h.split(s,3).map(parseFloat),l.emissiveColor=e.Color3.FromArray(a)):"ns"===d&&l?l.specularPower=parseFloat(h):"d"===d&&l?l.alpha=parseFloat(h):"map_ka"===d&&l?l.ambientTexture=t._getTexture(o,h,r):"map_kd"===d&&l?l.diffuseTexture=t._getTexture(o,h,r):"map_ks"===d&&l?l.specularTexture=t._getTexture(o,h,r):"map_ns"===d||("map_bump"===d&&l?l.bumpTexture=t._getTexture(o,h,r):"map_d"===d&&l&&(l.opacityTexture=t._getTexture(o,h,r)))}}l&&this.materials.push(l)},t._getTexture=function(t,r,n){if(!r)return null;var o=t;if("file:"===t){var a=r.lastIndexOf("\\");-1===a&&(a=r.lastIndexOf("/")),o+=a>-1?r.substr(a+1):r}else o+=r;return new e.Texture(o,n)},t})();e.MTLFileLoader=t;var r=(function(){function r(){this.name="obj",this.extensions=".obj",this.obj=/^o/,this.group=/^g/,this.mtllib=/^mtllib /,this.usemtl=/^usemtl /,this.smooth=/^s /,this.vertexPattern=/v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,this.normalPattern=/vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,this.uvPattern=/vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,this.facePattern1=/f\s+(([\d]{1,}[\s]?){3,})+/,this.facePattern2=/f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,this.facePattern3=/f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,this.facePattern4=/f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/}return r.prototype._loadMTL=function(t,r,n){var o=e.Tools.BaseUrl+r+t;e.Tools.LoadFile(o,n,void 0,void 0,!1,(function(){console.warn("Error - Unable to load "+o)}))},r.prototype.importMesh=function(e,t,r,n,o,a,i){var s=this._parseSolid(e,t,r,n);return o&&s.forEach((function(e){o.push(e)})),!0},r.prototype.load=function(e,t,r){return this.importMesh(null,e,t,r,null,null,null)},r.prototype._parseSolid=function(n,o,a,i){for(var s,l=[],u=[],c=[],f=[],d=[],h=[],p=[],m=[],E=[],T=0,_=!1,A=[],y=[],g=[],v=[],L="",x="",N=new t,b=1,M=!0,O=function(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});var r=e[t[0]].normals.indexOf(t[1]);return-1===r?-1:e[t[0]].idx[r]},F=function(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});var r=e[t[0]].normals.indexOf(t[1]);return 1!=r&&t[2]==e[t[0]].uv[r]?e[t[0]].idx[r]:-1},R=function(e,t,n,o,a,i){var s;s=r.OPTIMIZE_WITH_UV?F(E,[e,n,t]):O(E,[e,n]),-1==s?(d.push(h.length),h.push(o),p.push(a),m.push(i),E[e].normals.push(n),E[e].idx.push(T++),r.OPTIMIZE_WITH_UV&&E[e].uv.push(t)):d.push(s)},S=function(){for(var e=0;e<h.length;e++)A.push(h[e].x,h[e].y,h[e].z),y.push(m[e].x,m[e].y,m[e].z),g.push(p[e].x,p[e].y);h=[],m=[],p=[],E=[],T=0},I=function(e,t){t+1<e.length&&(v.push(e[0],e[t],e[t+1]),t+=1,I(e,t))},w=function(){f.length>0&&(s=f[f.length-1],S(),d.reverse(),s.indices=d.slice(),s.positions=A.slice(),s.normals=y.slice(),s.uvs=g.slice(),d=[],A=[],y=[],g=[])},P=a.split("\n"),B=0;B<P.length;B++){var C,G=P[B].trim();if(0!==G.length&&"#"!==G.charAt(0))if(null!==(C=this.vertexPattern.exec(G)))l.push(new e.Vector3(parseFloat(C[1]),parseFloat(C[2]),parseFloat(C[3])));else if(null!==(C=this.normalPattern.exec(G)))u.push(new e.Vector3(parseFloat(C[1]),parseFloat(C[2]),parseFloat(C[3])));else if(null!==(C=this.uvPattern.exec(G)))c.push(new e.Vector2(parseFloat(C[1]),parseFloat(C[2])));else if(null!==(C=this.facePattern3.exec(G)))!(function(e,t){I(e,t);for(var r=0;r<v.length;r++){var n=v[r].split("/"),o=parseInt(n[0])-1,a=parseInt(n[1])-1,i=parseInt(n[2])-1;R(o,a,i,l[o],c[a],u[i])}v=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern4.exec(G)))!(function(t,r){I(t,r);for(var n=0;n<v.length;n++){var o=v[n].split("//"),a=parseInt(o[0])-1,i=parseInt(o[1])-1;R(a,1,i,l[a],e.Vector2.Zero(),u[i])}v=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern2.exec(G)))!(function(t,r){I(t,r);for(var n=0;n<v.length;n++){var o=v[n].split("/"),a=parseInt(o[0])-1,i=parseInt(o[1])-1;R(a,i,0,l[a],c[i],e.Vector3.Up())}v=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern1.exec(G)))!(function(t,r){I(t,r);for(var n=0;n<v.length;n++){var o=parseInt(v[n])-1;R(o,0,0,l[o],e.Vector2.Zero(),e.Vector3.Up())}v=[]})(C[1].trim().split(" "),1);else if(this.group.test(G)||this.obj.test(G)){var D={name:G.substring(2).trim(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,materialName:""};w(),f.push(D),_=!0,M=!0,b=1}else if(this.usemtl.test(G)){if(L=G.substring(7).trim(),!M){w();var D={name:"_mm"+b.toString(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,materialName:L};b++,f.push(D)}_&&M&&(f[f.length-1].materialName=L,M=!1)}else this.mtllib.test(G)?x=G.substring(7).trim():this.smooth.test(G)||console.log("Unhandled expression at line : "+G)}_&&(s=f[f.length-1],d.reverse(),S(),s.indices=d,s.positions=A,s.normals=y,s.uvs=g),_||(d.reverse(),S(),f.push({name:e.Geometry.RandomId(),indices:d,positions:A,normals:y,uvs:g,materialName:L}));for(var V=[],U=new Array,k=0;k<f.length;k++){if(n&&f[k].name)if(n instanceof Array){if(-1==n.indexOf(f[k].name))continue}else if(f[k].name!==n)continue;s=f[k];var H=new e.Mesh(f[k].name,o);U.push(f[k].materialName);var Y=new e.VertexData;Y.positions=s.positions,Y.normals=s.normals,Y.uvs=s.uvs,Y.indices=s.indices,Y.applyToMesh(H),V.push(H)}return""!==x&&this._loadMTL(x,i,(function(e){N.parseMTL(o,e,i);for(var t=0;t<N.materials.length;t++){for(var r,n=0,a=[];(r=U.indexOf(N.materials[t].name,n))>-1;)a.push(r),n=r+1;if(-1==r&&0==a.length)N.materials[t].dispose();else for(var s=0;s<a.length;s++)V[a[s]].material=N.materials[t]}})),V},r.OPTIMIZE_WITH_UV=!1,r})();e.OBJFileLoader=r,e.SceneLoader&&e.SceneLoader.RegisterPlugin(new r)})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){e[e.AUTO=0]="AUTO",e[e.PASS_THROUGH=1]="PASS_THROUGH",e[e.FORCE_RIGHT_HANDED=2]="FORCE_RIGHT_HANDED"})(t=e.GLTFLoaderCoordinateSystemMode||(e.GLTFLoaderCoordinateSystemMode={}));var r=(function(){function e(){this.coordinateSystemMode=t.AUTO,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}}}return e.prototype.dispose=function(){this._loader&&this._loader.dispose()},e.prototype.importMeshAsync=function(t,r,n,o,a,i,s){try{var l=e._parse(n);this.onParsed&&this.onParsed(l),this._loader=this._getLoader(l),this._loader.importMeshAsync(t,r,l,o,a,i,s)}catch(e){s(e.message)}},e.prototype.loadAsync=function(t,r,n,o,a,i){try{var s=e._parse(r);this.onParsed&&this.onParsed(s),this._loader=this._getLoader(s),this._loader.loadAsync(t,s,n,o,a,i)}catch(e){i(e.message)}},e.prototype.canDirectLoad=function(e){return-1!==e.indexOf("scene")&&-1!==e.indexOf("node")},e._parse=function(t){return t instanceof ArrayBuffer?e._parseBinary(t):{json:JSON.parse(t),bin:null}},e.prototype._getLoader=function(t){var r={major:2,minor:0},n=t.json.asset||{},o=e._parseVersion(n.version);if(!o)throw new Error("Invalid version: "+n.version);if(void 0!==n.minVersion){var a=e._parseVersion(n.minVersion);if(!a)throw new Error("Invalid minimum version: "+n.minVersion);if(e._compareVersion(a,r)>0)throw new Error("Incompatible minimum version: "+n.minVersion)}var i={1:e.CreateGLTFLoaderV1,2:e.CreateGLTFLoaderV2},s=i[o.major];if(!s)throw new Error("Unsupported version: "+n.version);return s(this)},e._parseBinary=function(t){var r={Magic:1179937895},o=new n(t),a=o.readUint32();if(a!==r.Magic)throw new Error("Unexpected magic: "+a);var i=o.readUint32();switch(i){case 1:return e._parseV1(o);case 2:return e._parseV2(o)}throw new Error("Unsupported version: "+i)},e._parseV1=function(t){var r={JSON:0},n=t.readUint32();if(n!=t.getLength())throw new Error("Length in header does not match actual data length: "+n+" != "+t.getLength());var o,a=t.readUint32(),i=t.readUint32();switch(i){case r.JSON:o=JSON.parse(e._decodeBufferToText(t.readUint8Array(a)));break;default:throw new Error("Unexpected content format: "+i)}var s=t.getLength()-t.getPosition();return{json:o,bin:t.readUint8Array(s)}},e._parseV2=function(t){var r={JSON:1313821514,BIN:5130562},n=t.readUint32();if(n!==t.getLength())throw new Error("Length in header does not match actual data length: "+n+" != "+t.getLength());var o=t.readUint32();if(t.readUint32()!==r.JSON)throw new Error("First chunk format is not JSON");for(var a=JSON.parse(e._decodeBufferToText(t.readUint8Array(o))),i=null;t.getPosition()<t.getLength();){var s=t.readUint32();switch(t.readUint32()){case r.JSON:throw new Error("Unexpected JSON chunk");case r.BIN:i=t.readUint8Array(s);break;default:t.skipBytes(s)}}return{json:a,bin:i}},e._parseVersion=function(e){var t=(e+"").match(/^(\d+)\.(\d+)$/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null},e._compareVersion=function(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0},e._decodeBufferToText=function(e){for(var t="",r=e.byteLength,n=0;n<r;n++)t+=String.fromCharCode(e[n]);return t},e.HomogeneousCoordinates=!1,e.IncrementalLoading=!0,e})();e.GLTFFileLoader=r;var n=(function(){function e(e){this._arrayBuffer=e,this._dataView=new DataView(e),this._byteOffset=0}return e.prototype.getPosition=function(){return this._byteOffset},e.prototype.getLength=function(){return this._arrayBuffer.byteLength},e.prototype.readUint32=function(){var e=this._dataView.getUint32(this._byteOffset,!0);return this._byteOffset+=4,e},e.prototype.readUint8Array=function(e){var t=new Uint8Array(this._arrayBuffer,this._byteOffset,e);return this._byteOffset+=e,t},e.prototype.skipBytes=function(e){this._byteOffset+=e},e})();e.SceneLoader&&e.SceneLoader.RegisterPlugin(new r)})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){!(function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.FLOAT=5126]="FLOAT"})(e.EComponentType||(e.EComponentType={}));!(function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"})(e.EShaderType||(e.EShaderType={}));!(function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.INT=5124]="INT",e[e.UNSIGNED_INT=5125]="UNSIGNED_INT",e[e.FLOAT=5126]="FLOAT",e[e.FLOAT_VEC2=35664]="FLOAT_VEC2",e[e.FLOAT_VEC3=35665]="FLOAT_VEC3",e[e.FLOAT_VEC4=35666]="FLOAT_VEC4",e[e.INT_VEC2=35667]="INT_VEC2",e[e.INT_VEC3=35668]="INT_VEC3",e[e.INT_VEC4=35669]="INT_VEC4",e[e.BOOL=35670]="BOOL",e[e.BOOL_VEC2=35671]="BOOL_VEC2",e[e.BOOL_VEC3=35672]="BOOL_VEC3",e[e.BOOL_VEC4=35673]="BOOL_VEC4",e[e.FLOAT_MAT2=35674]="FLOAT_MAT2",e[e.FLOAT_MAT3=35675]="FLOAT_MAT3",e[e.FLOAT_MAT4=35676]="FLOAT_MAT4",e[e.SAMPLER_2D=35678]="SAMPLER_2D"})(e.EParameterType||(e.EParameterType={}));!(function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"})(e.ETextureWrapMode||(e.ETextureWrapMode={}));!(function(e){e[e.NEAREST=9728]="NEAREST",e[e.LINEAR=9728]="LINEAR",e[e.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",e[e.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",e[e.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",e[e.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"})(e.ETextureFilterType||(e.ETextureFilterType={}));!(function(e){e[e.ALPHA=6406]="ALPHA",e[e.RGB=6407]="RGB",e[e.RGBA=6408]="RGBA",e[e.LUMINANCE=6409]="LUMINANCE",e[e.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA"})(e.ETextureFormat||(e.ETextureFormat={}));!(function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"})(e.ECullingType||(e.ECullingType={}));!(function(e){e[e.ZERO=0]="ZERO",e[e.ONE=1]="ONE",e[e.SRC_COLOR=768]="SRC_COLOR",e[e.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",e[e.DST_COLOR=774]="DST_COLOR",e[e.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",e[e.SRC_ALPHA=770]="SRC_ALPHA",e[e.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",e[e.DST_ALPHA=772]="DST_ALPHA",e[e.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",e[e.CONSTANT_COLOR=32769]="CONSTANT_COLOR",e[e.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",e[e.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",e[e.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",e[e.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE"})(e.EBlendingFunction||(e.EBlendingFunction={}))})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r;!(function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"})(r||(r={}));var n=(function(){function e(e){this._pos=0,this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}return e.prototype.getNextToken=function(){if(this.isEnd())return r.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=r.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=r.IDENTIFIER,this.currentIdentifier=this.currentString;!this.isEnd()&&(this.isLetterOrDigitPattern.test(this.currentString=this.peek())||"_"===this.currentString);)this.currentIdentifier+=this.currentString,this.forward();return this.currentToken},e.prototype.peek=function(){return this._toParse[this._pos]},e.prototype.read=function(){return this._toParse[this._pos++]},e.prototype.forward=function(){this._pos++},e.prototype.isEnd=function(){return this._pos>=this._maxPos},e})(),o=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],a=["world","view","projection","worldView","worldViewProjection","mBones"],i=["translation","rotation","scale"],s=["position","rotationQuaternion","scaling"],l=function(e,t){for(var r in e){var n=e[r];t.buffers[r]=n,t.buffersCount++}},u=function(e,t){for(var r in e){var n=e[r];t.shaders[r]=n,t.shaderscount++}},c=function(e,t,r){for(var n in e){var o=e[n];r[t][n]=o}},f=function(e){if(e)for(var t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},d=function(e){if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){var t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},h=function(r){for(var n in r.animations){var o=r.animations[n];if(o.channels&&o.samplers)for(var a=null,l=0;l<o.channels.length;l++){var u=o.channels[l],c=o.samplers[u.sampler];if(c){var f=null,d=null;o.parameters?(f=o.parameters[c.input],d=o.parameters[c.output]):(f=c.input,d=c.output);var h=t.GLTFUtils.GetBufferFromAccessor(r,r.accessors[f]),p=t.GLTFUtils.GetBufferFromAccessor(r,r.accessors[d]),m=u.target.id,E=r.scene.getNodeByID(m);if(null===E&&(E=r.scene.getNodeByName(m)),null!==E){var T=E instanceof e.Bone,_=u.target.path,A=i.indexOf(_);-1!==A&&(_=s[A]);var y=e.Animation.ANIMATIONTYPE_MATRIX;T||("rotationQuaternion"===_?(y=e.Animation.ANIMATIONTYPE_QUATERNION,E.rotationQuaternion=new e.Quaternion):y=e.Animation.ANIMATIONTYPE_VECTOR3);var g=null,v=[],L=0,x=!1;T&&a&&a.getKeys().length===h.length&&(g=a,x=!0),x||(g=new e.Animation(n,T?"_matrix":_,1,y,e.Animation.ANIMATIONLOOPMODE_CYCLE));for(var N=0;N<h.length;N++){var b=null;if("rotationQuaternion"===_?(b=e.Quaternion.FromArray([p[L],p[L+1],p[L+2],p[L+3]]),L+=4):(b=e.Vector3.FromArray([p[L],p[L+1],p[L+2]]),L+=3),T){var M=E,O=e.Vector3.Zero(),F=new e.Quaternion,R=e.Vector3.Zero(),S=M.getBaseMatrix();x&&a&&(S=a.getKeys()[N].value),S.decompose(R,F,O),"position"===_?O=b:"rotationQuaternion"===_?F=b:R=b,b=e.Matrix.Compose(R,F,O)}x?a&&(a.getKeys()[N].value=b):v.push({frame:h[N],value:b})}!x&&g&&(g.setKeys(v),E.animations.push(g)),a=g,r.scene.stopAnimation(E),r.scene.beginAnimation(E,0,h[h.length-1],!0,1)}else e.Tools.Warn("Creating animation named "+n+". But cannot find node named "+m+" to attach to")}}}},p=function(t){var r=null;if(t.translation||t.rotation||t.scale){var n=e.Vector3.FromArray(t.scale||[1,1,1]),o=e.Quaternion.FromArray(t.rotation||[0,0,0,1]),a=e.Vector3.FromArray(t.translation||[0,0,0]);r=e.Matrix.Compose(n,o,a)}else r=e.Matrix.FromArray(t.matrix);return r},m=function(t,r,n,o){for(var a=0;a<o.bones.length;a++)if(o.bones[a].name===n)return o.bones[a];var i=t.nodes;for(var s in i){var l=i[s];if(l.jointName)for(var u=l.children,a=0;a<u.length;a++){var c=t.nodes[u[a]];if(c.jointName&&c.jointName===n){var f=p(l),d=new e.Bone(l.name||"",o,m(t,r,l.jointName,o),f);return d.id=s,d}}}return null},E=function(e,t){for(var r=0;r<e.length;r++)for(var n=e[r],o=0;o<n.node.children.length;o++){var a=n.node.children[o];if(a===t)return n.bone}return null},T=function(e,t){var r=e.nodes,n=r[t];if(n)return{node:n,id:t};for(var o in r)if(n=r[o],n.jointName===t)return{node:n,id:o};return null},_=function(e,t){for(var r=0;r<e.jointNames.length;r++)if(e.jointNames[r]===t)return!0;return!1},A=function(t,r,n,o){for(var a in t.nodes){var i=t.nodes[a],s=a;if(i.jointName&&!_(n,i.jointName)){var l=p(i),u=new e.Bone(i.name||"",r,null,l);u.id=s,o.push({bone:u,node:i,id:s})}}for(var c=0;c<o.length;c++)for(var f=o[c],d=f.node.children,h=0;h<d.length;h++){for(var m=null,E=0;E<o.length;E++)if(o[E].id===d[h]){m=o[E];break}m&&(m.bone._parent=f.bone,f.bone.children.push(m.bone))}},y=function(t,r,n,o,a){if(o||(o=new e.Skeleton(r.name||"","",t.scene)),!r.babylonSkeleton)return o;var i=[],s=[];A(t,o,r,i),o.bones=[];for(var l=0;l<r.jointNames.length;l++){var u=T(t,r.jointNames[l]);if(u){var c=u.node;if(c){var a=u.id,f=t.scene.getBoneByID(a);if(f)o.bones.push(f);else{for(var d=!1,h=null,_=0;_<l;_++){var y=T(t,r.jointNames[_]);if(y){var g=y.node;if(g){var v=g.children;if(v){d=!1;for(var L=0;L<v.length;L++)if(v[L]===a){h=m(t,r,r.jointNames[_],o),d=!0;break}if(d)break}}else e.Tools.Warn("Joint named "+r.jointNames[_]+" does not exist when looking for parent")}}var x=p(c);!h&&i.length>0&&(h=E(i,a))&&-1===s.indexOf(h)&&s.push(h);new e.Bone(c.jointName||"",o,h,x).id=a}}else e.Tools.Warn("Joint named "+r.jointNames[l]+" does not exist")}}var N=o.bones;o.bones=[];for(var l=0;l<r.jointNames.length;l++){var u=T(t,r.jointNames[l]);if(u)for(var _=0;_<N.length;_++)if(N[_].id===u.id){o.bones.push(N[_]);break}}o.prepare();for(var l=0;l<s.length;l++)o.bones.push(s[l]);return o},g=function(r,n,o,a,i){if(i||(i=new e.Mesh(n.name||"",r.scene),i.id=a),!n.babylonNode)return i;var s=new e.MultiMaterial("multimat"+a,r.scene);i.material||(i.material=s);for(var l=new e.VertexData,u=new e.Geometry(a,r.scene,l,!1,i),c=new Array,d=new Array,h=new Array,p=new Array,m=0;m<o.length;m++){var E=o[m],T=r.meshes[E];if(T)for(var _=0;_<T.primitives.length;_++){var A=new e.VertexData,y=T.primitives[_];y.mode;var g=y.attributes,v=null,L=null;for(var x in g)if(v=r.accessors[g[x]],L=t.GLTFUtils.GetBufferFromAccessor(r,v),"NORMAL"===x)A.normals=new Float32Array(L.length),A.normals.set(L);else if("POSITION"===x){if(e.GLTFFileLoader.HomogeneousCoordinates){A.positions=new Float32Array(L.length-L.length/4);for(var N=0;N<L.length;N+=4)A.positions[N]=L[N],A.positions[N+1]=L[N+1],A.positions[N+2]=L[N+2]}else A.positions=new Float32Array(L.length),A.positions.set(L);d.push(A.positions.length)}else if(-1!==x.indexOf("TEXCOORD_")){var b=Number(x.split("_")[1]),M=e.VertexBuffer.UVKind+(0===b?"":b+1),O=new Float32Array(L.length);O.set(L),f(O),A.set(O,M)}else"JOINT"===x?(A.matricesIndices=new Float32Array(L.length),A.matricesIndices.set(L)):"WEIGHT"===x?(A.matricesWeights=new Float32Array(L.length),A.matricesWeights.set(L)):"COLOR"===x&&(A.colors=new Float32Array(L.length),A.colors.set(L));if(v=r.accessors[y.indices])L=t.GLTFUtils.GetBufferFromAccessor(r,v),A.indices=new Int32Array(L.length),A.indices.set(L),p.push(A.indices.length);else{for(var F=[],N=0;N<A.positions.length/3;N++)F.push(N);A.indices=new Int32Array(F),p.push(A.indices.length)}l.merge(A);var R=r.scene.getMaterialByID(y.material);s.subMaterials.push(null===R?t.GLTFUtils.GetDefaultMaterial(r.scene):R),c.push(0===c.length?0:c[c.length-1]+d[d.length-2]),h.push(0===h.length?0:h[h.length-1]+p[p.length-2])}}u.setAllVerticesData(l,!1),i.computeWorldMatrix(!0),i.subMeshes=[];for(var S=0,m=0;m<o.length;m++){var E=o[m],T=r.meshes[E];if(T)for(var _=0;_<T.primitives.length;_++)T.primitives[_].mode,e.SubMesh.AddToMesh(S,c[S],d[S],h[S],p[S],i,i,!0),S++}return i},v=function(e,t,r,n){e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=r),e.scaling&&(e.scaling=n)},L=function(t,r,n){if(r.matrix){var o=new e.Vector3(0,0,0),a=new e.Quaternion,i=new e.Vector3(0,0,0);e.Matrix.FromArray(r.matrix).decompose(i,a,o),v(t,o,a,i)}else r.translation&&r.rotation&&r.scale&&v(t,e.Vector3.FromArray(r.translation),e.Quaternion.FromArray(r.rotation),e.Vector3.FromArray(r.scale));t.computeWorldMatrix(!0)},x=function(t,r,n,o){var a=null;if(t.importOnlyMeshes&&(r.skin||r.meshes)&&t.importMeshesNames&&t.importMeshesNames.length>0&&-1===t.importMeshesNames.indexOf(r.name||""))return null;if(r.skin){if(r.meshes){var i=t.skins[r.skin],s=g(t,r,r.meshes,n,r.babylonNode);s.skeleton=t.scene.getLastSkeletonByID(r.skin),null===s.skeleton&&i.babylonSkeleton&&(s.skeleton=y(t,i,0,i.babylonSkeleton,r.skin),i.babylonSkeleton||(i.babylonSkeleton=s.skeleton)),a=s}}else if(r.meshes){var s=g(t,r,r.mesh?[r.mesh]:r.meshes,n,r.babylonNode);a=s}else if(!r.light||r.babylonNode||t.importOnlyMeshes){if(r.camera&&!r.babylonNode&&!t.importOnlyMeshes){var l=t.cameras[r.camera];if(l)if("orthographic"===l.type){var u=new e.FreeCamera(r.camera,e.Vector3.Zero(),t.scene);u.name=r.name||"",u.mode=e.Camera.ORTHOGRAPHIC_CAMERA,u.attachControl(t.scene.getEngine().getRenderingCanvas()),a=u}else if("perspective"===l.type){var c=l[l.type],f=new e.FreeCamera(r.camera,e.Vector3.Zero(),t.scene);f.name=r.name||"",f.attachControl(t.scene.getEngine().getRenderingCanvas()),c.aspectRatio||(c.aspectRatio=t.scene.getEngine().getRenderWidth()/t.scene.getEngine().getRenderHeight()),c.znear&&c.zfar&&(f.maxZ=c.zfar,f.minZ=c.znear),a=f}}}else{var d=t.lights[r.light];if(d)if("ambient"===d.type){var h=d[d.type],p=new e.HemisphericLight(r.light,e.Vector3.Zero(),t.scene);p.name=r.name||"",h.color&&(p.diffuse=e.Color3.FromArray(h.color)),a=p}else if("directional"===d.type){var m=d[d.type],E=new e.DirectionalLight(r.light,e.Vector3.Zero(),t.scene);E.name=r.name||"",m.color&&(E.diffuse=e.Color3.FromArray(m.color)),a=E}else if("point"===d.type){var T=d[d.type],_=new e.PointLight(r.light,e.Vector3.Zero(),t.scene);_.name=r.name||"",T.color&&(_.diffuse=e.Color3.FromArray(T.color)),a=_}else if("spot"===d.type){var A=d[d.type],x=new e.SpotLight(r.light,e.Vector3.Zero(),e.Vector3.Zero(),0,0,t.scene);x.name=r.name||"",A.color&&(x.diffuse=e.Color3.FromArray(A.color)),A.fallOfAngle&&(x.angle=A.fallOfAngle),A.fallOffExponent&&(x.exponent=A.fallOffExponent),a=x}}if(!r.jointName){if(r.babylonNode)return r.babylonNode;if(null===a){var N=new e.Mesh(r.name||"",t.scene);r.babylonNode=N,a=N}}if(null!==a){if(r.matrix&&a instanceof e.Mesh)L(a,r);else{var b=r.translation||[0,0,0],M=r.rotation||[0,0,0,1],O=r.scale||[1,1,1];v(a,e.Vector3.FromArray(b),e.Quaternion.FromArray(M),e.Vector3.FromArray(O))}a.updateCache(!0),r.babylonNode=a}return a},N=function(e,t,r,n){void 0===n&&(n=!1);var o=e.nodes[t],a=null;if(n=!(e.importOnlyMeshes&&!n&&e.importMeshesNames)||(-1!==e.importMeshesNames.indexOf(o.name||"")||0===e.importMeshesNames.length),!o.jointName&&n&&null!==(a=x(e,o,t))&&(a.id=t,a.parent=r),o.children)for(var i=0;i<o.children.length;i++)N(e,o.children[i],a,n)},b=function(e){var t=e.currentScene;if(t)for(var r=0;r<t.nodes.length;r++)N(e,t.nodes[r],null);else for(var n in e.scenes){t=e.scenes[n];for(var r=0;r<t.nodes.length;r++)N(e,t.nodes[r],null)}h(e);for(var r=0;r<e.scene.skeletons.length;r++){var o=e.scene.skeletons[r];e.scene.beginAnimation(o,0,Number.MAX_VALUE,!0,1)}},M=function(e,r,n,o,a,i,s){var l=i.values||a.parameters;for(var u in n){var c=n[u],f=c.type;if(f===t.EParameterType.FLOAT_MAT2||f===t.EParameterType.FLOAT_MAT3||f===t.EParameterType.FLOAT_MAT4)if(!c.semantic||c.source||c.node){if(c.semantic&&(c.source||c.node)){var d=r.scene.getNodeByName(c.source||c.node||"");if(null===d&&(d=r.scene.getNodeByID(c.source||c.node||"")),null===d)continue;t.GLTFUtils.SetMatrix(r.scene,d,c,u,o.getEffect())}}else t.GLTFUtils.SetMatrix(r.scene,e,c,u,o.getEffect());else{var h=l[a.uniforms[u]];if(!h)continue;if(f===t.EParameterType.SAMPLER_2D){var p=r.textures[i.values?h:c.value].babylonTexture;if(null===p||void 0===p)continue;o.getEffect().setTexture(u,p)}else t.GLTFUtils.SetUniform(o.getEffect(),u,h,f)}}s(o)},O=function(e,r,n,o,a){var i=o.values||n.parameters,s=n.uniforms;for(var l in a){var u=a[l],c=u.type,f=i[s[l]];if(void 0===f&&(f=u.value),f){var d=function(e){return function(t){u.value&&e&&(r.setTexture(e,t),delete a[e])}};c===t.EParameterType.SAMPLER_2D?t.GLTFLoaderExtension.LoadTextureAsync(e,o.values?f:u.value,d(l),(function(){return d(null)})):u.value&&t.GLTFUtils.SetUniform(r,l,o.values?f:u.value,c)&&delete a[l]}}},F=function(e,t,r){return function(n,o){t.dispose(!0),r("Cannot compile program named "+e.name+". Error: "+o+". Default material will be applied")}},R=function(e,t,r,n,o,a){return function(i){O(e,t,r,n,o),t.onBind=function(i){M(i,e,o,t,r,n,a)}}},S=function(e,t,r){for(var n in t.uniforms){var i=t.uniforms[n],s=t.parameters[i];if(e.currentIdentifier===n&&s.semantic&&!s.source&&!s.node){var l=o.indexOf(s.semantic);if(-1!==l)return delete r[n],a[l]}}return e.currentIdentifier},I=function(e){for(var r in e.materials)t.GLTFLoaderExtension.LoadMaterialAsync(e,r,(function(e){}),(function(){}))},w=(function(){function i(){}return i.CreateRuntime=function(e,t,r){var n={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:r,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[]};return e.extensions&&c(e.extensions,"extensions",n),e.extensionsUsed&&c(e.extensionsUsed,"extensionsUsed",n),e.buffers&&l(e.buffers,n),e.bufferViews&&c(e.bufferViews,"bufferViews",n),e.accessors&&c(e.accessors,"accessors",n),e.meshes&&c(e.meshes,"meshes",n),e.lights&&c(e.lights,"lights",n),e.cameras&&c(e.cameras,"cameras",n),e.nodes&&c(e.nodes,"nodes",n),e.images&&c(e.images,"images",n),e.textures&&c(e.textures,"textures",n),e.shaders&&u(e.shaders,n),e.programs&&c(e.programs,"programs",n),e.samplers&&c(e.samplers,"samplers",n),e.techniques&&c(e.techniques,"techniques",n),e.materials&&c(e.materials,"materials",n),e.animations&&c(e.animations,"animations",n),e.skins&&c(e.skins,"skins",n),e.scenes&&(n.scenes=e.scenes),e.scene&&e.scenes&&(n.currentScene=e.scenes[e.scene]),n},i.LoadBufferAsync=function(r,n,o,a,i){var s=r.buffers[n];t.GLTFUtils.IsBase64(s.uri)?setTimeout((function(){return o(new Uint8Array(t.GLTFUtils.DecodeBase64(s.uri)))})):e.Tools.LoadFile(r.rootUrl+s.uri,(function(e){return o(new Uint8Array(e))}),i,void 0,!0,(function(e){e&&a(e.status+" "+e.statusText)}))},i.LoadTextureBufferAsync=function(r,n,o,a){var i=r.textures[n];if(!i||!i.source)return void a("");if(i.babylonTexture)return void o(null);var s=r.images[i.source];t.GLTFUtils.IsBase64(s.uri)?setTimeout((function(){return o(new Uint8Array(t.GLTFUtils.DecodeBase64(s.uri)))})):e.Tools.LoadFile(r.rootUrl+s.uri,(function(e){return o(new Uint8Array(e))}),void 0,void 0,!0,(function(e){e&&a(e.status+" "+e.statusText)}))},i.CreateTextureAsync=function(r,n,o,a,i){var s=r.textures[n];if(s.babylonTexture)return void a(s.babylonTexture);var l=r.samplers[s.sampler],u=l.minFilter===t.ETextureFilterType.NEAREST_MIPMAP_NEAREST||l.minFilter===t.ETextureFilterType.NEAREST_MIPMAP_LINEAR||l.minFilter===t.ETextureFilterType.LINEAR_MIPMAP_NEAREST||l.minFilter===t.ETextureFilterType.LINEAR_MIPMAP_LINEAR,c=e.Texture.BILINEAR_SAMPLINGMODE,f=new Blob([o]),d=URL.createObjectURL(f),h=function(){return URL.revokeObjectURL(d)},p=new e.Texture(d,r.scene,!u,!0,c,h,h);void 0!==l.wrapS&&(p.wrapU=t.GLTFUtils.GetWrapMode(l.wrapS)),void 0!==l.wrapT&&(p.wrapV=t.GLTFUtils.GetWrapMode(l.wrapT)),p.name=n,s.babylonTexture=p,a(p)},
  103300. i.LoadShaderStringAsync=function(r,n,o,a){var i=r.shaders[n];if(t.GLTFUtils.IsBase64(i.uri)){o(atob(i.uri.split(",")[1]))}else e.Tools.LoadFile(r.rootUrl+i.uri,o,void 0,void 0,!1,(function(e){e&&a(e.status+" "+e.statusText)}))},i.LoadMaterialAsync=function(i,s,l,u){var c=i.materials[s];if(!c.technique)return void(u&&u("No technique found."));var f=i.techniques[c.technique];if(!f){var h=new e.StandardMaterial(s,i.scene);return h.diffuseColor=new e.Color3(.5,.5,.5),h.sideOrientation=e.Material.CounterClockWiseSideOrientation,void l(h)}var p=i.programs[f.program],m=f.states,E=e.Effect.ShadersStore[p.vertexShader+"VertexShader"],T=e.Effect.ShadersStore[p.fragmentShader+"PixelShader"],_="",A="",y=new n(E),g=new n(T),v={},L=[],x=[],N=[];for(var b in f.uniforms){var M=f.uniforms[b],O=f.parameters[M];if(v[b]=O,!O.semantic||O.node||O.source)O.type===t.EParameterType.SAMPLER_2D?N.push(b):L.push(b);else{var I=o.indexOf(O.semantic);-1!==I?(L.push(a[I]),delete v[b]):L.push(b)}}for(var w in f.attributes){var P=f.attributes[w],B=f.parameters[P];B.semantic&&x.push(d(B))}for(;!y.isEnd()&&y.getNextToken();){var C=y.currentToken;if(C===r.IDENTIFIER){var G=!1;for(var w in f.attributes){var P=f.attributes[w],B=f.parameters[P];if(y.currentIdentifier===w&&B.semantic){_+=d(B),G=!0;break}}G||(_+=S(y,f,v))}else _+=y.currentString}for(;!g.isEnd()&&g.getNextToken();){var C=g.currentToken;C===r.IDENTIFIER?A+=S(g,f,v):A+=g.currentString}var D={vertex:p.vertexShader+s,fragment:p.fragmentShader+s},V={attributes:x,uniforms:L,samplers:N,needAlphaBlending:m&&m.enable&&-1!==m.enable.indexOf(3042)};e.Effect.ShadersStore[p.vertexShader+s+"VertexShader"]=_,e.Effect.ShadersStore[p.fragmentShader+s+"PixelShader"]=A;var U=new e.ShaderMaterial(s,i.scene,D,V);if(U.onError=F(p,U,u),U.onCompiled=R(i,U,f,c,v,l),U.sideOrientation=e.Material.CounterClockWiseSideOrientation,m&&m.functions){var k=m.functions;k.cullFace&&k.cullFace[0]!==t.ECullingType.BACK&&(U.backFaceCulling=!1);var H=k.blendFuncSeparate;H&&(H[0]===t.EBlendingFunction.SRC_ALPHA&&H[1]===t.EBlendingFunction.ONE_MINUS_SRC_ALPHA&&H[2]===t.EBlendingFunction.ONE&&H[3]===t.EBlendingFunction.ONE?U.alphaMode=e.Engine.ALPHA_COMBINE:H[0]===t.EBlendingFunction.ONE&&H[1]===t.EBlendingFunction.ONE&&H[2]===t.EBlendingFunction.ZERO&&H[3]===t.EBlendingFunction.ONE?U.alphaMode=e.Engine.ALPHA_ONEONE:H[0]===t.EBlendingFunction.SRC_ALPHA&&H[1]===t.EBlendingFunction.ONE&&H[2]===t.EBlendingFunction.ZERO&&H[3]===t.EBlendingFunction.ONE?U.alphaMode=e.Engine.ALPHA_ADD:H[0]===t.EBlendingFunction.ZERO&&H[1]===t.EBlendingFunction.ONE_MINUS_SRC_COLOR&&H[2]===t.EBlendingFunction.ONE&&H[3]===t.EBlendingFunction.ONE?U.alphaMode=e.Engine.ALPHA_SUBTRACT:H[0]===t.EBlendingFunction.DST_COLOR&&H[1]===t.EBlendingFunction.ZERO&&H[2]===t.EBlendingFunction.ONE&&H[3]===t.EBlendingFunction.ONE?U.alphaMode=e.Engine.ALPHA_MULTIPLY:H[0]===t.EBlendingFunction.SRC_ALPHA&&H[1]===t.EBlendingFunction.ONE_MINUS_SRC_COLOR&&H[2]===t.EBlendingFunction.ONE&&H[3]===t.EBlendingFunction.ONE&&(U.alphaMode=e.Engine.ALPHA_MAXIMIZED))}},i})();t.GLTFLoaderBase=w;var P=(function(){function r(){}return r.RegisterExtension=function(t){if(r.Extensions[t.name])return void e.Tools.Error('Tool with the same name "'+t.name+'" already exists');r.Extensions[t.name]=t},r.prototype.dispose=function(){},r.prototype.importMeshAsync=function(r,n,o,a,i,s,l){var u=this;return n.useRightHandedSystem=!0,t.GLTFLoaderExtension.LoadRuntimeAsync(n,o,a,(function(t){t.importOnlyMeshes=!0,""===r?t.importMeshesNames=[]:"string"==typeof r?t.importMeshesNames=[r]:!r||r instanceof Array?(t.importMeshesNames=[],e.Tools.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[r],u._createNodes(t);var n=new Array,o=new Array;for(var a in t.nodes){var l=t.nodes[a];l.babylonNode instanceof e.AbstractMesh&&n.push(l.babylonNode)}for(var c in t.skins){var f=t.skins[c];f.babylonSkeleton instanceof e.Skeleton&&o.push(f.babylonSkeleton)}u._loadBuffersAsync(t,(function(){u._loadShadersAsync(t,(function(){I(t),b(t),!e.GLTFFileLoader.IncrementalLoading&&i&&i(n,[],o)}))}),s),e.GLTFFileLoader.IncrementalLoading&&i&&i(n,[],o)}),l),!0},r.prototype.loadAsync=function(r,n,o,a,i,s){var l=this;r.useRightHandedSystem=!0,t.GLTFLoaderExtension.LoadRuntimeAsync(r,n,o,(function(r){t.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(r,(function(){l._createNodes(r),l._loadBuffersAsync(r,(function(){l._loadShadersAsync(r,(function(){I(r),b(r),e.GLTFFileLoader.IncrementalLoading||a()}))})),e.GLTFFileLoader.IncrementalLoading&&a()}),s)}),s)},r.prototype._loadShadersAsync=function(r,n){var o=!1,a=function(o,a){t.GLTFLoaderExtension.LoadShaderStringAsync(r,o,(function(i){r.loadedShaderCount++,i&&(e.Effect.ShadersStore[o+(a.type===t.EShaderType.VERTEX?"VertexShader":"PixelShader")]=i),r.loadedShaderCount===r.shaderscount&&n()}),(function(){e.Tools.Error("Error when loading shader program named "+o+" located at "+a.uri)}))};for(var i in r.shaders){o=!0;var s=r.shaders[i];s?a.bind(this,i,s)():e.Tools.Error("No shader named: "+i)}o||n()},r.prototype._loadBuffersAsync=function(r,n,o){var a=!1,i=function(o,a){t.GLTFLoaderExtension.LoadBufferAsync(r,o,(function(t){r.loadedBufferCount++,t&&(t.byteLength!=r.buffers[o].byteLength&&e.Tools.Error("Buffer named "+o+" is length "+t.byteLength+". Expected: "+a.byteLength),r.loadedBufferViews[o]=t),r.loadedBufferCount===r.buffersCount&&n()}),(function(){e.Tools.Error("Error when loading buffer named "+o+" located at "+a.uri)}))};for(var s in r.buffers){a=!0;var l=r.buffers[s];l?i.bind(this,s,l)():e.Tools.Error("No buffer named: "+s)}a||n()},r.prototype._createNodes=function(e){var t=e.currentScene;if(t)for(var r=0;r<t.nodes.length;r++)N(e,t.nodes[r],null);else for(var n in e.scenes){t=e.scenes[n];for(var r=0;r<t.nodes.length;r++)N(e,t.nodes[r],null)}},r.Extensions={},r})();t.GLTFLoader=P,e.GLTFFileLoader.CreateGLTFLoaderV1=function(){return new P}})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r=(function(){function r(){}return r.SetMatrix=function(r,n,o,a,i){var s=null;if("MODEL"===o.semantic?s=n.getWorldMatrix():"PROJECTION"===o.semantic?s=r.getProjectionMatrix():"VIEW"===o.semantic?s=r.getViewMatrix():"MODELVIEWINVERSETRANSPOSE"===o.semantic?s=e.Matrix.Transpose(n.getWorldMatrix().multiply(r.getViewMatrix()).invert()):"MODELVIEW"===o.semantic?s=n.getWorldMatrix().multiply(r.getViewMatrix()):"MODELVIEWPROJECTION"===o.semantic?s=n.getWorldMatrix().multiply(r.getTransformMatrix()):"MODELINVERSE"===o.semantic?s=n.getWorldMatrix().invert():"VIEWINVERSE"===o.semantic?s=r.getViewMatrix().invert():"PROJECTIONINVERSE"===o.semantic?s=r.getProjectionMatrix().invert():"MODELVIEWINVERSE"===o.semantic?s=n.getWorldMatrix().multiply(r.getViewMatrix()).invert():"MODELVIEWPROJECTIONINVERSE"===o.semantic?s=n.getWorldMatrix().multiply(r.getTransformMatrix()).invert():"MODELINVERSETRANSPOSE"===o.semantic&&(s=e.Matrix.Transpose(n.getWorldMatrix().invert())),s)switch(o.type){case t.EParameterType.FLOAT_MAT2:i.setMatrix2x2(a,e.Matrix.GetAsMatrix2x2(s));break;case t.EParameterType.FLOAT_MAT3:i.setMatrix3x3(a,e.Matrix.GetAsMatrix3x3(s));break;case t.EParameterType.FLOAT_MAT4:i.setMatrix(a,s)}},r.SetUniform=function(r,n,o,a){switch(a){case t.EParameterType.FLOAT:return r.setFloat(n,o),!0;case t.EParameterType.FLOAT_VEC2:return r.setVector2(n,e.Vector2.FromArray(o)),!0;case t.EParameterType.FLOAT_VEC3:return r.setVector3(n,e.Vector3.FromArray(o)),!0;case t.EParameterType.FLOAT_VEC4:return r.setVector4(n,e.Vector4.FromArray(o)),!0;default:return!1}},r.IsBase64=function(e){return!(e.length<5)&&"data:"===e.substr(0,5)},r.DecodeBase64=function(e){for(var t=atob(e.split(",")[1]),r=t.length,n=new Uint8Array(new ArrayBuffer(r)),o=0;o<r;o++)n[o]=t.charCodeAt(o);return n.buffer},r.GetWrapMode=function(r){switch(r){case t.ETextureWrapMode.CLAMP_TO_EDGE:return e.Texture.CLAMP_ADDRESSMODE;case t.ETextureWrapMode.MIRRORED_REPEAT:return e.Texture.MIRROR_ADDRESSMODE;case t.ETextureWrapMode.REPEAT:default:return e.Texture.WRAP_ADDRESSMODE}},r.GetByteStrideFromType=function(e){switch(e.type){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}},r.GetTextureFilterMode=function(r){switch(r){case t.ETextureFilterType.LINEAR:case t.ETextureFilterType.LINEAR_MIPMAP_NEAREST:case t.ETextureFilterType.LINEAR_MIPMAP_LINEAR:return e.Texture.TRILINEAR_SAMPLINGMODE;case t.ETextureFilterType.NEAREST:case t.ETextureFilterType.NEAREST_MIPMAP_NEAREST:return e.Texture.NEAREST_SAMPLINGMODE;default:return e.Texture.BILINEAR_SAMPLINGMODE}},r.GetBufferFromBufferView=function(e,r,n,o,a){var n=r.byteOffset+n,i=e.loadedBufferViews[r.buffer];if(n+o>i.byteLength)throw new Error("Buffer access is out of range");var s=i.buffer;switch(n+=i.byteOffset,a){case t.EComponentType.BYTE:return new Int8Array(s,n,o);case t.EComponentType.UNSIGNED_BYTE:return new Uint8Array(s,n,o);case t.EComponentType.SHORT:return new Int16Array(s,n,o);case t.EComponentType.UNSIGNED_SHORT:return new Uint16Array(s,n,o);default:return new Float32Array(s,n,o)}},r.GetBufferFromAccessor=function(e,t){var n=e.bufferViews[t.bufferView],o=t.count*r.GetByteStrideFromType(t);return r.GetBufferFromBufferView(e,n,t.byteOffset,o,t.componentType)},r.DecodeBufferToText=function(e){for(var t="",r=e.byteLength,n=0;n<r;++n)t+=String.fromCharCode(e[n]);return t},r.GetDefaultMaterial=function(t){if(!r._DefaultMaterial){e.Effect.ShadersStore.GLTFDefaultMaterialVertexShader=["precision highp float;","","uniform mat4 worldView;","uniform mat4 projection;","","attribute vec3 position;","","void main(void)","{"," gl_Position = projection * worldView * vec4(position, 1.0);","}"].join("\n"),e.Effect.ShadersStore.GLTFDefaultMaterialPixelShader=["precision highp float;","","uniform vec4 u_emission;","","void main(void)","{"," gl_FragColor = u_emission;","}"].join("\n");var n={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},o={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};r._DefaultMaterial=new e.ShaderMaterial("GLTFDefaultMaterial",t,n,o),r._DefaultMaterial.setColor4("u_emission",new e.Color4(.5,.5,.5,1))}return r._DefaultMaterial},r._DefaultMaterial=null,r})();t.GLTFUtils=r})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){var t=(function(){function t(e){this._name=e}return Object.defineProperty(t.prototype,"name",{get:function(){return this._name},enumerable:!0,configurable:!0}),t.prototype.loadRuntimeAsync=function(e,t,r,n,o){return!1},t.prototype.loadRuntimeExtensionsAsync=function(e,t,r){return!1},t.prototype.loadBufferAsync=function(e,t,r,n,o){return!1},t.prototype.loadTextureBufferAsync=function(e,t,r,n){return!1},t.prototype.createTextureAsync=function(e,t,r,n,o){return!1},t.prototype.loadShaderStringAsync=function(e,t,r,n){return!1},t.prototype.loadMaterialAsync=function(e,t,r,n){return!1},t.LoadRuntimeAsync=function(r,n,o,a,i){t.ApplyExtensions((function(e){return e.loadRuntimeAsync(r,n,o,a,i)}),(function(){setTimeout((function(){a(e.GLTFLoaderBase.CreateRuntime(n.json,r,o))}))}))},t.LoadRuntimeExtensionsAsync=function(e,r,n){t.ApplyExtensions((function(t){return t.loadRuntimeExtensionsAsync(e,r,n)}),(function(){setTimeout((function(){r()}))}))},t.LoadBufferAsync=function(r,n,o,a,i){t.ApplyExtensions((function(e){return e.loadBufferAsync(r,n,o,a,i)}),(function(){e.GLTFLoaderBase.LoadBufferAsync(r,n,o,a,i)}))},t.LoadTextureAsync=function(e,r,n,o){t.LoadTextureBufferAsync(e,r,(function(a){return t.CreateTextureAsync(e,r,a,n,o)}),o)},t.LoadShaderStringAsync=function(r,n,o,a){t.ApplyExtensions((function(e){return e.loadShaderStringAsync(r,n,o,a)}),(function(){e.GLTFLoaderBase.LoadShaderStringAsync(r,n,o,a)}))},t.LoadMaterialAsync=function(r,n,o,a){t.ApplyExtensions((function(e){return e.loadMaterialAsync(r,n,o,a)}),(function(){e.GLTFLoaderBase.LoadMaterialAsync(r,n,o,a)}))},t.LoadTextureBufferAsync=function(r,n,o,a){t.ApplyExtensions((function(e){return e.loadTextureBufferAsync(r,n,o,a)}),(function(){e.GLTFLoaderBase.LoadTextureBufferAsync(r,n,o,a)}))},t.CreateTextureAsync=function(r,n,o,a,i){t.ApplyExtensions((function(e){return e.createTextureAsync(r,n,o,a,i)}),(function(){e.GLTFLoaderBase.CreateTextureAsync(r,n,o,a,i)}))},t.ApplyExtensions=function(t,r){for(var n in e.GLTFLoader.Extensions){if(t(e.GLTFLoader.Extensions[n]))return}r()},t})();e.GLTFLoaderExtension=t})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){var t=(function(t){function r(){return t.call(this,"KHR_binary_glTF")||this}return __extends(r,t),r.prototype.loadRuntimeAsync=function(t,r,n,o,a){var i=r.json.extensionsUsed;return!(!i||-1===i.indexOf(this.name)||!r.bin)&&(this._bin=r.bin,o(e.GLTFLoaderBase.CreateRuntime(r.json,t,n)),!0)},r.prototype.loadBufferAsync=function(e,t,r,n){return-1!==e.extensionsUsed.indexOf(this.name)&&("binary_glTF"===t&&(r(this._bin),!0))},r.prototype.loadTextureBufferAsync=function(t,r,n,o){var a=t.textures[r],i=t.images[a.source];if(!(i.extensions&&this.name in i.extensions))return!1;var s=i.extensions[this.name],l=t.bufferViews[s.bufferView];return n(e.GLTFUtils.GetBufferFromBufferView(t,l,0,l.byteLength,e.EComponentType.UNSIGNED_BYTE)),!0},r.prototype.loadShaderStringAsync=function(t,r,n,o){var a=t.shaders[r];if(!(a.extensions&&this.name in a.extensions))return!1;var i=a.extensions[this.name],s=t.bufferViews[i.bufferView],l=e.GLTFUtils.GetBufferFromBufferView(t,s,0,s.byteLength,e.EComponentType.UNSIGNED_BYTE);return setTimeout((function(){var t=e.GLTFUtils.DecodeBufferToText(l);n(t)})),!0},r})(e.GLTFLoaderExtension);e.GLTFBinaryExtension=t,e.GLTFLoader.RegisterExtension(new t)})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r=(function(r){function n(){return r.call(this,"KHR_materials_common")||this}return __extends(n,r),n.prototype.loadRuntimeExtensionsAsync=function(t,r,n){if(!t.extensions)return!1;var o=t.extensions[this.name];if(!o)return!1;var a=o.lights;if(a)for(var i in a){var s=a[i];switch(s.type){case"ambient":var l=new e.HemisphericLight(s.name,new e.Vector3(0,1,0),t.scene),u=s.ambient;u&&(l.diffuse=e.Color3.FromArray(u.color||[1,1,1]));break;case"point":var c=new e.PointLight(s.name,new e.Vector3(10,10,10),t.scene),f=s.point;f&&(c.diffuse=e.Color3.FromArray(f.color||[1,1,1]));break;case"directional":var d=new e.DirectionalLight(s.name,new e.Vector3(0,-1,0),t.scene),h=s.directional;h&&(d.diffuse=e.Color3.FromArray(h.color||[1,1,1]));break;case"spot":var p=s.spot;if(p){var m=new e.SpotLight(s.name,new e.Vector3(0,10,0),new e.Vector3(0,-1,0),p.fallOffAngle||Math.PI,p.fallOffExponent||0,t.scene);m.diffuse=e.Color3.FromArray(p.color||[1,1,1])}break;default:e.Tools.Warn('GLTF Material Common extension: light type "'+s.type+"” not supported")}}return!1},n.prototype.loadMaterialAsync=function(t,r,n,o){var a=t.materials[r];if(!a||!a.extensions)return!1;var i=a.extensions[this.name];if(!i)return!1;var s=new e.StandardMaterial(r,t.scene);return s.sideOrientation=e.Material.CounterClockWiseSideOrientation,"CONSTANT"===i.technique&&(s.disableLighting=!0),s.backFaceCulling=void 0!==i.doubleSided&&!i.doubleSided,s.alpha=void 0===i.values.transparency?1:i.values.transparency,s.specularPower=void 0===i.values.shininess?0:i.values.shininess,"string"==typeof i.values.ambient?this._loadTexture(t,i.values.ambient,s,"ambientTexture",o):s.ambientColor=e.Color3.FromArray(i.values.ambient||[0,0,0]),"string"==typeof i.values.diffuse?this._loadTexture(t,i.values.diffuse,s,"diffuseTexture",o):s.diffuseColor=e.Color3.FromArray(i.values.diffuse||[0,0,0]),"string"==typeof i.values.emission?this._loadTexture(t,i.values.emission,s,"emissiveTexture",o):s.emissiveColor=e.Color3.FromArray(i.values.emission||[0,0,0]),"string"==typeof i.values.specular?this._loadTexture(t,i.values.specular,s,"specularTexture",o):s.specularColor=e.Color3.FromArray(i.values.specular||[0,0,0]),!0},n.prototype._loadTexture=function(e,r,n,o,a){t.GLTFLoaderBase.LoadTextureBufferAsync(e,r,(function(i){t.GLTFLoaderBase.CreateTextureAsync(e,r,i,(function(e){return n[o]=e}),a)}),a)},n})(t.GLTFLoaderExtension);t.GLTFMaterialsCommonExtension=r,t.GLTFLoader.RegisterExtension(new r)})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){!(function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.UNSIGNED_INT=5125]="UNSIGNED_INT",e[e.FLOAT=5126]="FLOAT"})(e.EComponentType||(e.EComponentType={}));!(function(e){e[e.POINTS=0]="POINTS",e[e.LINES=1]="LINES",e[e.LINE_LOOP=2]="LINE_LOOP",e[e.LINE_STRIP=3]="LINE_STRIP",e[e.TRIANGLES=4]="TRIANGLES",e[e.TRIANGLE_STRIP=5]="TRIANGLE_STRIP",e[e.TRIANGLE_FAN=6]="TRIANGLE_FAN"})(e.EMeshPrimitiveMode||(e.EMeshPrimitiveMode={}));!(function(e){e[e.NEAREST=9728]="NEAREST",e[e.LINEAR=9729]="LINEAR"})(e.ETextureMagFilter||(e.ETextureMagFilter={}));!(function(e){e[e.NEAREST=9728]="NEAREST",e[e.LINEAR=9729]="LINEAR",e[e.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",e[e.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",e[e.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",e[e.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"})(e.ETextureMinFilter||(e.ETextureMinFilter={}));!(function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"})(e.ETextureWrapMode||(e.ETextureWrapMode={}))})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r=(function(){function e(e){this._pendingCount=0,this._callback=e}return e.prototype._addPendingData=function(e){this._pendingCount++},e.prototype._removePendingData=function(e){0==--this._pendingCount&&this._callback()},e})(),n=(function(){function n(t){this._disposed=!1,this._renderReady=!1,this._requests=new Array,this._renderReadyObservable=new e.Observable,this._renderPendingCount=0,this._loaderPendingCount=0,this._loaderTrackers=new Array,this._parent=t}return n.RegisterExtension=function(r){if(n.Extensions[r.name])return void e.Tools.Error("Extension with the same name '"+r.name+"' already exists");n.Extensions[r.name]=r,t.GLTFLoaderExtension._Extensions.push(r)},n.prototype.dispose=function(){if(!this._disposed){this._disposed=!0;for(var e=0,t=this._requests;e<t.length;e++){var r=t[e];r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort()}if(this._gltf.textures)for(var n=0,o=this._gltf.textures;n<o.length;n++){var a=o[n];a.url&&URL.revokeObjectURL(a.url)}}},n.prototype.importMeshAsync=function(e,t,r,n,o,a,i){var s=this;this._loadAsync(e,t,r,n,(function(){o(s._getMeshes(),[],s._getSkeletons())}),a,i)},n.prototype.loadAsync=function(e,t,r,n,o,a){this._loadAsync(null,e,t,r,n,o,a)},n.prototype._loadAsync=function(e,t,r,n,o,a,i){var s=this;this._tryCatchOnError((function(){s._loadData(r),s._babylonScene=t,s._rootUrl=n,s._successCallback=o,s._progressCallback=a,s._errorCallback=i,s._addPendingData(s),s._loadDefaultScene(e),s._loadAnimations(),s._removePendingData(s)}))},n.prototype._onProgress=function(e){this._progressCallback&&this._progressCallback(e)},n.prototype._executeWhenRenderReady=function(e){this._renderReady?e():this._renderReadyObservable.add(e)},n.prototype._onRenderReady=function(){this._rootNode.babylonMesh.setEnabled(!0),this._startAnimations(),this._successCallback(),this._renderReadyObservable.notifyObservers(this)},n.prototype._onComplete=function(){this._parent.onComplete&&this._parent.onComplete(),this.dispose()},n.prototype._loadData=function(t){if(this._gltf=t.json,n._AssignIndices(this._gltf.accessors),n._AssignIndices(this._gltf.animations),n._AssignIndices(this._gltf.buffers),n._AssignIndices(this._gltf.bufferViews),n._AssignIndices(this._gltf.images),n._AssignIndices(this._gltf.materials),n._AssignIndices(this._gltf.meshes),n._AssignIndices(this._gltf.nodes),n._AssignIndices(this._gltf.scenes),n._AssignIndices(this._gltf.skins),n._AssignIndices(this._gltf.textures),t.bin){var r=this._gltf.buffers;if(r&&r[0]&&!r[0].uri){var o=r[0];o.byteLength!=t.bin.byteLength&&e.Tools.Warn("Binary buffer length ("+o.byteLength+") from JSON does not match chunk length ("+t.bin.byteLength+")"),o.loadedData=t.bin}else e.Tools.Warn("Unexpected BIN chunk")}},n.prototype._getMeshes=function(){var e=new Array;e.push(this._rootNode.babylonMesh);var t=this._gltf.nodes;if(t)for(var r=0,n=t;r<n.length;r++){var o=n[r];o.babylonMesh&&e.push(o.babylonMesh)}return e},n.prototype._getSkeletons=function(){var e=new Array,t=this._gltf.skins;if(t)for(var r=0,n=t;r<n.length;r++){var o=n[r];o.babylonSkeleton&&e.push(o.babylonSkeleton)}return e},n.prototype._getAnimationTargets=function(){var e=new Array,t=this._gltf.animations;if(t)for(var r=0,n=t;r<n.length;r++){var o=n[r];e.push.apply(e,o.targets)}return e},n.prototype._startAnimations=function(){for(var e=0,t=this._getAnimationTargets();e<t.length;e++){var r=t[e];this._babylonScene.beginAnimation(r,0,Number.MAX_VALUE,!0)}},n.prototype._loadDefaultScene=function(e){var t=n._GetProperty(this._gltf.scenes,this._gltf.scene||0);if(!t)throw new Error("Failed to find scene "+(this._gltf.scene||0));this._loadScene("#/scenes/"+t.index,t,e)},n.prototype._loadScene=function(t,r,o){switch(this._rootNode={babylonMesh:new e.Mesh("__root__",this._babylonScene)},this._parent.coordinateSystemMode){case e.GLTFLoaderCoordinateSystemMode.AUTO:this._babylonScene.useRightHandedSystem||(this._rootNode.babylonMesh.rotation=new e.Vector3(0,Math.PI,0),this._rootNode.babylonMesh.scaling=new e.Vector3(1,1,-1));break;case e.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:break;case e.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:return void e.Tools.Error("Invalid coordinate system mode "+this._parent.coordinateSystemMode)}var a=r.nodes;if(this._traverseNodes(t,a,(function(e,t){return e.parent=t,!0}),this._rootNode),o){o instanceof Array||(o=[o]);var i=new Array;this._traverseNodes(t,a,(function(e){return-1===o.indexOf(e.name)||(i.push(e.index),!1)}),this._rootNode),a=i}for(var s=0,l=a;s<l.length;s++){var u=l[s],c=n._GetProperty(this._gltf.nodes,u);if(!c)throw new Error(t+": Failed to find node "+u);this._loadNode("#/nodes/"+u,c)}this._rootNode.babylonMesh.setEnabled(!1)},n.prototype._loadNode=function(r,o){if(o.babylonBones={},o.babylonAnimationTargets=[],!t.GLTFLoaderExtension.LoadNode(this,r,o)){if(o.babylonMesh=new e.Mesh(o.name||"mesh"+o.index,this._babylonScene),o.babylonMesh.hasVertexAlpha=!0,this._loadTransform(o),null!=o.mesh){var a=n._GetProperty(this._gltf.meshes,o.mesh);if(!a)throw new Error(r+": Failed to find mesh "+o.mesh);this._loadMesh("#/meshes/"+o.mesh,o,a)}if(o.babylonMesh.parent=o.parent?o.parent.babylonMesh:null,o.babylonAnimationTargets.push(o.babylonMesh),null!=o.skin){var i=n._GetProperty(this._gltf.skins,o.skin);if(!i)throw new Error(r+": Failed to find skin "+o.skin);o.babylonMesh.skeleton=this._loadSkin("#/skins/"+o.skin,i)}if(o.camera,o.children)for(var s=0,l=o.children;s<l.length;s++){var u=l[s],c=n._GetProperty(this._gltf.nodes,u);if(!c)throw new Error(r+": Failed to find child node "+u);this._loadNode("#/nodes/"+u,c)}}},n.prototype._loadMesh=function(t,r,o){var a=this,i=o.primitives;if(!i||0===i.length)throw new Error(t+": Primitives are missing");this._createMorphTargets(t,r,o),this._loadAllVertexDataAsync(t,o,(function(){a._loadMorphTargets(t,r,o);for(var n=new e.VertexData,s=0,l=i;s<l.length;s++){var u=l[s];n.merge(u.vertexData)}new e.Geometry(r.babylonMesh.name,a._babylonScene,n,!1,r.babylonMesh),r.babylonMesh.subMeshes=[];for(var c=0,f=0,d=0;d<i.length;d++){var h=i[d].vertexData,p=h.positions.length,m=h.indices.length;e.SubMesh.AddToMesh(d,c,p,f,m,r.babylonMesh),c+=p,f+=m}}));var s=new e.MultiMaterial(r.babylonMesh.name,this._babylonScene);r.babylonMesh.material=s;for(var l=s.subMaterials,u=this,c=0;c<i.length;c++)!(function(e){var o=i[e];if(null==o.material)l[e]=u._getDefaultMaterial();else{var s=n._GetProperty(u._gltf.materials,o.material);if(!s)throw new Error(t+": Failed to find material "+o.material);u._loadMaterial("#/materials/"+s.index,s,(function(t,n){n&&a._parent.onMaterialLoaded&&a._parent.onMaterialLoaded(t),a._parent.onBeforeMaterialReadyAsync?(a._addLoaderPendingData(s),a._parent.onBeforeMaterialReadyAsync(t,r.babylonMesh,null!=l[e],(function(){a._tryCatchOnError((function(){l[e]=t,a._removeLoaderPendingData(s)}))}))):l[e]=t}))}})(c)},n.prototype._loadAllVertexDataAsync=function(e,t,r){for(var n=t.primitives,o=n.length,a=this,i=0;i<n.length;i++)!(function(i){var s=n[i];a._loadVertexDataAsync(e+"/primitive/"+i,t,s,(function(e){s.vertexData=e,0==--o&&r()}))})(i)},n.prototype._convertToFloat4TextureCoordArray=function(e,r,n){if(n.componentType==t.EComponentType.FLOAT)return r;var o=r,a=1;switch(n.componentType){case t.EComponentType.UNSIGNED_BYTE:a=1/255;break;case t.EComponentType.UNSIGNED_SHORT:a=1/65535;break;default:throw new Error(e+": Invalid component type ("+n.componentType+")")}for(var i=new Float32Array(2*n.count),s=0;s<i.length;++s)i[s]=o[s]*a;return i},n.prototype._convertToFloat4ColorArray=function(e,r,o){var a=n._GetNumComponents(o.type);if(4===a&&o.componentType===t.EComponentType.FLOAT)return r;var i=r,s=1;switch(o.componentType){case t.EComponentType.FLOAT:s=1;break;case t.EComponentType.UNSIGNED_BYTE:s=1/255;break;case t.EComponentType.UNSIGNED_SHORT:s=1/65535;break;default:throw new Error(e+": Invalid component type ("+o.componentType+")")}var l=new Float32Array(4*o.count);if(4===a)for(var u=0;u<l.length;++u)l[u]=i[u]*s;else for(var c=0,u=0;u<l.length;++u)l[u]=(u+1)%4==0?1:i[c++]*s;return l},n.prototype._loadVertexDataAsync=function(r,o,a,i){var s=this,l=a.attributes;if(!l)throw new Error(r+": Attributes are missing");if(a.mode&&a.mode!==t.EMeshPrimitiveMode.TRIANGLES)throw new Error(r+": Mode "+a.mode+" is not currently supported");var u=new e.VertexData,c=Object.keys(l).length,f=this;for(var d in l)!(function(t){var o=n._GetProperty(f._gltf.accessors,l[t]);if(!o)throw new Error(r+": Failed to find attribute '"+t+"' accessor "+l[t]);f._loadAccessorAsync("#/accessors/"+o.index,o,(function(l){switch(t){case"POSITION":u.positions=l;break;case"NORMAL":u.normals=l;break;case"TANGENT":u.tangents=l;break;case"TEXCOORD_0":u.uvs=s._convertToFloat4TextureCoordArray(r,l,o);break;case"TEXCOORD_1":u.uvs2=s._convertToFloat4TextureCoordArray(r,l,o);break;case"JOINTS_0":u.matricesIndices=new Float32Array(Array.prototype.slice.apply(l));break;case"WEIGHTS_0":u.matricesWeights=l;break;case"COLOR_0":u.colors=s._convertToFloat4ColorArray(r,l,o);break;default:e.Tools.Warn("Ignoring unrecognized attribute '"+t+"'")}if(0==--c)if(null==a.indices){u.indices=new Uint32Array(u.positions.length/3);for(var f=0;f<u.indices.length;f++)u.indices[f]=f;i(u)}else{var d=n._GetProperty(s._gltf.accessors,a.indices);if(!d)throw new Error(r+": Failed to find indices accessor "+a.indices);s._loadAccessorAsync("#/accessors/"+d.index,d,(function(e){u.indices=e,i(u)}))}}))})(d)},n.prototype._createMorphTargets=function(t,r,n){var o=n.primitives,a=o[0].targets;if(a){for(var i=0,s=o;i<s.length;i++){var l=s[i];if(!l.targets||l.targets.length!=a.length)throw new Error(t+": All primitives are required to list the same number of targets")}var u=new e.MorphTargetManager;r.babylonMesh.morphTargetManager=u;for(var c=0;c<a.length;c++){var f=r.weights?r.weights[c]:n.weights?n.weights[c]:0;u.addTarget(new e.MorphTarget("morphTarget"+c,f))}}},n.prototype._loadMorphTargets=function(t,r,n){var o=r.babylonMesh.morphTargetManager;o&&this._loadAllMorphTargetVertexDataAsync(t,r,n,(function(){for(var r=o.numTargets,a=0;a<r;a++){for(var i=new e.VertexData,s=0,l=n.primitives;s<l.length;s++){var u=l[s];i.merge(u.targetsVertexData[a],{tangentLength:3})}if(!i.positions)throw new Error(t+": Positions are missing");var c=o.getTarget(a);c.setPositions(i.positions),c.setNormals(i.normals),c.setTangents(i.tangents)}}))},n.prototype._loadAllMorphTargetVertexDataAsync=function(e,t,r,n){for(var o=r.primitives.length*t.babylonMesh.morphTargetManager.numTargets,a=this,i=0,s=r.primitives;i<s.length;i++){var l=s[i];!(function(t){var r=t.targets;t.targetsVertexData=new Array(r.length);for(var i=0;i<r.length;i++)!(function(i){a._loadMorphTargetVertexDataAsync(e+"/targets/"+i,t.vertexData,r[i],(function(e){t.targetsVertexData[i]=e,0==--o&&n()}))})(i)})(l)}},n.prototype._loadMorphTargetVertexDataAsync=function(t,r,o,a){var i=new e.VertexData,s=Object.keys(o).length,l=this;for(var u in o)!(function(u){var c=n._GetProperty(l._gltf.accessors,o[u]);if(!c)throw new Error(t+": Failed to find attribute '"+u+"' accessor "+o[u]);l._loadAccessorAsync("#/accessors/"+c.index,c,(function(t){var n=t;switch(u){case"POSITION":for(var o=0;o<n.length;o++)n[o]+=r.positions[o];i.positions=n;break;case"NORMAL":for(var o=0;o<n.length;o++)n[o]+=r.normals[o];i.normals=n;break;case"TANGENT":for(var o=0,l=0;o<n.length;o++,l++)n[o]+=r.tangents[l],(o+1)%3==0&&l++;i.tangents=n;break;default:e.Tools.Warn("Ignoring unrecognized attribute '"+u+"'")}0==--s&&a(i)}))})(u)},n.prototype._loadTransform=function(t){var r=e.Vector3.Zero(),n=e.Quaternion.Identity(),o=e.Vector3.One();if(t.matrix){e.Matrix.FromArray(t.matrix).decompose(o,n,r)}else t.translation&&(r=e.Vector3.FromArray(t.translation)),t.rotation&&(n=e.Quaternion.FromArray(t.rotation)),t.scale&&(o=e.Vector3.FromArray(t.scale));t.babylonMesh.position=r,t.babylonMesh.rotationQuaternion=n,t.babylonMesh.scaling=o},n.prototype._loadSkin=function(t,r){var o=this,a="skeleton"+r.index;if(r.babylonSkeleton=new e.Skeleton(r.name||a,a,this._babylonScene),null==r.inverseBindMatrices)this._loadBones(t,r,null);else{var i=n._GetProperty(this._gltf.accessors,r.inverseBindMatrices);if(!i)throw new Error(t+": Failed to find inverse bind matrices attribute "+r.inverseBindMatrices);this._loadAccessorAsync("#/accessors/"+i.index,i,(function(e){o._loadBones(t,r,e)}))}return r.babylonSkeleton},n.prototype._createBone=function(t,r,n,o,a,i){var s=new e.Bone(t.name||"bone"+t.index,r.babylonSkeleton,n,o,null,a,i);return t.babylonBones[r.index]=s,t.babylonAnimationTargets.push(s),s},n.prototype._loadBones=function(e,t,r){for(var o={},a=0,i=t.joints;a<i.length;a++){var s=i[a],l=n._GetProperty(this._gltf.nodes,s);if(!l)throw new Error(e+": Failed to find joint "+s);this._loadBone(l,t,r,o)}},n.prototype._loadBone=function(t,r,n,o){var a=o[t.index];if(a)return a;var i=r.joints.indexOf(t.index),s=e.Matrix.Identity();n&&-1!==i&&(s=e.Matrix.FromArray(n,16*i),s.invertToRef(s));var l=null;return t.index!==r.skeleton&&t.parent&&t.parent!==this._rootNode&&(l=this._loadBone(t.parent,r,n,o),s.multiplyToRef(l.getInvertedAbsoluteTransform(),s)),a=this._createBone(t,r,l,this._getNodeMatrix(t),s,i),o[t.index]=a,a},n.prototype._getNodeMatrix=function(t){return t.matrix?e.Matrix.FromArray(t.matrix):e.Matrix.Compose(t.scale?e.Vector3.FromArray(t.scale):e.Vector3.One(),t.rotation?e.Quaternion.FromArray(t.rotation):e.Quaternion.Identity(),t.translation?e.Vector3.FromArray(t.translation):e.Vector3.Zero())},n.prototype._traverseNodes=function(e,t,r,o){void 0===o&&(o=null);for(var a=0,i=t;a<i.length;a++){var s=i[a],l=n._GetProperty(this._gltf.nodes,s);if(!l)throw new Error(e+": Failed to find node "+s);this._traverseNode(e,l,r,o)}},n.prototype._traverseNode=function(e,r,n,o){void 0===o&&(o=null),t.GLTFLoaderExtension.TraverseNode(this,e,r,n,o)||n(r,o)&&r.children&&this._traverseNodes(e,r.children,n,r)},n.prototype._loadAnimations=function(){var e=this._gltf.animations;if(e)for(var t=0;t<e.length;t++){var r=e[t];this._loadAnimation("#/animations/"+t,r)}},n.prototype._loadAnimation=function(e,t){t.targets=[];for(var r=0;r<t.channels.length;r++){var o=n._GetProperty(t.channels,r);if(!o)throw new Error(e+": Failed to find channel "+r);var a=n._GetProperty(t.samplers,o.sampler);if(!a)throw new Error(e+": Failed to find sampler "+o.sampler);this._loadAnimationChannel(t,e+"/channels/"+r,o,e+"/samplers/"+o.sampler,a)}},n.prototype._loadAnimationChannel=function(t,r,o,a,i){var s=n._GetProperty(this._gltf.nodes,o.target.node)
  103301. ;if(!s)throw new Error(r+": Failed to find target node "+o.target.node);var l,u;switch(o.target.path){case"translation":l="position",u=e.Animation.ANIMATIONTYPE_VECTOR3;break;case"rotation":l="rotationQuaternion",u=e.Animation.ANIMATIONTYPE_QUATERNION;break;case"scale":l="scaling",u=e.Animation.ANIMATIONTYPE_VECTOR3;break;case"weights":l="influence",u=e.Animation.ANIMATIONTYPE_FLOAT;break;default:throw new Error(r+": Invalid target path "+o.target.path)}var c,f,d=function(){if(c&&f){var r,n=0;switch(l){case"position":r=function(){var t=e.Vector3.FromArray(f,n);return n+=3,t};break;case"rotationQuaternion":r=function(){var t=e.Quaternion.FromArray(f,n);return n+=4,t};break;case"scaling":r=function(){var t=e.Vector3.FromArray(f,n);return n+=3,t};break;case"influence":r=function(){for(var e=s.babylonMesh.morphTargetManager.numTargets,t=new Array(e),r=0;r<e;r++)t[r]=f[n++];return t}}var o;switch(i.interpolation){case"LINEAR":o=function(e){return{frame:c[e],value:r()}};break;case"CUBICSPLINE":o=function(e){return{frame:c[e],inTangent:r(),value:r(),outTangent:r()}};break;default:throw new Error(a+": Invalid interpolation "+i.interpolation)}for(var d=new Array(c.length),h=0;h<c.length;h++)d[h]=o(h);if("influence"===l)for(var p=s.babylonMesh.morphTargetManager,m=0;m<p.numTargets;m++)!(function(r){var n=p.getTarget(r),o=(t.name||"anim"+t.index)+"_"+r,a=new e.Animation(o,l,1,u);a.setKeys(d.map((function(e){return{frame:e.frame,inTangent:e.inTangent?e.inTangent[r]:void 0,value:e.value[r],outTangent:e.outTangent?e.outTangent[r]:void 0}}))),n.animations.push(a),t.targets.push(n)})(m);else{var E=t.name||"anim"+t.index,T=new e.Animation(E,l,1,u);T.setKeys(d);for(var _=0,A=s.babylonAnimationTargets;_<A.length;_++){var y=A[_];y.animations.push(T.clone()),t.targets.push(y)}}}},h=n._GetProperty(this._gltf.accessors,i.input);if(!h)throw new Error(a+": Failed to find input accessor "+i.input);this._loadAccessorAsync("#/accessors/"+h.index,h,(function(e){c=e,d()}));var p=n._GetProperty(this._gltf.accessors,i.output);if(!p)throw new Error(a+": Failed to find output accessor "+i.output);this._loadAccessorAsync("#/accessors/"+p.index,p,(function(e){f=e,d()}))},n.prototype._loadBufferAsync=function(r,n,o){var a=this;if(this._addPendingData(n),n.loadedData)o(n.loadedData),this._removePendingData(n);else if(n.loadedObservable)n.loadedObservable.add((function(e){o(e.loadedData),a._removePendingData(e)}));else{if(!n.uri)throw new Error(r+": Uri is missing");if(t.GLTFUtils.IsBase64(n.uri)){var i=t.GLTFUtils.DecodeBase64(n.uri);n.loadedData=new Uint8Array(i),o(n.loadedData),this._removePendingData(n)}else n.loadedObservable=new e.Observable,n.loadedObservable.add((function(e){o(e.loadedData),a._removePendingData(e)})),this._loadUri(r,n.uri,(function(e){n.loadedData=e,n.loadedObservable.notifyObservers(n),n.loadedObservable=void 0}))}},n.prototype._loadBufferViewAsync=function(e,t,r){var o=n._GetProperty(this._gltf.buffers,t.buffer);if(!o)throw new Error(e+": Failed to find buffer "+t.buffer);this._loadBufferAsync("#/buffers/"+o.index,o,(function(n){var o;try{o=new Uint8Array(n.buffer,n.byteOffset+(t.byteOffset||0),t.byteLength)}catch(t){throw new Error(e+": "+t.message)}r(o)}))},n.prototype._loadAccessorAsync=function(e,r,o){var a=this;if(r.sparse)throw new Error(e+": Sparse accessors are not currently supported");var i=n._GetProperty(this._gltf.bufferViews,r.bufferView);if(!i)throw new Error(e+": Failed to find buffer view "+r.bufferView);this._loadBufferViewAsync("#/bufferViews/"+i.index,i,(function(s){var l=n._GetNumComponents(r.type);if(0===l)throw new Error(e+": Invalid type "+r.type);var u,c=r.byteOffset||0,f=i.byteStride;try{switch(r.componentType){case t.EComponentType.BYTE:u=a._buildArrayBuffer(Float32Array,s,c,r.count,l,f);break;case t.EComponentType.UNSIGNED_BYTE:u=a._buildArrayBuffer(Uint8Array,s,c,r.count,l,f);break;case t.EComponentType.SHORT:u=a._buildArrayBuffer(Int16Array,s,c,r.count,l,f);break;case t.EComponentType.UNSIGNED_SHORT:u=a._buildArrayBuffer(Uint16Array,s,c,r.count,l,f);break;case t.EComponentType.UNSIGNED_INT:u=a._buildArrayBuffer(Uint32Array,s,c,r.count,l,f);break;case t.EComponentType.FLOAT:u=a._buildArrayBuffer(Float32Array,s,c,r.count,l,f);break;default:throw new Error(e+": Invalid component type "+r.componentType)}}catch(t){throw new Error(e+": "+t)}o(u)}))},n.prototype._buildArrayBuffer=function(e,t,r,n,o,a){r+=t.byteOffset;var i=n*o;if(null==a||a===o*e.BYTES_PER_ELEMENT)return new e(t.buffer,r,i);for(var s=a/e.BYTES_PER_ELEMENT,l=new e(t.buffer,r,s*n),u=new e(i),c=0,f=0;f<i;){for(var d=0;d<o;d++)u[f]=l[c+d],f++;c+=s}return u},n.prototype._addPendingData=function(e){this._renderReady||this._renderPendingCount++,this._addLoaderPendingData(e)},n.prototype._removePendingData=function(e){this._renderReady||0==--this._renderPendingCount&&(this._renderReady=!0,this._onRenderReady()),this._removeLoaderPendingData(e)},n.prototype._addLoaderPendingData=function(e){this._loaderPendingCount++;for(var t=0,r=this._loaderTrackers;t<r.length;t++){r[t]._addPendingData(e)}},n.prototype._removeLoaderPendingData=function(e){for(var t=0,r=this._loaderTrackers;t<r.length;t++){r[t]._removePendingData(e)}0==--this._loaderPendingCount&&this._onComplete()},n.prototype._whenAction=function(e,t){var n=this,o=new r(function(){n._loaderTrackers.splice(n._loaderTrackers.indexOf(o),1),t()});this._loaderTrackers.push(o),this._addLoaderPendingData(o),e(),this._removeLoaderPendingData(o)},n.prototype._getDefaultMaterial=function(){if(!this._defaultMaterial){var t="__gltf_default",r=this._babylonScene.getMaterialByName(t);r||(r=new e.PBRMaterial(t,this._babylonScene),r.sideOrientation=e.Material.CounterClockWiseSideOrientation,r.metallic=1,r.roughness=1),this._defaultMaterial=r}return this._defaultMaterial},n.prototype._loadMaterialMetallicRoughnessProperties=function(t,r){var o=r.babylonMaterial;o.metallic=1,o.roughness=1;var a=r.pbrMetallicRoughness;if(a){if(o.albedoColor=a.baseColorFactor?e.Color3.FromArray(a.baseColorFactor):new e.Color3(1,1,1),o.metallic=null==a.metallicFactor?1:a.metallicFactor,o.roughness=null==a.roughnessFactor?1:a.roughnessFactor,a.baseColorTexture){var i=n._GetProperty(this._gltf.textures,a.baseColorTexture.index);if(!i)throw new Error(t+": Failed to find base color texture "+a.baseColorTexture.index);o.albedoTexture=this._loadTexture("#/textures/"+i.index,i,a.baseColorTexture.texCoord)}if(a.metallicRoughnessTexture){var i=n._GetProperty(this._gltf.textures,a.metallicRoughnessTexture.index);if(!i)throw new Error(t+": Failed to find metallic roughness texture "+a.metallicRoughnessTexture.index);o.metallicTexture=this._loadTexture("#/textures/"+i.index,i,a.metallicRoughnessTexture.texCoord),o.useMetallnessFromMetallicTextureBlue=!0,o.useRoughnessFromMetallicTextureGreen=!0,o.useRoughnessFromMetallicTextureAlpha=!1}this._loadMaterialAlphaProperties(t,r,a.baseColorFactor)}},n.prototype._loadMaterial=function(e,r,n){if(r.babylonMaterial)return void n(r.babylonMaterial,!1);t.GLTFLoaderExtension.LoadMaterial(this,e,r,n)||(this._createPbrMaterial(r),this._loadMaterialBaseProperties(e,r),this._loadMaterialMetallicRoughnessProperties(e,r),n(r.babylonMaterial,!0))},n.prototype._createPbrMaterial=function(t){var r=new e.PBRMaterial(t.name||"mat"+t.index,this._babylonScene);r.sideOrientation=e.Material.CounterClockWiseSideOrientation,t.babylonMaterial=r},n.prototype._loadMaterialBaseProperties=function(t,r){var o=r.babylonMaterial;if(o.emissiveColor=r.emissiveFactor?e.Color3.FromArray(r.emissiveFactor):new e.Color3(0,0,0),r.doubleSided&&(o.backFaceCulling=!1,o.twoSidedLighting=!0),r.normalTexture){var a=n._GetProperty(this._gltf.textures,r.normalTexture.index);if(!a)throw new Error(t+": Failed to find normal texture "+r.normalTexture.index);o.bumpTexture=this._loadTexture("#/textures/"+a.index,a,r.normalTexture.texCoord),o.invertNormalMapX=!this._babylonScene.useRightHandedSystem,o.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=r.normalTexture.scale&&(o.bumpTexture.level=r.normalTexture.scale)}if(r.occlusionTexture){var a=n._GetProperty(this._gltf.textures,r.occlusionTexture.index);if(!a)throw new Error(t+": Failed to find occlusion texture "+r.occlusionTexture.index);o.ambientTexture=this._loadTexture("#/textures/"+a.index,a,r.occlusionTexture.texCoord),o.useAmbientInGrayScale=!0,null!=r.occlusionTexture.strength&&(o.ambientTextureStrength=r.occlusionTexture.strength)}if(r.emissiveTexture){var a=n._GetProperty(this._gltf.textures,r.emissiveTexture.index);if(!a)throw new Error(t+": Failed to find emissive texture "+r.emissiveTexture.index);o.emissiveTexture=this._loadTexture("#/textures/"+a.index,a,r.emissiveTexture.texCoord)}},n.prototype._loadMaterialAlphaProperties=function(t,r,n){var o=r.babylonMaterial;switch(r.alphaMode||"OPAQUE"){case"OPAQUE":o.transparencyMode=e.PBRMaterial.PBRMATERIAL_OPAQUE;break;case"MASK":o.transparencyMode=e.PBRMaterial.PBRMATERIAL_ALPHATEST,o.alphaCutOff=null==r.alphaCutoff?.5:r.alphaCutoff,n&&(0==n[3]?o.alphaCutOff=1:o.alphaCutOff/=n[3]),o.albedoTexture&&(o.albedoTexture.hasAlpha=!0);break;case"BLEND":o.transparencyMode=e.PBRMaterial.PBRMATERIAL_ALPHABLEND,n&&(o.alpha=n[3]),o.albedoTexture&&(o.albedoTexture.hasAlpha=!0,o.useAlphaFromAlbedoTexture=!0);break;default:throw new Error(t+": Invalid alpha mode "+r.alphaMode)}},n.prototype._loadTexture=function(r,o,a){var i=this,s=null==o.sampler?{}:n._GetProperty(this._gltf.samplers,o.sampler);if(!s)throw new Error(r+": Failed to find sampler "+o.sampler);var l=s.minFilter===t.ETextureMinFilter.NEAREST||s.minFilter===t.ETextureMinFilter.LINEAR,u=n._GetTextureSamplingMode(s.magFilter,s.minFilter);this._addPendingData(o);var c=new e.Texture(null,this._babylonScene,l,!1,u,function(){i._tryCatchOnError((function(){i._removePendingData(o)}))},function(e){i._tryCatchOnError((function(){throw new Error(r+": "+e)}))});if(o.url)c.updateURL(o.url);else if(o.dataReadyObservable)o.dataReadyObservable.add((function(e){c.updateURL(e.url)}));else{o.dataReadyObservable=new e.Observable,o.dataReadyObservable.add((function(e){c.updateURL(e.url)}));var f=n._GetProperty(this._gltf.images,o.source);if(!f)throw new Error(r+": Failed to find source "+o.source);this._loadImage("#/images/"+f.index,f,(function(e){o.url=URL.createObjectURL(new Blob([e],{type:f.mimeType})),o.dataReadyObservable.notifyObservers(o),o.dataReadyObservable=void 0}))}return c.coordinatesIndex=a||0,c.wrapU=n._GetTextureWrapMode(s.wrapS),c.wrapV=n._GetTextureWrapMode(s.wrapT),c.name=o.name||"texture"+o.index,this._parent.onTextureLoaded&&this._parent.onTextureLoaded(c),c},n.prototype._loadImage=function(e,r,o){if(r.uri)t.GLTFUtils.IsBase64(r.uri)?o(new Uint8Array(t.GLTFUtils.DecodeBase64(r.uri))):this._loadUri(e,r.uri,o);else{var a=n._GetProperty(this._gltf.bufferViews,r.bufferView);if(!a)throw new Error(e+": Failed to find buffer view "+r.bufferView);this._loadBufferViewAsync("#/bufferViews/"+a.index,a,o)}},n.prototype._loadUri=function(r,n,o){var a=this;if(!t.GLTFUtils.ValidateUri(n))throw new Error(r+": Uri '"+n+"' is invalid");var i=e.Tools.LoadFile(this._rootUrl+n,(function(e){a._tryCatchOnError((function(){o(new Uint8Array(e))}))}),(function(e){a._tryCatchOnError((function(){a._onProgress(e)}))}),this._babylonScene.database,!0,(function(e){a._tryCatchOnError((function(){throw new Error(r+": Failed to load '"+n+"'"+(e?": "+e.status+" "+e.statusText:""))}))}));i&&this._requests.push(i)},n.prototype._tryCatchOnError=function(t){if(!this._disposed)try{t()}catch(t){e.Tools.Error("glTF Loader: "+t.message),this._errorCallback&&this._errorCallback(t.message),this.dispose()}},n._AssignIndices=function(e){if(e)for(var t=0;t<e.length;t++)e[t].index=t},n._GetProperty=function(e,t){return e&&void 0!=t&&e[t]?e[t]:null},n._GetTextureWrapMode=function(r){switch(r=void 0==r?t.ETextureWrapMode.REPEAT:r){case t.ETextureWrapMode.CLAMP_TO_EDGE:return e.Texture.CLAMP_ADDRESSMODE;case t.ETextureWrapMode.MIRRORED_REPEAT:return e.Texture.MIRROR_ADDRESSMODE;case t.ETextureWrapMode.REPEAT:return e.Texture.WRAP_ADDRESSMODE;default:return e.Tools.Warn("Invalid texture wrap mode ("+r+")"),e.Texture.WRAP_ADDRESSMODE}},n._GetTextureSamplingMode=function(r,n){if(r=void 0==r?t.ETextureMagFilter.LINEAR:r,n=void 0==n?t.ETextureMinFilter.LINEAR_MIPMAP_LINEAR:n,r===t.ETextureMagFilter.LINEAR)switch(n){case t.ETextureMinFilter.NEAREST:return e.Texture.LINEAR_NEAREST;case t.ETextureMinFilter.LINEAR:return e.Texture.LINEAR_LINEAR;case t.ETextureMinFilter.NEAREST_MIPMAP_NEAREST:return e.Texture.LINEAR_NEAREST_MIPNEAREST;case t.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:return e.Texture.LINEAR_LINEAR_MIPNEAREST;case t.ETextureMinFilter.NEAREST_MIPMAP_LINEAR:return e.Texture.LINEAR_NEAREST_MIPLINEAR;case t.ETextureMinFilter.LINEAR_MIPMAP_LINEAR:return e.Texture.LINEAR_LINEAR_MIPLINEAR;default:return e.Tools.Warn("Invalid texture minification filter ("+n+")"),e.Texture.LINEAR_LINEAR_MIPLINEAR}else switch(r!==t.ETextureMagFilter.NEAREST&&e.Tools.Warn("Invalid texture magnification filter ("+r+")"),n){case t.ETextureMinFilter.NEAREST:return e.Texture.NEAREST_NEAREST;case t.ETextureMinFilter.LINEAR:return e.Texture.NEAREST_LINEAR;case t.ETextureMinFilter.NEAREST_MIPMAP_NEAREST:return e.Texture.NEAREST_NEAREST_MIPNEAREST;case t.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:return e.Texture.NEAREST_LINEAR_MIPNEAREST;case t.ETextureMinFilter.NEAREST_MIPMAP_LINEAR:return e.Texture.NEAREST_NEAREST_MIPLINEAR;case t.ETextureMinFilter.LINEAR_MIPMAP_LINEAR:return e.Texture.NEAREST_LINEAR_MIPLINEAR;default:return e.Tools.Warn("Invalid texture minification filter ("+n+")"),e.Texture.NEAREST_NEAREST_MIPNEAREST}},n._GetNumComponents=function(e){switch(e){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}return 0},n.Extensions={},n})();t.GLTFLoader=n,e.GLTFFileLoader.CreateGLTFLoaderV2=function(e){return new n(e)}})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){var t=(function(){function e(){}return e.IsBase64=function(e){return!(e.length<5)&&"data:"===e.substr(0,5)},e.DecodeBase64=function(e){for(var t=atob(e.split(",")[1]),r=t.length,n=new Uint8Array(new ArrayBuffer(r)),o=0;o<r;o++)n[o]=t.charCodeAt(o);return n.buffer},e.ValidateUri=function(e){return-1===e.indexOf("..")},e})();e.GLTFUtils=t})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){var t=(function(){function e(){this.enabled=!0}return e.prototype._traverseNode=function(e,t,r,n,o){return!1},e.prototype._loadNode=function(e,t,r){return!1},e.prototype._loadMaterial=function(e,t,r,n){return!1},e.prototype._loadExtension=function(e,t,r){var n=this;if(!t.extensions)return!1;var o=t.extensions[this.name];return!!o&&(t.extensions[this.name]=void 0,r(e+"extensions/"+this.name,o,(function(){t.extensions[n.name]=o})),!0)},e.TraverseNode=function(e,t,r,n,o){return this._ApplyExtensions((function(a){return a._traverseNode(e,t,r,n,o)}))},e.LoadNode=function(e,t,r){return this._ApplyExtensions((function(n){return n._loadNode(e,t,r)}))},e.LoadMaterial=function(e,t,r,n){return this._ApplyExtensions((function(o){return o._loadMaterial(e,t,r,n)}))},e._ApplyExtensions=function(t){var r=e._Extensions;if(!r)return!1;for(var n=0,o=r;n<o.length;n++){var a=o[n];if(a.enabled&&t(a))return!0}return!1},e._Extensions=[],e})();e.GLTFLoaderExtension=t})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){!(function(r){var n=(function(r){function n(){return null!==r&&r.apply(this,arguments)||this}return __extends(n,r),Object.defineProperty(n.prototype,"name",{get:function(){return"MSFT_lod"},enumerable:!0,configurable:!0}),n.prototype._traverseNode=function(e,r,n,o,a){return this._loadExtension(r,n,(function(r,i,s){for(var l=i.ids.length-1;l>=0;l--){var u=t.GLTFLoader._GetProperty(e._gltf.nodes,i.ids[l]);if(!u)throw new Error(r+": Failed to find node "+i.ids[l]);e._traverseNode(r,u,o,a)}e._traverseNode(r,n,o,a),s()}))},n.prototype._loadNode=function(e,r,n){var o=this;return this._loadExtension(r,n,(function(r,a,i){for(var s=[n],l=0,u=a.ids;l<u.length;l++){var c=u[l],f=t.GLTFLoader._GetProperty(e._gltf.nodes,c);if(!f)throw new Error(r+": Failed to find node "+c);s.push(f)}e._addLoaderPendingData(n),o._loadNodeLOD(e,r,s,s.length-1,(function(){e._removeLoaderPendingData(n),i()}))}))},n.prototype._loadNodeLOD=function(e,t,r,o,a){var i=this;e._whenAction((function(){e._loadNode(t,r[o])}),(function(){if(o!==r.length-1){r[o+1].babylonMesh.setEnabled(!1)}if(0===o)return void a();setTimeout((function(){e._tryCatchOnError((function(){i._loadNodeLOD(e,t,r,o-1,a)}))}),n.MinimalLODDelay)}))},n.prototype._loadMaterial=function(e,r,n,o){var a=this;return this._loadExtension(r,n,(function(r,i,s){for(var l=[n],u=0,c=i.ids;u<c.length;u++){var f=c[u],d=t.GLTFLoader._GetProperty(e._gltf.materials,f);if(!d)throw new Error(r+": Failed to find material "+f);l.push(d)}e._addLoaderPendingData(n),a._loadMaterialLOD(e,r,l,l.length-1,o,(function(){e._removeLoaderPendingData(n),s()}))}))},n.prototype._loadMaterialLOD=function(t,r,o,a,i,s){var l=this;t._loadMaterial(r,o[a],(function(u,c){if(i(u,c),0===a)return void s();t._executeWhenRenderReady((function(){e.BaseTexture.WhenAllReady(u.getActiveTextures(),(function(){setTimeout((function(){t._tryCatchOnError((function(){l._loadMaterialLOD(t,r,o,a-1,i,s)}))}),n.MinimalLODDelay)}))}))}))},n.MinimalLODDelay=250,n})(t.GLTFLoaderExtension);r.MSFTLOD=n,t.GLTFLoader.RegisterExtension(new n)})(t.Extensions||(t.Extensions={}))})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){!(function(r){var n=(function(r){function n(){return null!==r&&r.apply(this,arguments)||this}return __extends(n,r),Object.defineProperty(n.prototype,"name",{get:function(){return"KHR_materials_pbrSpecularGlossiness"},enumerable:!0,configurable:!0}),n.prototype._loadMaterial=function(e,t,r,n){var o=this;return this._loadExtension(t,r,(function(t,a,i){e._createPbrMaterial(r),e._loadMaterialBaseProperties(t,r),o._loadSpecularGlossinessProperties(e,t,r,a),n(r.babylonMaterial,!0)}))},n.prototype._loadSpecularGlossinessProperties=function(r,n,o,a){var i=o.babylonMaterial;if(i.albedoColor=a.diffuseFactor?e.Color3.FromArray(a.diffuseFactor):new e.Color3(1,1,1),i.reflectivityColor=a.specularFactor?e.Color3.FromArray(a.specularFactor):new e.Color3(1,1,1),i.microSurface=null==a.glossinessFactor?1:a.glossinessFactor,a.diffuseTexture){var s=t.GLTFLoader._GetProperty(r._gltf.textures,a.diffuseTexture.index);if(!s)throw new Error(n+": Failed to find diffuse texture "+a.diffuseTexture.index);i.albedoTexture=r._loadTexture("textures["+s.index+"]",s,a.diffuseTexture.texCoord)}if(a.specularGlossinessTexture){var s=t.GLTFLoader._GetProperty(r._gltf.textures,a.specularGlossinessTexture.index);if(!s)throw new Error(n+": Failed to find diffuse texture "+a.specularGlossinessTexture.index);i.reflectivityTexture=r._loadTexture("textures["+s.index+"]",s,a.specularGlossinessTexture.texCoord),i.reflectivityTexture.hasAlpha=!0,i.useMicroSurfaceFromReflectivityMapAlpha=!0}r._loadMaterialAlphaProperties(n,o,a.diffuseFactor)},n})(t.GLTFLoaderExtension);r.KHRMaterialsPbrSpecularGlossiness=n,t.GLTFLoader.RegisterExtension(new n)})(t.Extensions||(t.Extensions={}))})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={})),(function(e,t){var r=t();e&&e.BABYLON||( true?module.exports=r:"function"==typeof define&&define.amd?define(["BJSLoaders"],t):"object"==typeof exports?exports.BJSLoaders=r:e.BABYLON=r)})(this,(function(){return BABYLON}));
  103302. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  103303. /***/ }),
  103304. /* 31 */
  103305. /***/ (function(module, exports, __webpack_require__) {
  103306. /* WEBPACK VAR INJECTION */(function(global) {var globalObject="undefined"!=typeof global?global:"undefined"!=typeof window?window:this,babylonDependency=globalObject&&globalObject.BABYLON||BABYLON||"undefined"!="function"&&__webpack_require__(0),BABYLON=babylonDependency,__decorate=this&&this.__decorate||function(e,i,t,n){var r,o=arguments.length,a=o<3?i:null===n?n=Object.getOwnPropertyDescriptor(i,t):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,i,t,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(i,t,a):r(i,t))||a);return o>3&&a&&Object.defineProperty(i,t,a),a},__extends=this&&this.__extends||(function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var t in i)i.hasOwnProperty(t)&&(e[t]=i[t])};return function(i,t){function n(){this.constructor=i}e(i,t),i.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}})(),BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.CLIPPLANE=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(e,i){return t.call(this,e,i)||this}return __extends(n,t),n.prototype.needAlphaBlending=function(){return!0},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},Object.defineProperty(n.prototype,"activeLight",{get:function(){return this._activeLight},set:function(e){this._activeLight=e},enumerable:!0,configurable:!0}),n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(this._activeLight)for(var f=0,l=t._lightSources;f<l.length;f++){var u=l[f];if(u.shadowEnabled){if(this._activeLight===u)break;var c=t._lightSources.indexOf(this._activeLight);-1!==c&&(t._lightSources.splice(c,1),t._lightSources.splice(0,0,this._activeLight));break}}if(e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,1),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!1,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var d=new e.EffectFallbacks;o.FOG&&d.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,d,1),o.NUM_BONE_INFLUENCERS>0&&d.addCPUSkinningFallback(0,t);var p=[e.VertexBuffer.PositionKind];o.NORMAL&&p.push(e.VertexBuffer.NormalKind),e.MaterialHelper.PrepareAttributesForBones(p,t,o,d),e.MaterialHelper.PrepareAttributesForInstances(p,o);var h=o.toString(),m=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","mBones","vClipPlane"],v=new Array,_=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:m,uniformBuffersNames:_,samplers:v,defines:o,maxSimultaneousLights:1}),n.setEffect(a.getEngine().createEffect("shadowOnly",{attributes:p,uniformsNames:m,uniformBuffersNames:_,samplers:v,defines:h,fallbacks:d,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),e.MaterialHelper.BindEyePosition(a,r)),r.lightsEnabled&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,1),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.ShadowOnlyMaterial",i},n.prototype.getClassName=function(){return"ShadowOnlyMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},n})(e.PushMaterial);e.ShadowOnlyMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.shadowOnlyVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.shadowOnlyPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform float alpha;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0..1]\n\nvec4 color=vec4(0.,0.,0.,(1.0-clamp(shadow,0.,1.))*alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.LIGHT0=!1,i.LIGHT1=!1,i.LIGHT2=!1,i.LIGHT3=!1,i.SPOTLIGHT0=!1,i.SPOTLIGHT1=!1,i.SPOTLIGHT2=!1,i.SPOTLIGHT3=!1,i.HEMILIGHT0=!1,i.HEMILIGHT1=!1,i.HEMILIGHT2=!1,i.HEMILIGHT3=!1,i.DIRLIGHT0=!1,i.DIRLIGHT1=!1,i.DIRLIGHT2=!1,i.DIRLIGHT3=!1,i.POINTLIGHT0=!1,i.POINTLIGHT1=!1,i.POINTLIGHT2=!1,i.POINTLIGHT3=!1,i.SHADOW0=!1,i.SHADOW1=!1,i.SHADOW2=!1,i.SHADOW3=!1,i.SHADOWS=!1,i.SHADOWESM0=!1,i.SHADOWESM1=!1,i.SHADOWESM2=!1,i.SHADOWESM3=!1,i.SHADOWPCF0=!1,i.SHADOWPCF1=!1,i.SHADOWPCF2=!1,i.SHADOWPCF3=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r._maxSimultaneousLights=4,r.topColor=new e.Color3(1,0,0),r.topColorAlpha=1,r.bottomColor=new e.Color3(0,0,1),r.bottomColorAlpha=1,r.offset=0,r.smoothness=1,r.disableLighting=!1,r._scaledDiffuse=new e.Color3,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1||this.topColorAlpha<1||this.bottomColorAlpha<1},n.prototype.needAlphaTesting=function(){return!0},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!1,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","topColor","bottomColor","offset","smoothness"],d=["diffuseSampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:4}),n.setEffect(a.getEngine().createEffect("gradient",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,a),this._mustRebind(r,a)&&(e.MaterialHelper.BindClipPlane(a,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){return[]},n.prototype.dispose=function(e){t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.GradientMaterial",i},n.prototype.getClassName=function(){return"GradientMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serializeAsColor3()],n.prototype,"topColor",void 0),__decorate([e.serialize()],n.prototype,"topColorAlpha",void 0),__decorate([e.serializeAsColor3()],n.prototype,"bottomColor",void 0),__decorate([e.serialize()],n.prototype,"bottomColorAlpha",void 0),__decorate([e.serialize()],n.prototype,"offset",void 0),__decorate([e.serialize()],n.prototype,"smoothness",void 0),__decorate([e.serialize()],n.prototype,"disableLighting",void 0),n})(e.PushMaterial);e.GradientMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.gradientVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\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#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.gradientPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nuniform vec4 topColor;\nuniform vec4 bottomColor;\nuniform float offset;\nuniform float smoothness;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\nfloat h=normalize(vPositionW).y+offset;\nfloat mysmoothness=clamp(smoothness,0.01,max(smoothness,10.));\nvec4 baseColor=mix(bottomColor,topColor,max(pow(max(h,0.0),mysmoothness),0.0));\n\nvec3 diffuseColor=baseColor.rgb;\n\nfloat alpha=baseColor.a;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.LIGHT0=!1,i.LIGHT1=!1,i.LIGHT2=!1,i.LIGHT3=!1,i.SPOTLIGHT0=!1,i.SPOTLIGHT1=!1,i.SPOTLIGHT2=!1,i.SPOTLIGHT3=!1,i.HEMILIGHT0=!1,i.HEMILIGHT1=!1,i.HEMILIGHT2=!1,i.HEMILIGHT3=!1,i.DIRLIGHT0=!1,i.DIRLIGHT1=!1,i.DIRLIGHT2=!1,i.DIRLIGHT3=!1,i.POINTLIGHT0=!1,i.POINTLIGHT1=!1,i.POINTLIGHT2=!1,i.POINTLIGHT3=!1,i.SHADOW0=!1,i.SHADOW1=!1,i.SHADOW2=!1,i.SHADOW3=!1,i.SHADOWS=!1,i.SHADOWESM0=!1,i.SHADOWESM1=!1,i.SHADOWESM2=!1,i.SHADOWESM3=!1,i.SHADOWPCF0=!1,i.SHADOWPCF1=!1,i.SHADOWPCF2=!1,i.SHADOWPCF3=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix"],d=["diffuseSampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:4}),n.setEffect(a.getEngine().createEffect("normal",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.diffuseTexture===e},n.prototype.dispose=function(e){this.diffuseTexture&&this.diffuseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.NormalMaterial",i},n.prototype.getClassName=function(){return"NormalMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.NormalMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.normalVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\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#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.normalPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\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#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef NORMAL\nbaseColor=mix(baseColor,vec4(vNormalW,1.0),0.5);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.LIGHT0=!1,i.LIGHT1=!1,i.LIGHT2=!1,i.LIGHT3=!1,i.SPOTLIGHT0=!1,i.SPOTLIGHT1=!1,i.SPOTLIGHT2=!1,i.SPOTLIGHT3=!1,i.HEMILIGHT0=!1,i.HEMILIGHT1=!1,i.HEMILIGHT2=!1,i.HEMILIGHT3=!1,i.DIRLIGHT0=!1,i.DIRLIGHT1=!1,i.DIRLIGHT2=!1,i.DIRLIGHT3=!1,i.POINTLIGHT0=!1,i.POINTLIGHT1=!1,i.POINTLIGHT2=!1,i.POINTLIGHT3=!1,i.SHADOW0=!1,i.SHADOW1=!1,i.SHADOW2=!1,i.SHADOW3=!1,i.SHADOWS=!1,i.SHADOWESM0=!1,i.SHADOWESM1=!1,i.SHADOWESM2=!1,i.SHADOWESM3=!1,i.SHADOWPCF0=!1,i.SHADOWPCF1=!1,i.SHADOWPCF2=!1,i.SHADOWPCF3=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.speed=1,r.movingSpeed=1,r.lowFrequencySpeed=1,r.fogDensity=.15,r._lastTime=0,r.diffuseColor=new e.Color3(1,1,1),r._disableLighting=!1,r._maxSimultaneousLights=4,r._scaledDiffuse=new e.Color3,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"],d=["diffuseSampler","noiseTexture"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("lava",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._lastTime+=r.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=e.Color3.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.diffuseTexture===e},n.prototype.dispose=function(e){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.LavaMaterial",i},n.prototype.getClassName=function(){return"LavaMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture()],n.prototype,"noiseTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"fogColor",void 0),__decorate([e.serialize()],n.prototype,"speed",void 0),__decorate([e.serialize()],n.prototype,"movingSpeed",void 0),__decorate([e.serialize()],n.prototype,"lowFrequencySpeed",void 0),__decorate([e.serialize()],n.prototype,"fogDensity",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),
  103307. __decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.LavaMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.lavaVertexShader="precision highp float;\n\nuniform float time;\nuniform float lowFrequencySpeed;\n\nvarying float noise;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n\n\nvec3 mod289(vec3 x)\n{\nreturn x-floor(x*(1.0/289.0))*289.0;\n}\nvec4 mod289(vec4 x)\n{\nreturn x-floor(x*(1.0/289.0))*289.0;\n}\nvec4 permute(vec4 x)\n{\nreturn mod289(((x*34.0)+1.0)*x);\n}\nvec4 taylorInvSqrt(vec4 r)\n{\nreturn 1.79284291400159-0.85373472095314*r;\n}\nvec3 fade(vec3 t) {\nreturn t*t*t*(t*(t*6.0-15.0)+10.0);\n}\n\nfloat pnoise(vec3 P,vec3 rep)\n{\nvec3 Pi0=mod(floor(P),rep); \nvec3 Pi1=mod(Pi0+vec3(1.0),rep); \nPi0=mod289(Pi0);\nPi1=mod289(Pi1);\nvec3 Pf0=fract(P); \nvec3 Pf1=Pf0-vec3(1.0); \nvec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);\nvec4 iy=vec4(Pi0.yy,Pi1.yy);\nvec4 iz0=Pi0.zzzz;\nvec4 iz1=Pi1.zzzz;\nvec4 ixy=permute(permute(ix)+iy);\nvec4 ixy0=permute(ixy+iz0);\nvec4 ixy1=permute(ixy+iz1);\nvec4 gx0=ixy0*(1.0/7.0);\nvec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;\ngx0=fract(gx0);\nvec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);\nvec4 sz0=step(gz0,vec4(0.0));\ngx0-=sz0*(step(0.0,gx0)-0.5);\ngy0-=sz0*(step(0.0,gy0)-0.5);\nvec4 gx1=ixy1*(1.0/7.0);\nvec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;\ngx1=fract(gx1);\nvec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);\nvec4 sz1=step(gz1,vec4(0.0));\ngx1-=sz1*(step(0.0,gx1)-0.5);\ngy1-=sz1*(step(0.0,gy1)-0.5);\nvec3 g000=vec3(gx0.x,gy0.x,gz0.x);\nvec3 g100=vec3(gx0.y,gy0.y,gz0.y);\nvec3 g010=vec3(gx0.z,gy0.z,gz0.z);\nvec3 g110=vec3(gx0.w,gy0.w,gz0.w);\nvec3 g001=vec3(gx1.x,gy1.x,gz1.x);\nvec3 g101=vec3(gx1.y,gy1.y,gz1.y);\nvec3 g011=vec3(gx1.z,gy1.z,gz1.z);\nvec3 g111=vec3(gx1.w,gy1.w,gz1.w);\nvec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));\ng000*=norm0.x;\ng010*=norm0.y;\ng100*=norm0.z;\ng110*=norm0.w;\nvec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));\ng001*=norm1.x;\ng011*=norm1.y;\ng101*=norm1.z;\ng111*=norm1.w;\nfloat n000=dot(g000,Pf0);\nfloat n100=dot(g100,vec3(Pf1.x,Pf0.yz));\nfloat n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));\nfloat n110=dot(g110,vec3(Pf1.xy,Pf0.z));\nfloat n001=dot(g001,vec3(Pf0.xy,Pf1.z));\nfloat n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));\nfloat n011=dot(g011,vec3(Pf0.x,Pf1.yz));\nfloat n111=dot(g111,Pf1);\nvec3 fade_xyz=fade(Pf0);\nvec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);\nvec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);\nfloat n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);\nreturn 2.2*n_xyz;\n}\n\nfloat turbulence( vec3 p ) {\nfloat w=100.0;\nfloat t=-.5;\nfor (float f=1.0 ; f<=10.0 ; f++ ){\nfloat power=pow( 2.0,f );\nt+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );\n}\nreturn t;\n}\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef NORMAL\n\nnoise=10.0*-.10*turbulence( .5*normal+time*1.15 );\n\nfloat b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );\n\nfloat displacement =-1.5*noise+b;\n\nvec3 newPosition=position+normal*displacement;\ngl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );\nvec4 worldPos=finalWorld*vec4(newPosition,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\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#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}",BABYLON.Effect.ShadersStore.lavaPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n\nuniform float time;\nuniform float speed;\nuniform float movingSpeed;\nuniform vec3 fogColor;\nuniform sampler2D noiseTexture;\nuniform float fogDensity;\n\nvarying float noise;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nfloat random( vec3 scale,float seed ){\nreturn fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;\n}\nvoid main(void) {\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#ifdef DIFFUSE\n\nvec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );\nvec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time*0.02;\nvec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;\nT1.x+=noiseTex.x*2.0;\nT1.y+=noiseTex.y*2.0;\nT2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;\nT2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;\nfloat p=texture2D( noiseTexture,T1*3.0 ).a;\nvec4 lavaColor=texture2D( diffuseSampler,T2*4.0);\nvec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );\nbaseColor=temp;\nfloat depth=gl_FragCoord.z*4.0;\nconst float LOG2=1.442695;\nfloat fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );\nfogFactor=1.0-clamp( fogFactor,0.0,1.0 );\nbaseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );\ndiffuseColor=baseColor.rgb;\n\n\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix"],d=["diffuseSampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("simple",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.diffuseTexture===e},n.prototype.dispose=function(e){this._diffuseTexture&&this._diffuseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.SimpleMaterial",i},n.prototype.getClassName=function(){return"SimpleMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsColor3("diffuse")],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.SimpleMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.simpleVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\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#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.simplePixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\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#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.BUMP=!1,i.REFLECTION=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.SPECULARTERM=!1,i.LOGARITHMICDEPTH=!1,i.FRESNELSEPARATE=!1,i.BUMPSUPERIMPOSE=!1,i.BUMPAFFECTSREFLECTION=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n,r){void 0===r&&(r=new e.Vector2(512,512));var o=t.call(this,i,n)||this;return o.renderTargetSize=r,o.diffuseColor=new e.Color3(1,1,1),o.specularColor=new e.Color3(0,0,0),o.specularPower=64,o._disableLighting=!1,o._maxSimultaneousLights=4,o.windForce=6,o.windDirection=new e.Vector2(0,1),o.waveHeight=.4,o.bumpHeight=.4,o._bumpSuperimpose=!1,o._fresnelSeparate=!1,o._bumpAffectsReflection=!1,o.waterColor=new e.Color3(.1,.1,.6),o.colorBlendFactor=.2,o.waterColor2=new e.Color3(.1,.1,.6),o.colorBlendFactor2=.2,o.waveLength=.1,o.waveSpeed=1,o._renderTargets=new e.SmartArray(16),o._mesh=null,o._reflectionTransform=e.Matrix.Zero(),o._lastTime=0,o._lastDeltaTime=0,o._createRenderTargets(n,r),o.getRenderTargetTextures=function(){return o._renderTargets.reset(),o._renderTargets.push(o._reflectionRTT),o._renderTargets.push(o._refractionRTT),o._renderTargets},o}return __extends(n,t),Object.defineProperty(n.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"refractionTexture",{get:function(){return this._refractionRTT},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"reflectionTexture",{get:function(){return this._reflectionRTT},enumerable:!0,configurable:!0}),n.prototype.addToRenderList=function(e){this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)},n.prototype.enableRenderTargets=function(e){var i=e?1:0;this._refractionRTT.refreshRate=i,this._reflectionRTT.refreshRate=i},n.prototype.getRenderList=function(){return this._refractionRTT.renderList},Object.defineProperty(n.prototype,"renderTargetsEnabled",{get:function(){return!(0===this._refractionRTT.refreshRate)},enumerable:!0,configurable:!0}),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled)){if(this.bumpTexture&&e.StandardMaterial.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;o._needUVs=!0,o.BUMP=!0}e.StandardMaterial.ReflectionTextureEnabled&&(o.REFLECTION=!0)}if(e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForMisc(t,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,o),o._areMiscDirty&&(this._fresnelSeparate&&(o.FRESNELSEPARATE=!0),this._bumpSuperimpose&&(o.BUMPSUPERIMPOSE=!0),this._bumpAffectsReflection&&(o.BUMPAFFECTSREFLECTION=!0)),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!0,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),this._mesh=t,o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),o.LOGARITHMICDEPTH&&f.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","vClipPlane","normalMatrix","logarithmicDepthConstant","worldReflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed"],d=["normalSampler","refractionSampler","reflectionSampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("water",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;if(a&&this._mesh){this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.bumpTexture&&e.StandardMaterial.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),e.MaterialHelper.BindLogDepth(o,this._activeEffect,r),e.StandardMaterial.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));var s=this._mesh.getWorldMatrix().multiply(this._reflectionTransform).multiply(r.getProjectionMatrix()),f=r.getEngine().getDeltaTime();f!==this._lastDeltaTime&&(this._lastDeltaTime=f,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("worldReflectionViewProjection",s),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._afterBind(t,this._activeEffect)}}},n.prototype._createRenderTargets=function(i,t){var n=this;this._refractionRTT=new e.RenderTargetTexture(name+"_refraction",{width:t.x,height:t.y},i,!1,!0),this._refractionRTT.wrapU=e.Texture.MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=e.Texture.MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0,this._reflectionRTT=new e.RenderTargetTexture(name+"_reflection",{width:t.x,height:t.y},i,!1,!0),this._reflectionRTT.wrapU=e.Texture.MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=e.Texture.MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;var r,o,a=null,s=e.Matrix.Zero();this._refractionRTT.onBeforeRender=function(){n._mesh&&(r=n._mesh.isVisible,n._mesh.isVisible=!1),a=i.clipPlane;var t=n._mesh?n._mesh.position.y:0;i.clipPlane=e.Plane.FromPositionAndNormal(new e.Vector3(0,t+.05,0),new e.Vector3(0,1,0))},this._refractionRTT.onAfterRender=function(){n._mesh&&(n._mesh.isVisible=r),i.clipPlane=a},this._reflectionRTT.onBeforeRender=function(){n._mesh&&(r=n._mesh.isVisible,n._mesh.isVisible=!1),a=i.clipPlane;var t=n._mesh?n._mesh.position.y:0;i.clipPlane=e.Plane.FromPositionAndNormal(new e.Vector3(0,t-.05,0),new e.Vector3(0,-1,0)),e.Matrix.ReflectionToRef(i.clipPlane,s),o=i.getViewMatrix(),s.multiplyToRef(o,n._reflectionTransform),i.setTransformMatrix(n._reflectionTransform,i.getProjectionMatrix()),i.getEngine().cullBackFaces=!1,i._mirroredCameraPosition=e.Vector3.TransformCoordinates(i.activeCamera.position,s)},this._reflectionRTT.onAfterRender=function(){n._mesh&&(n._mesh.isVisible=r),i.clipPlane=a,i.setTransformMatrix(o,i.getProjectionMatrix()),i.getEngine().cullBackFaces=!0,i._mirroredCameraPosition=null}},n.prototype.getAnimatables=function(){var e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._bumpTexture&&e.push(this._bumpTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this._bumpTexture===e},n.prototype.dispose=function(e){this.bumpTexture&&this.bumpTexture.dispose();var i=this.getScene().customRenderTargets.indexOf(this._refractionRTT);-1!=i&&this.getScene().customRenderTargets.splice(i,1),i=-1,i=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),-1!=i&&this.getScene().customRenderTargets.splice(i,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.WaterMaterial",i.reflectionTexture.isRenderTarget=!0,i.refractionTexture.isRenderTarget=!0,i},n.prototype.getClassName=function(){return"WaterMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},n.CreateDefaultMesh=function(i,t){return e.Mesh.CreateGround(i,512,512,32,t,!1)},__decorate([e.serializeAsTexture("bumpTexture")],n.prototype,"_bumpTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"specularColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],n.prototype,"windForce",void 0),__decorate([e.serializeAsVector2()],n.prototype,"windDirection",void 0),__decorate([e.serialize()],n.prototype,"waveHeight",void 0),__decorate([e.serialize()],n.prototype,"bumpHeight",void 0),__decorate([e.serialize("bumpSuperimpose")],n.prototype,"_bumpSuperimpose",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsMiscDirty")],n.prototype,"bumpSuperimpose",void 0),__decorate([e.serialize("fresnelSeparate")],n.prototype,"_fresnelSeparate",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsMiscDirty")],n.prototype,"fresnelSeparate",void 0),__decorate([e.serialize("bumpAffectsReflection")],n.prototype,"_bumpAffectsReflection",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsMiscDirty")],n.prototype,"bumpAffectsReflection",void 0),__decorate([e.serializeAsColor3()],n.prototype,"waterColor",void 0),__decorate([e.serialize()],n.prototype,"colorBlendFactor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"waterColor2",void 0),__decorate([e.serialize()],n.prototype,"colorBlendFactor2",void 0),__decorate([e.serialize()],n.prototype,"waveLength",void 0),__decorate([e.serialize()],n.prototype,"waveSpeed",void 0),__decorate([e.serialize()],n.prototype,"useLogarithmicDepth",null),n})(e.PushMaterial);e.WaterMaterial=t})(BABYLON||(BABYLON={})),
  103308. BABYLON.Effect.ShadersStore.waterVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform mat4 normalMatrix;\nuniform vec2 vNormalInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<logDepthDeclaration>\n\nuniform mat4 worldReflectionViewProjection;\nuniform vec2 windDirection;\nuniform float waveLength;\nuniform float time;\nuniform float windForce;\nuniform float waveHeight;\nuniform float waveSpeed;\n\nvarying vec3 vPosition;\nvarying vec3 vRefractionMapTexCoord;\nvarying vec3 vReflectionMapTexCoord;\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 BUMP\nif (vNormalInfos.x == 0.)\n{\nvNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0));\n#endif\n}\nelse\n{\nvNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0));\n#endif\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\nvec3 p=position;\nfloat newY=(sin(((p.x/0.05)+time*waveSpeed))*waveHeight*windDirection.x*5.0)\n+(cos(((p.z/0.05)+time*waveSpeed))*waveHeight*windDirection.y*5.0);\np.y+=abs(newY);\ngl_Position=viewProjection*finalWorld*vec4(p,1.0);\n#ifdef REFLECTION\nworldPos=viewProjection*finalWorld*vec4(p,1.0);\n\nvPosition=position;\nvRefractionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);\nvRefractionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);\nvRefractionMapTexCoord.z=worldPos.w;\nworldPos=worldReflectionViewProjection*vec4(position,1.0);\nvReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);\nvReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);\nvReflectionMapTexCoord.z=worldPos.w;\n#endif\n#include<logDepthVertex>\n}\n",BABYLON.Effect.ShadersStore.waterPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef BUMP\nvarying vec2 vNormalUV;\nvarying vec2 vNormalUV2;\nuniform sampler2D normalSampler;\nuniform vec2 vNormalInfos;\n#endif\nuniform sampler2D refractionSampler;\nuniform sampler2D reflectionSampler;\n\nconst float LOG2=1.442695;\nuniform vec3 cameraPosition;\nuniform vec4 waterColor;\nuniform float colorBlendFactor;\nuniform vec4 waterColor2;\nuniform float colorBlendFactor2;\nuniform float bumpHeight;\nuniform float time;\n\nvarying vec3 vRefractionMapTexCoord;\nvarying vec3 vReflectionMapTexCoord;\nvarying vec3 vPosition;\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n\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#ifdef BUMP\n#ifdef BUMPSUPERIMPOSE\nbaseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y));\n#else\nbaseColor=texture2D(normalSampler,vNormalUV);\n#endif\nvec3 bumpColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vNormalInfos.y;\n#else\nvec3 bumpColor=vec3(1.0);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec2 perturbation=bumpHeight*(baseColor.rg-0.5);\n#ifdef BUMPAFFECTSREFLECTION\nvec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));\nif (normalW.y<0.0) {\nnormalW.y=-normalW.y;\n}\n#else\nvec3 normalW=normalize(vNormalW);\n#endif\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\nvec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5);\n#endif\n#ifdef FRESNELSEPARATE\n#ifdef REFLECTION\n\nvec3 eyeVector=normalize(vEyePosition-vPosition);\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);\nvec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\nvec2 projectedReflectionTexCoords=clamp(vec2(\nvReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3,\nvReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y\n),0.0,1.0);\nvec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\nvec3 upVector=vec3(0.0,1.0,0.0);\nfloat fresnelTerm=clamp(abs(pow(dot(eyeVector,upVector),3.0)),0.05,0.65);\nfloat IfresnelTerm=1.0-fresnelTerm;\nrefractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;\nreflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;\nvec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;\nbaseColor=combinedColor;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#else \n#ifdef REFLECTION\n\nvec3 eyeVector=normalize(vEyePosition-vPosition);\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);\nvec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\nvec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);\nvec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\nvec3 upVector=vec3(0.0,1.0,0.0);\nfloat fresnelTerm=max(dot(eyeVector,upVector),0.0);\nvec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);\nbaseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#endif\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.UV1=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.BonesPerMesh=0,i.NUM_BONE_INFLUENCERS=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r.speed=1,r._scaledDiffuse=new e.Color3,r._lastTime=0,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return!1},n.prototype.needAlphaTesting=function(){return!0},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(o._areMiscDirty&&(o.POINTSIZE=this.pointsCloud||a.forcePointsCloud,o.FOG=a.fogEnabled&&t.applyFog&&a.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!1,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.UV1&&l.push(e.VertexBuffer.UVKind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString();n.setEffect(a.getEngine().createEffect("fire",{attributes:l,uniformsNames:["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","time","speed"],uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:null,maxSimultaneousLights:4,transformFeedbackVaryings:null},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene();if(n._materialDefines){var o=n.effect;if(o){if(this._activeEffect=o,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,o)){if(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),r.clipPlane){var a=r.clipPlane;this._activeEffect.setFloat4("vClipPlane",a.normal.x,a.normal.y,a.normal.z,a.d)}this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(o,r)}this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._lastTime+=r.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect)}}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._distortionTexture&&e.push(this._distortionTexture),this._opacityTexture&&e.push(this._opacityTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._diffuseTexture===e||(this._distortionTexture===e||this._opacityTexture===e))},n.prototype.getClassName=function(){return"FireMaterial"},n.prototype.dispose=function(e){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.customType="BABYLON.FireMaterial",e.diffuseColor=this.diffuseColor.asArray(),e.speed=this.speed,this._diffuseTexture&&(e._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(e._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(e._opacityTexture=this._opacityTexture.serialize()),e},n.Parse=function(i,t,r){var o=new n(i.name,t);return o.diffuseColor=e.Color3.FromArray(i.diffuseColor),o.speed=i.speed,o.alpha=i.alpha,o.id=i.id,e.Tags.AddTagsTo(o,i.tags),o.backFaceCulling=i.backFaceCulling,o.wireframe=i.wireframe,i._diffuseTexture&&(o._diffuseTexture=e.Texture.Parse(i._diffuseTexture,t,r)),i._distortionTexture&&(o._distortionTexture=e.Texture.Parse(i._distortionTexture,t,r)),i._opacityTexture&&(o._opacityTexture=e.Texture.Parse(i._opacityTexture,t,r)),i.checkReadyOnlyOnce&&(o.checkReadyOnlyOnce=i.checkReadyOnlyOnce),o},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture("distortionTexture")],n.prototype,"_distortionTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"distortionTexture",void 0),__decorate([e.serializeAsTexture("opacityTexture")],n.prototype,"_opacityTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"opacityTexture",void 0),__decorate([e.serializeAsColor3("diffuse")],n.prototype,"diffuseColor",void 0),__decorate([e.serialize()],n.prototype,"speed",void 0),n})(e.PushMaterial);e.FireMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.fireVertexShader="precision highp float;\n\nattribute vec3 position;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n\nuniform float time;\nuniform float speed;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;\nvarying vec2 vDistortionCoords2;\nvarying vec2 vDistortionCoords3;\n#endif\nvoid main(void) {\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\n#ifdef DIFFUSE\nvDiffuseUV=uv;\nvDiffuseUV.y-=0.2;\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n#ifdef DIFFUSE\n\nvec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;\nvDistortionCoords1.x=uv.x;\nvDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;\nvDistortionCoords2.x=uv.x;\nvDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;\nvDistortionCoords3.x=uv.x;\nvDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0;\n#endif\n}\n",BABYLON.Effect.ShadersStore.firePixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\nuniform sampler2D distortionSampler;\nuniform sampler2D opacitySampler;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;\nvarying vec2 vDistortionCoords2;\nvarying vec2 vDistortionCoords3;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvec4 bx2(vec4 x)\n{\nreturn vec4(2.0)*x-vec4(1.0);\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\n\nfloat alpha=1.0;\n#ifdef DIFFUSE\n\nconst float distortionAmount0=0.092;\nconst float distortionAmount1=0.092;\nconst float distortionAmount2=0.092;\nvec2 heightAttenuation=vec2(0.3,0.39);\nvec4 noise0=texture2D(distortionSampler,vDistortionCoords1);\nvec4 noise1=texture2D(distortionSampler,vDistortionCoords2);\nvec4 noise2=texture2D(distortionSampler,vDistortionCoords3);\nvec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;\nvec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);\nvec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy);\n#ifdef ALPHATEST\nif (opacityColor.r<0.1)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;\nbaseColor*=opacityColor;\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(1.0,1.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec4 color=vec4(baseColor.rgb,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.HEIGHTMAP=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.HIGHLEVEL=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r.furLength=1,r.furAngle=0,r.furColor=new e.Color3(.44,.21,.02),r.furOffset=0,r.furSpacing=12,r.furGravity=new e.Vector3(0,0,0),r.furSpeed=100,r.furDensity=20,r._disableLighting=!1,r._maxSimultaneousLights=4,r.highLevelFur=!0,r._furTime=0,r}return __extends(n,t),Object.defineProperty(n.prototype,"furTime",{get:function(){return this._furTime},set:function(e){this._furTime=e},enumerable:!0,configurable:!0}),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.updateFur=function(){for(var e=1;e<this._meshes.length;e++){var i=this._meshes[e].material;i.furLength=this.furLength,i.furAngle=this.furAngle,i.furGravity=this.furGravity,i.furSpacing=this.furSpacing,i.furSpeed=this.furSpeed,i.furColor=this.furColor,i.diffuseTexture=this.diffuseTexture,i.furTexture=this.furTexture,i.highLevelFur=this.highLevelFur,i.furTime=this.furTime,i.furDensity=this.furDensity}},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&a.texturesEnabled){if(this.diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this.diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(this.heightTexture&&s.getCaps().maxVertexTextureImageUnits){if(!this.heightTexture.isReady())return!1;o._needUVs=!0,o.HEIGHTMAP=!0}}if(this.highLevelFur!==o.HIGHLEVEL&&(o.HIGHLEVEL=!0,o.markAsUnprocessed()),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity"],d=["diffuseSampler","heightTexture","furTexture"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("fur",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),r.getCachedMaterial()!==this&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._heightTexture&&e.push(this._heightTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this.diffuseTexture===e||this._heightTexture===e)},n.prototype.dispose=function(e){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(var i=1;i<this._meshes.length;i++){var n=this._meshes[i].material;n&&n.dispose(e),this._meshes[i].dispose()}t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.FurMaterial",this._meshes&&(i.sourceMeshName=this._meshes[0].name,i.quality=this._meshes.length),i},n.prototype.getClassName=function(){return"FurMaterial"},n.Parse=function(i,t,r){var o=e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r);return i.sourceMeshName&&o.highLevelFur&&t.executeWhenReady((function(){var e=t.getMeshByName(i.sourceMeshName);if(e){var r=n.GenerateTexture("Fur Texture",t);o.furTexture=r,n.FurifyMesh(e,i.quality)}})),o},n.GenerateTexture=function(i,t){for(var n=new e.DynamicTexture("FurTexture "+i,256,t,!0),r=n.getContext(),o=0;o<2e4;++o)r.fillStyle="rgba(255, "+Math.floor(255*Math.random())+", "+Math.floor(255*Math.random())+", 1)",r.fillRect(Math.random()*n.getSize().width,Math.random()*n.getSize().height,2,2);return n.update(!1),n.wrapU=e.Texture.WRAP_ADDRESSMODE,n.wrapV=e.Texture.WRAP_ADDRESSMODE,n},n.FurifyMesh=function(i,t){var r,o=[i],a=i.material;if(!(a instanceof n))throw"The material of the source mesh must be a Fur Material";for(r=1;r<t;r++){var s=new e.FurMaterial(a.name+r,i.getScene());i.getScene().materials.pop(),e.Tags.EnableFor(s),e.Tags.AddTagsTo(s,"furShellMaterial"),s.furLength=a.furLength,s.furAngle=a.furAngle,s.furGravity=a.furGravity,s.furSpacing=a.furSpacing,s.furSpeed=a.furSpeed,s.furColor=a.furColor,s.diffuseTexture=a.diffuseTexture,s.furOffset=r/t,s.furTexture=a.furTexture,s.highLevelFur=a.highLevelFur,s.furTime=a.furTime,s.furDensity=a.furDensity;var f=i.clone(i.name+r);f.material=s,f.skeleton=i.skeleton,f.position=e.Vector3.Zero(),o.push(f)}for(r=1;r<o.length;r++)o[r].parent=i;return i.material._meshes=o,o},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture("heightTexture")],n.prototype,"_heightTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"heightTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serialize()],n.prototype,"furLength",void 0),__decorate([e.serialize()],n.prototype,"furAngle",void 0),__decorate([e.serializeAsColor3()],n.prototype,"furColor",void 0),__decorate([e.serialize()],n.prototype,"furOffset",void 0),__decorate([e.serialize()],n.prototype,"furSpacing",void 0),__decorate([e.serializeAsVector3()],n.prototype,"furGravity",void 0),__decorate([e.serialize()],n.prototype,"furSpeed",void 0),__decorate([e.serialize()],n.prototype,"furDensity",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],n.prototype,"highLevelFur",void 0),__decorate([e.serialize()],n.prototype,"furTime",null),n})(e.PushMaterial);e.FurMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.furVertexShader="precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\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<bonesDeclaration>\n\nuniform float furLength;\nuniform float furAngle;\n#ifdef HIGHLEVEL\nuniform float furOffset;\nuniform vec3 furGravity;\nuniform float furTime;\nuniform float furSpacing;\nuniform float furDensity;\n#endif\n#ifdef HEIGHTMAP\nuniform sampler2D heightTexture;\n#endif\n#ifdef HIGHLEVEL\nvarying vec2 vFurUV;\n#endif\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\nvarying float vfur_length;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nfloat Rand(vec3 rv) {\nfloat x=dot(rv,vec3(12.9898,78.233,24.65487));\nreturn fract(sin(x)*43758.5453);\n}\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\n\nfloat r=Rand(position);\n#ifdef HEIGHTMAP\n#if __VERSION__>100\nvfur_length=furLength*texture(heightTexture,uv).x;\n#else\nvfur_length=furLength*texture2D(heightTexture,uv).r;\n#endif\n#else \nvfur_length=(furLength*r);\n#endif\nvec3 tangent1=vec3(normal.y,-normal.x,0);\nvec3 tangent2=vec3(-normal.z,0,normal.x);\nr=Rand(tangent1*r);\nfloat J=(2.0+4.0*r);\nr=Rand(tangent2*r);\nfloat K=(2.0+2.0*r);\ntangent1=tangent1*J+tangent2*K;\ntangent1=normalize(tangent1);\nvec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle);\n#ifdef HIGHLEVEL\n\nvec3 forceDirection=vec3(0.0,0.0,0.0);\nforceDirection.x=sin(furTime+position.x*0.05)*0.2;\nforceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;\nforceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;\nvec3 displacement=vec3(0.0,0.0,0.0);\ndisplacement=furGravity+forceDirection;\nfloat displacementFactor=pow(furOffset,3.0);\nvec3 aNormal=normal;\naNormal.xyz+=displacement*displacementFactor;\nnewPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing);\n#endif\n#ifdef NORMAL\n#ifdef HIGHLEVEL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))*aNormal);\n#else\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#endif\n\ngl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);\nvec4 worldPos=finalWorld*vec4(newPosition,1.0);\nvPositionW=vec3(worldPos);\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\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#ifdef HIGHLEVEL\nvFurUV=vDiffuseUV*furDensity;\n#endif\n#else\n#ifdef HIGHLEVEL\nvFurUV=uv*furDensity;\n#endif\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",
  103309. BABYLON.Effect.ShadersStore.furPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nuniform vec4 furColor;\nuniform float furLength;\nvarying vec3 vPositionW;\nvarying float vfur_length;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef HIGHLEVEL\nuniform float furOffset;\nuniform sampler2D furTexture;\nvarying vec2 vFurUV;\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<fogFragmentDeclaration>\n#include<clipPlaneFragmentDeclaration>\nfloat Rand(vec3 rv) {\nfloat x=dot(rv,vec3(12.9898,78.233,24.65487));\nreturn fract(sin(x)*43758.5453);\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=furColor;\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor*=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef HIGHLEVEL\n\nvec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));\nif (furTextureColor.a<=0.0 || furTextureColor.g<furOffset) {\ndiscard;\n}\nfloat occlusion=mix(0.0,furTextureColor.b*1.2,furOffset);\nbaseColor=vec4(baseColor.xyz*occlusion,1.1-furOffset);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0);\n\n#ifdef HIGHLEVEL\nvec4 color=vec4(finalDiffuse,alpha);\n#else\nfloat r=vfur_length/furLength*0.5;\nvec4 color=vec4(finalDiffuse*(0.5+r),alpha);\n#endif\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.BUMP=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.SPECULARTERM=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r.specularColor=new e.Color3(0,0,0),r.specularPower=64,r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(a.texturesEnabled){if(this.mixTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this.mixTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}(this.bumpTexture1||this.bumpTexture2||this.bumpTexture3)&&e.StandardMaterial.BumpTextureEnabled&&(o._needUVs=!0,o._needNormals=!0,o.BUMP=!0)}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","vClipPlane","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],d=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("terrain",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),e.StandardMaterial.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),e.StandardMaterial.BumpTextureEnabled&&r.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._mixTexture&&e.push(this._mixTexture),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._bumpTexture1&&e.push(this._bumpTexture1),this._bumpTexture2&&e.push(this._bumpTexture2),this._bumpTexture3&&e.push(this._bumpTexture3),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._mixTexture===e||(this._diffuseTexture1===e||(this._diffuseTexture2===e||(this._diffuseTexture3===e||(this._bumpTexture1===e||(this._bumpTexture2===e||this._bumpTexture3===e))))))},n.prototype.dispose=function(e){this.mixTexture&&this.mixTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.TerrainMaterial",i},n.prototype.getClassName=function(){return"TerrainMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("mixTexture")],n.prototype,"_mixTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"mixTexture",void 0),__decorate([e.serializeAsTexture("diffuseTexture1")],n.prototype,"_diffuseTexture1",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture1",void 0),__decorate([e.serializeAsTexture("diffuseTexture2")],n.prototype,"_diffuseTexture2",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture2",void 0),__decorate([e.serializeAsTexture("diffuseTexture3")],n.prototype,"_diffuseTexture3",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture3",void 0),__decorate([e.serializeAsTexture("bumpTexture1")],n.prototype,"_bumpTexture1",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture1",void 0),__decorate([e.serializeAsTexture("bumpTexture2")],n.prototype,"_bumpTexture2",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture2",void 0),__decorate([e.serializeAsTexture("bumpTexture3")],n.prototype,"_bumpTexture3",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture3",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"specularColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.TerrainMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.terrainVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform mat4 textureMatrix;\nuniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\nif (vTextureInfos.x == 0.)\n{\nvTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\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",BABYLON.Effect.ShadersStore.terrainPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform sampler2D textureSampler;\nuniform vec2 vTextureInfos;\nuniform sampler2D diffuse1Sampler;\nuniform sampler2D diffuse2Sampler;\nuniform sampler2D diffuse3Sampler;\nuniform vec2 diffuse1Infos;\nuniform vec2 diffuse2Infos;\nuniform vec2 diffuse3Infos;\n#endif\n#ifdef BUMP\nuniform sampler2D bump1Sampler;\nuniform sampler2D bump2Sampler;\nuniform sampler2D bump3Sampler;\n#endif\n\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\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 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,vec3 mixColor)\n{ \nvec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;\nvec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;\nvec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;\nbump1Color.rgb*=mixColor.r;\nbump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);\nvec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);\nmap=map*255./127.-128./127.;\nmat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);\nreturn normalize(TBN*map);\n}\n#endif\nvoid main(void) {\n\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(textureSampler,vTextureUV);\n#if defined(BUMP) && defined(DIFFUSE)\nnormalW=perturbNormal(viewDirectionW,baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vTextureInfos.y;\nvec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);\nvec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);\nvec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);\ndiffuse1Color.rgb*=baseColor.r;\ndiffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);\nbaseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSEX=!1,i.DIFFUSEY=!1,i.DIFFUSEZ=!1,i.BUMPX=!1,i.BUMPY=!1,i.BUMPZ=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.SPECULARTERM=!1,i.NORMAL=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.tileSize=1,r.diffuseColor=new e.Color3(1,1,1),r.specularColor=new e.Color3(.2,.2,.2),r.specularPower=64,r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&a.texturesEnabled){if(e.StandardMaterial.DiffuseTextureEnabled)for(var f=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],l=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"],u=0;u<f.length;u++)if(f[u]){if(!f[u].isReady())return!1;o[l[u]]=!0}if(e.StandardMaterial.BumpTextureEnabled)for(var f=[this.normalTextureX,this.normalTextureY,this.normalTextureZ],l=["BUMPX","BUMPY","BUMPZ"],u=0;u<f.length;u++)if(f[u]){if(!f[u].isReady())return!1;o[l[u]]=!0}}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var c=new e.EffectFallbacks;o.FOG&&c.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,c,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&c.addCPUSkinningFallback(0,t);var d=[e.VertexBuffer.PositionKind];o.NORMAL&&d.push(e.VertexBuffer.NormalKind),o.VERTEXCOLOR&&d.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(d,t,o,c),e.MaterialHelper.PrepareAttributesForInstances(d,o);var p=o.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","vClipPlane","tileSize"],m=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ"],v=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:v,samplers:m,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("triplanar",{attributes:d,uniformsNames:h,uniformBuffersNames:v,samplers:m,defines:p,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),r.getCachedMaterial()!==this&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTextureX&&e.push(this._diffuseTextureX),this._diffuseTextureY&&e.push(this._diffuseTextureY),this._diffuseTextureZ&&e.push(this._diffuseTextureZ),this._normalTextureX&&e.push(this._normalTextureX),this._normalTextureY&&e.push(this._normalTextureY),this._normalTextureZ&&e.push(this._normalTextureZ),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._diffuseTextureX===e||(this._diffuseTextureY===e||(this._diffuseTextureZ===e||(this._normalTextureX===e||(this._normalTextureY===e||this._normalTextureZ===e)))))},n.prototype.dispose=function(e){this.mixTexture&&this.mixTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.TriPlanarMaterial",i},n.prototype.getClassName=function(){return"TriPlanarMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture()],n.prototype,"mixTexture",void 0),__decorate([e.serializeAsTexture("diffuseTextureX")],n.prototype,"_diffuseTextureX",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTextureX",void 0),__decorate([e.serializeAsTexture("diffuseTexturY")],n.prototype,"_diffuseTextureY",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTextureY",void 0),__decorate([e.serializeAsTexture("diffuseTextureZ")],n.prototype,"_diffuseTextureZ",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTextureZ",void 0),__decorate([e.serializeAsTexture("normalTextureX")],n.prototype,"_normalTextureX",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"normalTextureX",void 0),__decorate([e.serializeAsTexture("normalTextureY")],n.prototype,"_normalTextureY",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"normalTextureY",void 0),__decorate([e.serializeAsTexture("normalTextureZ")],n.prototype,"_normalTextureZ",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"normalTextureZ",void 0),__decorate([e.serialize()],n.prototype,"tileSize",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"specularColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.TriPlanarMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.triplanarVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\n#endif\nuniform float tileSize;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void)\n{\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 DIFFUSEX\nvTextureUVX=worldPos.zy/tileSize;\n#endif\n#ifdef DIFFUSEY\nvTextureUVY=worldPos.xz/tileSize;\n#endif\n#ifdef DIFFUSEZ\nvTextureUVZ=worldPos.xy/tileSize;\n#endif\n#ifdef NORMAL\n\nvec3 xtan=vec3(0,0,1);\nvec3 xbin=vec3(0,1,0);\nvec3 ytan=vec3(1,0,0);\nvec3 ybin=vec3(0,0,1);\nvec3 ztan=vec3(1,0,0);\nvec3 zbin=vec3(0,1,0);\nvec3 normalizedNormal=normalize(normal);\nnormalizedNormal*=normalizedNormal;\nvec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);\nvec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);\nworldTangent=(world*vec4(worldTangent,1.0)).xyz;\nworldBinormal=(world*vec4(worldBinormal,1.0)).xyz;\nvec3 worldNormal=normalize(cross(worldTangent,worldBinormal));\ntangentSpace[0]=worldTangent;\ntangentSpace[1]=worldBinormal;\ntangentSpace[2]=worldNormal;\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",BABYLON.Effect.ShadersStore.triplanarPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\nuniform sampler2D diffuseSamplerX;\n#ifdef BUMPX\nuniform sampler2D normalSamplerX;\n#endif\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\nuniform sampler2D diffuseSamplerY;\n#ifdef BUMPY\nuniform sampler2D normalSamplerY;\n#endif\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\nuniform sampler2D diffuseSamplerZ;\n#ifdef BUMPZ\nuniform sampler2D normalSamplerZ;\n#endif\n#endif\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(0.,0.,0.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=tangentSpace[2];\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec4 baseNormal=vec4(0.0,0.0,0.0,1.0);\nnormalW*=normalW;\n#ifdef DIFFUSEX\nbaseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x;\n#ifdef BUMPX\nbaseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x;\n#endif\n#endif\n#ifdef DIFFUSEY\nbaseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y;\n#ifdef BUMPY\nbaseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y;\n#endif\n#endif\n#ifdef DIFFUSEZ\nbaseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z;\n#ifdef BUMPZ\nbaseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z;\n#endif\n#endif\n#ifdef NORMAL\nnormalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.CLIPPLANE=!1,i.POINTSIZE=!1,i.FOG=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.luminance=1,r.turbidity=10,r.rayleigh=2,r.mieCoefficient=.005,r.mieDirectionalG=.8,r.distance=500,r.inclination=.49,r.azimuth=.25,r.sunPosition=new e.Vector3(0,100,0),r.useSunPosition=!1,r._cameraPosition=e.Vector3.Zero(),r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!1),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var s=new e.EffectFallbacks;o.FOG&&s.addFallback(1,"FOG");var f=[e.VertexBuffer.PositionKind];o.VERTEXCOLOR&&f.push(e.VertexBuffer.ColorKind);var l=o.toString();n.setEffect(a.getEngine().createEffect("sky",f,["world","viewProjection","view","vFogInfos","vFogColor","pointSize","vClipPlane","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition"],[],l,s,this.onCompiled,this.onError),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene();if(n._materialDefines){var o=n.effect;if(o){if(this._activeEffect=o,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._mustRebind(r,o)){if(r.clipPlane){var a=r.clipPlane;this._activeEffect.setFloat4("vClipPlane",a.normal.x,a.normal.y,a.normal.z,a.d)}this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize)}r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect);var s=r.activeCamera;if(s){var f=s.getWorldMatrix();this._cameraPosition.x=f.m[12],this._cameraPosition.y=f.m[13],this._cameraPosition.z=f.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}
  103310. if(this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){var l=Math.PI*(this.inclination-.5),u=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(u),this.sunPosition.y=this.distance*Math.sin(u)*Math.sin(l),this.sunPosition.z=this.distance*Math.sin(u)*Math.cos(l)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect)}}},n.prototype.getAnimatables=function(){return[]},n.prototype.dispose=function(e){t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.SkyMaterial",i},n.prototype.getClassName=function(){return"SkyMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serialize()],n.prototype,"luminance",void 0),__decorate([e.serialize()],n.prototype,"turbidity",void 0),__decorate([e.serialize()],n.prototype,"rayleigh",void 0),__decorate([e.serialize()],n.prototype,"mieCoefficient",void 0),__decorate([e.serialize()],n.prototype,"mieDirectionalG",void 0),__decorate([e.serialize()],n.prototype,"distance",void 0),__decorate([e.serialize()],n.prototype,"inclination",void 0),__decorate([e.serialize()],n.prototype,"azimuth",void 0),__decorate([e.serializeAsVector3()],n.prototype,"sunPosition",void 0),__decorate([e.serialize()],n.prototype,"useSunPosition",void 0),n})(e.PushMaterial);e.SkyMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.skyVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\nvoid main(void) {\ngl_Position=viewProjection*world*vec4(position,1.0);\nvec4 worldPos=world*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.skyPixelShader="precision highp float;\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\nuniform vec3 cameraPosition;\nuniform float luminance;\nuniform float turbidity;\nuniform float rayleigh;\nuniform float mieCoefficient;\nuniform float mieDirectionalG;\nuniform vec3 sunPosition;\n\n#include<fogFragmentDeclaration>\n\nconst float e=2.71828182845904523536028747135266249775724709369995957;\nconst float pi=3.141592653589793238462643383279502884197169;\nconst float n=1.0003;\nconst float N=2.545E25;\nconst float pn=0.035;\nconst vec3 lambda=vec3(680E-9,550E-9,450E-9);\nconst vec3 K=vec3(0.686,0.678,0.666);\nconst float v=4.0;\nconst float rayleighZenithLength=8.4E3;\nconst float mieZenithLength=1.25E3;\nconst vec3 up=vec3(0.0,1.0,0.0);\nconst float EE=1000.0;\nconst float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;\nconst float cutoffAngle=pi/1.95;\nconst float steepness=1.5;\nvec3 totalRayleigh(vec3 lambda)\n{\nreturn (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));\n}\nvec3 simplifiedRayleigh()\n{\nreturn 0.0005/vec3(94,40,18);\n}\nfloat rayleighPhase(float cosTheta)\n{ \nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));\n}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{\nfloat c=(0.2*T )*10E-18;\nreturn 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;\n}\nfloat hgPhase(float cosTheta,float g)\n{\nreturn (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));\n}\nfloat sunIntensity(float zenithAngleCos)\n{\nreturn EE*max(0.0,1.0-exp(-((cutoffAngle-acos(zenithAngleCos))/steepness)));\n}\nfloat A=0.15;\nfloat B=0.50;\nfloat C=0.10;\nfloat D=0.20;\nfloat EEE=0.02;\nfloat F=0.30;\nfloat W=1000.0;\nvec3 Uncharted2Tonemap(vec3 x)\n{\nreturn ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\n\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);\nfloat rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));\nvec3 sunDirection=normalize(sunPosition);\nfloat sunE=sunIntensity(dot(sunDirection,up));\nvec3 betaR=simplifiedRayleigh()*rayleighCoefficient;\nvec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;\nfloat zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition))));\nfloat sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nfloat sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nvec3 Fex=exp(-(betaR*sR+betaM*sM));\nfloat cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);\nfloat rPhase=rayleighPhase(cosTheta*0.5+0.5);\nvec3 betaRTheta=betaR*rPhase;\nfloat mPhase=hgPhase(cosTheta,mieDirectionalG);\nvec3 betaMTheta=betaM*mPhase;\nvec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));\nLin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));\nvec3 direction=normalize(vPositionW-cameraPosition);\nfloat theta=acos(direction.y);\nfloat phi=atan(direction.z,direction.x);\nvec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);\nvec3 L0=vec3(0.1)*Fex;\nfloat sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);\nL0+=(sunE*19000.0*Fex)*sundisk;\nvec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));\nvec3 texColor=(Lin+L0); \ntexColor*=0.04 ;\ntexColor+=vec3(0.0,0.001,0.0025)*0.3;\nfloat g_fMaxLuminance=1.0;\nfloat fLumScaled=0.1/luminance; \nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); \nfloat ExposureBias=fLumCompressed;\nvec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);\n\n\n\nvec3 retColor=curr*whiteScale;\n\n\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.TRANSPARENT=!1,i.FOG=!1,i.PREMULTIPLYALPHA=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.mainColor=e.Color3.Black(),r.lineColor=e.Color3.Teal(),r.gridRatio=1,r.gridOffset=e.Vector3.Zero(),r.majorUnitFrequency=10,r.minorUnitVisibility=.33,r.opacity=1,r.preMultiplyAlpha=!1,r._gridControl=new e.Vector4(r.gridRatio,r.majorUnitFrequency,r.minorUnitVisibility,r.opacity),r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.opacity<1},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;if(o.TRANSPARENT!==this.opacity<1&&(o.TRANSPARENT=!o.TRANSPARENT,o.markAsUnprocessed()),o.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(o.PREMULTIPLYALPHA=!o.PREMULTIPLYALPHA,o.markAsUnprocessed()),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,!1,this.fogEnabled,o),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var s=[e.VertexBuffer.PositionKind,e.VertexBuffer.NormalKind],f=o.toString();n.setEffect(a.getEngine().createEffect("grid",s,["projection","worldView","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view"],[],f,void 0,this.onCompiled,this.onError),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene();if(n._materialDefines){var o=n.effect;o&&(this._activeEffect=o,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("worldView",i.multiply(r.getViewMatrix())),this._activeEffect.setMatrix("view",r.getViewMatrix()),this._activeEffect.setMatrix("projection",r.getProjectionMatrix()),this._mustRebind(r,o)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl)),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.dispose=function(e){t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.GridMaterial",i},n.prototype.getClassName=function(){return"GridMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsColor3()],n.prototype,"mainColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"lineColor",void 0),__decorate([e.serialize()],n.prototype,"gridRatio",void 0),__decorate([e.serializeAsColor3()],n.prototype,"gridOffset",void 0),__decorate([e.serialize()],n.prototype,"majorUnitFrequency",void 0),__decorate([e.serialize()],n.prototype,"minorUnitVisibility",void 0),__decorate([e.serialize()],n.prototype,"opacity",void 0),__decorate([e.serialize()],n.prototype,"preMultiplyAlpha",void 0),n})(e.PushMaterial);e.GridMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.gridVertexShader="precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}",BABYLON.Effect.ShadersStore.gridPixelShader="#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.AMBIENT=!1,i.OPACITY=!1,i.OPACITYRGB=!1,i.REFLECTION=!1,i.EMISSIVE=!1,i.SPECULAR=!1,i.BUMP=!1,i.PARALLAX=!1,i.PARALLAXOCCLUSION=!1,i.SPECULAROVERALPHA=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.ALPHAFROMDIFFUSE=!1,i.POINTSIZE=!1,i.FOG=!1,i.SPECULARTERM=!1,i.DIFFUSEFRESNEL=!1,i.OPACITYFRESNEL=!1,i.REFLECTIONFRESNEL=!1,i.REFRACTIONFRESNEL=!1,i.EMISSIVEFRESNEL=!1,i.FRESNEL=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.GLOSSINESS=!1,i.ROUGHNESS=!1,i.EMISSIVEASILLUMINATION=!1,i.LINKEMISSIVEWITHDIFFUSE=!1,i.REFLECTIONFRESNELFROMSPECULAR=!1,i.LIGHTMAP=!1,i.USELIGHTMAPASSHADOWMAP=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.LOGARITHMICDEPTH=!1,i.REFRACTION=!1,i.REFRACTIONMAP_3D=!1,i.REFLECTIONOVERALPHA=!1,i.TWOSIDEDLIGHTING=!1,i.SHADOWFLOAT=!1,i.MORPHTARGETS=!1,i.MORPHTARGETS_NORMAL=!1,i.MORPHTARGETS_TANGENT=!1,i.NUM_MORPH_INFLUENCERS=0,i.IMAGEPROCESSING=!1,i.VIGNETTE=!1,i.VIGNETTEBLENDMODEMULTIPLY=!1,i.VIGNETTEBLENDMODEOPAQUE=!1,i.TONEMAPPING=!1,i.CONTRAST=!1,i.COLORCURVES=!1,i.COLORGRADING=!1,i.COLORGRADING3D=!1,i.SAMPLER3DGREENDEPTH=!1,i.SAMPLER3DBGRMAP=!1,i.IMAGEPROCESSINGPOSTPROCESS=!1,i.EXPOSURE=!1,i.rebuild(),i}return __extends(i,e),i.prototype.setReflectionMode=function(e){for(var i=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"],t=0,n=i;t<n.length;t++){var r=n[t];this[r]=r===e}},i})(e.MaterialDefines);e.StandardMaterialDefines_OldVer=i;var t=(function(t){function n(i,r){var o=t.call(this,i,r)||this;return o.ambientColor=new e.Color3(0,0,0),o.diffuseColor=new e.Color3(1,1,1),o.specularColor=new e.Color3(1,1,1),o.emissiveColor=new e.Color3(0,0,0),o.specularPower=64,o._useAlphaFromDiffuseTexture=!1,o._useEmissiveAsIllumination=!1,o._linkEmissiveWithDiffuse=!1,o._useSpecularOverAlpha=!1,o._useReflectionOverAlpha=!1,o._disableLighting=!1,o._useParallax=!1,o._useParallaxOcclusion=!1,o.parallaxScaleBias=.05,o._roughness=0,o.indexOfRefraction=.98,o.invertRefractionY=!0,o._useLightmapAsShadowmap=!1,o._useReflectionFresnelFromSpecular=!1,o._useGlossinessFromSpecularMapAlpha=!1,o._maxSimultaneousLights=4,o._invertNormalMapX=!1,o._invertNormalMapY=!1,o._twoSidedLighting=!1,o._renderTargets=new e.SmartArray(16),o._worldViewProjectionMatrix=e.Matrix.Zero(),o._globalAmbientColor=new e.Color3(0,0,0),o._attachImageProcessingConfiguration(null),o.getRenderTargetTextures=function(){return o._renderTargets.reset(),n.ReflectionTextureEnabled&&o._reflectionTexture&&o._reflectionTexture.isRenderTarget&&o._renderTargets.push(o._reflectionTexture),n.RefractionTextureEnabled&&o._refractionTexture&&o._refractionTexture.isRenderTarget&&o._renderTargets.push(o._refractionTexture),o._renderTargets},o}return __extends(n,t),Object.defineProperty(n.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),n.prototype._attachImageProcessingConfiguration=function(e){var i=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(e){i._markAllSubMeshesAsImageProcessingDirty()})))},Object.defineProperty(n.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),n.prototype.getClassName=function(){return"StandardMaterial_OldVer"},Object.defineProperty(n.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()},enumerable:!0,configurable:!0}),n.prototype.needAlphaBlending=function(){return this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled},n.prototype.needAlphaTesting=function(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha},n.prototype._shouldUseAlphaFromDiffuseTexture=function(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture},n.prototype.getAlphaTestTexture=function(){return this._diffuseTexture},n.prototype.isReadyForSubMesh=function(t,r,o){if(this.isFrozen&&this._wasPreviouslyReady&&r.effect)return!0;r._materialDefines||(r._materialDefines=new i);var a=this.getScene(),s=r._materialDefines;if(!this.checkReadyOnEveryCall&&r.effect&&s._renderId===a.getRenderId())return!0;var f=a.getEngine();if(s._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,s,!0,this._maxSimultaneousLights,this._disableLighting),s._areTexturesDirty){if(s._needUVs=!1,a.texturesEnabled){if(this._diffuseTexture&&n.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.DIFFUSE=!0}else s.DIFFUSE=!1;if(this._ambientTexture&&n.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.AMBIENT=!0}else s.AMBIENT=!1;if(this._opacityTexture&&n.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.OPACITY=!0,s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&n.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(s._needNormals=!0,s.REFLECTION=!0,s.ROUGHNESS=this._roughness>0,s.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,s.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE,s.REFLECTIONMAP_3D=this._reflectionTexture.isCube,this._reflectionTexture.coordinatesMode){case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:s.setReflectionMode("REFLECTIONMAP_CUBIC");break;case e.Texture.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case e.Texture.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case e.Texture.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case e.Texture.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case e.Texture.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case e.Texture.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED")}}else s.REFLECTION=!1;if(this._emissiveTexture&&n.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.EMISSIVE=!0}else s.EMISSIVE=!1;if(this._lightmapTexture&&n.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.LIGHTMAP=!0,s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap}else s.LIGHTMAP=!1;if(this._specularTexture&&n.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.SPECULAR=!0,s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(a.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&n.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;s._needUVs=!0,s.BUMP=!0,s.PARALLAX=this._useParallax,s.PARALLAXOCCLUSION=this._useParallaxOcclusion}else s.BUMP=!1;if(this._refractionTexture&&n.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.REFRACTION=!0,s.REFRACTIONMAP_3D=this._refractionTexture.isCube}else s.REFRACTION=!1;s.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else s.DIFFUSE=!1,s.AMBIENT=!1,s.OPACITY=!1,s.REFLECTION=!1,s.EMISSIVE=!1,s.LIGHTMAP=!1,s.BUMP=!1,s.REFRACTION=!1;s.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),s.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,s.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,s.SPECULAROVERALPHA=this._useSpecularOverAlpha}if(s._areImageProcessingDirty){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s)}if(s._areFresnelDirty&&(n.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(s.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,s.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,s.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,s.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,s.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,s.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,s._needNormals=!0,s.FRESNEL=!0):s.FRESNEL=!1),e.MaterialHelper.PrepareDefinesForMisc(t,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,s),e.MaterialHelper.PrepareDefinesForAttributes(t,s,!0,!0,!0),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,f,s,!!o),s.isDirty){s.markAsProcessed(),a.resetCachedMaterial();var l=new e.EffectFallbacks;s.REFLECTION&&l.addFallback(0,"REFLECTION"),s.SPECULAR&&l.addFallback(0,"SPECULAR"),s.BUMP&&l.addFallback(0,"BUMP"),s.PARALLAX&&l.addFallback(1,"PARALLAX"),s.PARALLAXOCCLUSION&&l.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&l.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&l.addFallback(1,"FOG"),s.POINTSIZE&&l.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&l.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(s,l,this._maxSimultaneousLights),s.SPECULARTERM&&l.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&l.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&l.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&l.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&l.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&l.addFallback(4,"FRESNEL");var u=[e.VertexBuffer.PositionKind];s.NORMAL&&u.push(e.VertexBuffer.NormalKind),s.UV1&&u.push(e.VertexBuffer.UVKind),s.UV2&&u.push(e.VertexBuffer.UV2Kind),s.VERTEXCOLOR&&u.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(u,t,s,l),e.MaterialHelper.PrepareAttributesForInstances(u,s),e.MaterialHelper.PrepareAttributesForMorphTargets(u,t,s);var c="default",d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","logarithmicDepthConstant","vTangentSpaceParams"],p=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"],h=["Material","Scene"];e.ImageProcessingConfiguration.PrepareUniforms(d,s),e.ImageProcessingConfiguration.PrepareSamplers(p,s),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:h,samplers:p,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),this.customShaderNameResolve&&(c=this.customShaderNameResolve(c,d,h,p,s));var m=s.toString();r.setEffect(a.getEngine().createEffect(c,{attributes:u,uniformsNames:d,uniformBuffersNames:h,samplers:p,defines:m,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},f),s),this.buildUniformLayout()}return!(!r.effect||!r.effect.isReady())&&(s._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("diffuseLeftColor",4),this._uniformBuffer.addUniform("diffuseRightColor",4),this._uniformBuffer.addUniform("opacityParts",4),this._uniformBuffer.addUniform("reflectionLeftColor",4),this._uniformBuffer.addUniform("reflectionRightColor",4),this._uniformBuffer.addUniform("refractionLeftColor",4),this._uniformBuffer.addUniform("refractionRightColor",4),this._uniformBuffer.addUniform("emissiveLeftColor",4),this._uniformBuffer.addUniform("emissiveRightColor",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",2),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vSpecularInfos",2),this._uniformBuffer.addUniform("vBumpInfos",3),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("specularMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vSpecularColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("vDiffuseColor",4),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},n.prototype.unbind=function(){this._activeEffect&&(this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._activeEffect.setTexture("reflection2DSampler",null),this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._activeEffect.setTexture("refraction2DSampler",null)),t.prototype.unbind.call(this)},n.prototype.bindForSubMesh=function(i,t,r){var o=this.getScene(),a=r._materialDefines;if(a){var s=r.effect;if(s){if(this._activeEffect=s,this.bindOnlyWorldMatrix(i),e.MaterialHelper.BindBonesParameters(t,s),this._mustRebind(o,s,t.visibility)){if(this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s),!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(n.FresnelEnabled&&a.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),this._uniformBuffer.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._uniformBuffer.updateColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),this._uniformBuffer.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),this._uniformBuffer.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._uniformBuffer.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),o.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),
  103311. this._uniformBuffer.updateMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._ambientTexture&&n.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),this._uniformBuffer.updateMatrix("ambientMatrix",this._ambientTexture.getTextureMatrix())),this._opacityTexture&&n.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._uniformBuffer.updateMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix())),this._reflectionTexture&&n.ReflectionTextureEnabled&&(this._uniformBuffer.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),this._uniformBuffer.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix())),this._emissiveTexture&&n.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),this._uniformBuffer.updateMatrix("emissiveMatrix",this._emissiveTexture.getTextureMatrix())),this._lightmapTexture&&n.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),this._uniformBuffer.updateMatrix("lightmapMatrix",this._lightmapTexture.getTextureMatrix())),this._specularTexture&&n.SpecularTextureEnabled&&(this._uniformBuffer.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),this._uniformBuffer.updateMatrix("specularMatrix",this._specularTexture.getTextureMatrix())),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&(this._uniformBuffer.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),this._uniformBuffer.updateMatrix("bumpMatrix",this._bumpTexture.getTextureMatrix()),o._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&n.RefractionTextureEnabled)){var f=1;this._refractionTexture.isCube||(this._uniformBuffer.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(f=this._refractionTexture.depth)),this._uniformBuffer.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,f,this.invertRefractionY?-1:1)}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),a.SPECULARTERM&&this._uniformBuffer.updateColor4("vSpecularColor",this.specularColor,this.specularPower),this._uniformBuffer.updateColor3("vEmissiveColor",this.emissiveColor),this._uniformBuffer.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility)}if(o.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&s.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&n.AmbientTextureEnabled&&s.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&n.OpacityTextureEnabled&&s.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&n.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?s.setTexture("reflectionCubeSampler",this._reflectionTexture):s.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&n.EmissiveTextureEnabled&&s.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&n.LightmapTextureEnabled&&s.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&n.SpecularTextureEnabled&&s.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&s.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&n.RefractionTextureEnabled)){var f=1;this._refractionTexture.isCube?s.setTexture("refractionCubeSampler",this._refractionTexture):s.setTexture("refraction2DSampler",this._refractionTexture)}e.MaterialHelper.BindClipPlane(s,o),o.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),e.MaterialHelper.BindEyePosition(s,o),s.setColor3("vAmbientColor",this._globalAmbientColor)}!this._mustRebind(o,s)&&this.isFrozen||(o.lightsEnabled&&!this._disableLighting&&e.MaterialHelper.BindLights(o,t,s,a,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture)&&this.bindView(s),e.MaterialHelper.BindFogParameters(o,t,s),a.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(t,s),e.MaterialHelper.BindLogDepth(a,s,o),this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(t,this._activeEffect)}}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e},n.prototype.dispose=function(e,i){i&&(this._diffuseTexture&&this._diffuseTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._specularTexture&&this._specularTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),t.prototype.dispose.call(this,e,i)},n.prototype.clone=function(i){var t=this,r=e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this);return r.name=i,r.id=i,r},n.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},Object.defineProperty(n,"DiffuseTextureEnabled",{get:function(){return n._DiffuseTextureEnabled},set:function(i){n._DiffuseTextureEnabled!==i&&(n._DiffuseTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"AmbientTextureEnabled",{get:function(){return n._AmbientTextureEnabled},set:function(i){n._AmbientTextureEnabled!==i&&(n._AmbientTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"OpacityTextureEnabled",{get:function(){return n._OpacityTextureEnabled},set:function(i){n._OpacityTextureEnabled!==i&&(n._OpacityTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"ReflectionTextureEnabled",{get:function(){return n._ReflectionTextureEnabled},set:function(i){n._ReflectionTextureEnabled!==i&&(n._ReflectionTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"EmissiveTextureEnabled",{get:function(){return n._EmissiveTextureEnabled},set:function(i){n._EmissiveTextureEnabled!==i&&(n._EmissiveTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"SpecularTextureEnabled",{get:function(){return n._SpecularTextureEnabled},set:function(i){n._SpecularTextureEnabled!==i&&(n._SpecularTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"BumpTextureEnabled",{get:function(){return n._BumpTextureEnabled},set:function(i){n._BumpTextureEnabled!==i&&(n._BumpTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"LightmapTextureEnabled",{get:function(){return n._LightmapTextureEnabled},set:function(i){n._LightmapTextureEnabled!==i&&(n._LightmapTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"RefractionTextureEnabled",{get:function(){return n._RefractionTextureEnabled},set:function(i){n._RefractionTextureEnabled!==i&&(n._RefractionTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"ColorGradingTextureEnabled",{get:function(){return n._ColorGradingTextureEnabled},set:function(i){n._ColorGradingTextureEnabled!==i&&(n._ColorGradingTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"FresnelEnabled",{get:function(){return n._FresnelEnabled},set:function(i){n._FresnelEnabled!==i&&(n._FresnelEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.FresnelDirtyFlag))},enumerable:!0,configurable:!0}),n._DiffuseTextureEnabled=!0,n._AmbientTextureEnabled=!0,n._OpacityTextureEnabled=!0,n._ReflectionTextureEnabled=!0,n._EmissiveTextureEnabled=!0,n._SpecularTextureEnabled=!0,n._BumpTextureEnabled=!0,n._LightmapTextureEnabled=!0,n._RefractionTextureEnabled=!0,n._ColorGradingTextureEnabled=!0,n._FresnelEnabled=!0,__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture("ambientTexture")],n.prototype,"_ambientTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"ambientTexture",void 0),__decorate([e.serializeAsTexture("opacityTexture")],n.prototype,"_opacityTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"opacityTexture",void 0),__decorate([e.serializeAsTexture("reflectionTexture")],n.prototype,"_reflectionTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"reflectionTexture",void 0),__decorate([e.serializeAsTexture("emissiveTexture")],n.prototype,"_emissiveTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"emissiveTexture",void 0),__decorate([e.serializeAsTexture("specularTexture")],n.prototype,"_specularTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"specularTexture",void 0),__decorate([e.serializeAsTexture("bumpTexture")],n.prototype,"_bumpTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture",void 0),__decorate([e.serializeAsTexture("lightmapTexture")],n.prototype,"_lightmapTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"lightmapTexture",void 0),__decorate([e.serializeAsTexture("refractionTexture")],n.prototype,"_refractionTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"refractionTexture",void 0),__decorate([e.serializeAsColor3("ambient")],n.prototype,"ambientColor",void 0),__decorate([e.serializeAsColor3("diffuse")],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3("specular")],n.prototype,"specularColor",void 0),__decorate([e.serializeAsColor3("emissive")],n.prototype,"emissiveColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("useAlphaFromDiffuseTexture")],n.prototype,"_useAlphaFromDiffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useAlphaFromDiffuseTexture",void 0),__decorate([e.serialize("useEmissiveAsIllumination")],n.prototype,"_useEmissiveAsIllumination",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useEmissiveAsIllumination",void 0),__decorate([e.serialize("linkEmissiveWithDiffuse")],n.prototype,"_linkEmissiveWithDiffuse",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"linkEmissiveWithDiffuse",void 0),__decorate([e.serialize("useSpecularOverAlpha")],n.prototype,"_useSpecularOverAlpha",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useSpecularOverAlpha",void 0),__decorate([e.serialize("useReflectionOverAlpha")],n.prototype,"_useReflectionOverAlpha",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useReflectionOverAlpha",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("useParallax")],n.prototype,"_useParallax",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useParallax",void 0),__decorate([e.serialize("useParallaxOcclusion")],n.prototype,"_useParallaxOcclusion",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useParallaxOcclusion",void 0),__decorate([e.serialize()],n.prototype,"parallaxScaleBias",void 0),__decorate([e.serialize("roughness")],n.prototype,"_roughness",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"roughness",void 0),__decorate([e.serialize()],n.prototype,"indexOfRefraction",void 0),__decorate([e.serialize()],n.prototype,"invertRefractionY",void 0),__decorate([e.serialize("useLightmapAsShadowmap")],n.prototype,"_useLightmapAsShadowmap",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useLightmapAsShadowmap",void 0),__decorate([e.serializeAsFresnelParameters("diffuseFresnelParameters")],n.prototype,"_diffuseFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"diffuseFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("opacityFresnelParameters")],n.prototype,"_opacityFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"opacityFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("reflectionFresnelParameters")],n.prototype,"_reflectionFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"reflectionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("refractionFresnelParameters")],n.prototype,"_refractionFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"refractionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("emissiveFresnelParameters")],n.prototype,"_emissiveFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"emissiveFresnelParameters",void 0),__decorate([e.serialize("useReflectionFresnelFromSpecular")],n.prototype,"_useReflectionFresnelFromSpecular",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"useReflectionFresnelFromSpecular",void 0),__decorate([e.serialize("useGlossinessFromSpecularMapAlpha")],n.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useGlossinessFromSpecularMapAlpha",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize("invertNormalMapX")],n.prototype,"_invertNormalMapX",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"invertNormalMapX",void 0),__decorate([e.serialize("invertNormalMapY")],n.prototype,"_invertNormalMapY",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"invertNormalMapY",void 0),__decorate([e.serialize("twoSidedLighting")],n.prototype,"_twoSidedLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"twoSidedLighting",void 0),__decorate([e.serialize()],n.prototype,"useLogarithmicDepth",null),n})(e.PushMaterial);e.StandardMaterial_OldVer=t;var n=(function(){function e(){}return e})();e.CustomShaderStructure=n;var r=(function(){function e(){}return e})();e.ShaderSpecialParts=r;var o=(function(e){function i(){var i=e.call(this)||this;return i.VertexStore="",i.FragmentStore="#include<__decl__defaultFragment>\n#[Fragment_Begin]\n#extension GL_OES_standard_derivatives : enable\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_helper;\nvarying vec3 localNormal;\nvarying vec3 localPosition;\nvec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\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)\nvarying vec2 vSpecularUV;\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\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n\n#[Fragment_Definitions]\n\nvoid main(void) {\n\nvNormalW = vNormalW_helper;\n#[Fragment_MainBegin]\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#[Fragment_Custom_Diffuse]\n\nfloat alpha=vDiffuseColor.a;\n#[Fragment_Custom_Alpha]\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\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\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\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#include<logDepthFragment>\n#include<fogFragment>\n\n// Apply image processing if relevant. As this applies in linear space, \n// We first move from gamma to linear.\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\tcolor.rgb = toLinearSpace(color.rgb);\n#else\n\t#ifdef IMAGEPROCESSING\n\t\tcolor.rgb = toLinearSpace(color.rgb);\n\t\tcolor = applyImageProcessing(color);\n\t#endif\n#endif\n\n#[Fragment_Before_FragColor]\ngl_FragColor=color;\n}",i.VertexStore="#include<__decl__defaultVertex>\n\n#[Vertex_Begin]\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 VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 localPosition;\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW_helper;\nvarying vec3 localNormal;\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\n#[Vertex_Definitions]\n\nvoid main(void) {\n \n #[Vertex_MainBegin]\n \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>\n\nlocalPosition = positionUpdated;\n#[Vertex_Before_PositionUpdated]\n\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\n\n#[Vertex_Before_NormalUpdated]\n\nlocalNormal = normalUpdated;\nvNormalW_helper=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\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 DIFFUSE\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#ifdef AMBIENT\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#ifdef OPACITY\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#ifdef EMISSIVE\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#ifdef LIGHTMAP\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)\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#ifdef BUMP\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}",i}return __extends(i,e),i})(n);e.ShaderForVer3_0=o;var a=(function(){function e(){}return e.Ver3_0="3.0.0",e})();e.StandardShaderVersions=a;var s=(function(i){function t(e,t){var n=i.call(this,e,t)||this;return n.CustomParts=new r,n.customShaderNameResolve=n.Builder,n.SelectVersion("3.0.0"),n}return __extends(t,i),t.prototype.AttachAfterBind=function(e,i){for(var t in this._newUniformInstances){var n=t.toString().split("-");"vec2"==n[0]?i.setVector2(n[1],this._newUniformInstances[t]):"vec3"==n[0]?i.setVector3(n[1],this._newUniformInstances[t]):"vec4"==n[0]?i.setVector4(n[1],this._newUniformInstances[t]):"mat4"==n[0]?i.setMatrix(n[1],this._newUniformInstances[t]):"float"==n[0]&&i.setFloat(n[1],this._newUniformInstances[t])}for(var t in this._newSamplerInstances){var n=t.toString().split("-");"sampler2D"==n[0]&&this._newSamplerInstances[t].isReady&&this._newSamplerInstances[t].isReady()&&i.setTexture(n[1],this._newSamplerInstances[t])}},t.prototype.ReviewUniform=function(e,i){if("uniform"==e)for(var t in this._newUniforms)-1==this._customUniform[t].indexOf("sampler")&&i.push(this._newUniforms[t])
  103312. ;if("sampler"==e)for(var t in this._newUniforms)-1!=this._customUniform[t].indexOf("sampler")&&i.push(this._newUniforms[t]);return i},t.prototype.Builder=function(i,n,r,o,a){var s=this;if(this._isCreatedShader)return this._createdShaderName;this._isCreatedShader=!1,t.ShaderIndexer++;var f="custom_"+t.ShaderIndexer;this.ReviewUniform("uniform",n),this.ReviewUniform("sampler",o);var l=this._afterBind;return this._afterBind=function(e,i){if(i){s.AttachAfterBind(e,i);try{l(e,i)}catch(i){}}},e.Effect.ShadersStore[f+"VertexShader"]=this.ShaderVersion.VertexStore.replace("#[Vertex_Begin]",this.CustomParts.Vertex_Begin?this.CustomParts.Vertex_Begin:"").replace("#[Vertex_Definitions]",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Vertex_Definitions?this.CustomParts.Vertex_Definitions:"")).replace("#[Vertex_MainBegin]",this.CustomParts.Vertex_MainBegin?this.CustomParts.Vertex_MainBegin:"").replace("#[Vertex_Before_PositionUpdated]",this.CustomParts.Vertex_Before_PositionUpdated?this.CustomParts.Vertex_Before_PositionUpdated:"").replace("#[Vertex_Before_NormalUpdated]",this.CustomParts.Vertex_Before_NormalUpdated?this.CustomParts.Vertex_Before_NormalUpdated:""),e.Effect.ShadersStore[f+"PixelShader"]=this.ShaderVersion.FragmentStore.replace("#[Fragment_Begin]",this.CustomParts.Fragment_Begin?this.CustomParts.Fragment_Begin:"").replace("#[Fragment_MainBegin]",this.CustomParts.Fragment_MainBegin?this.CustomParts.Fragment_MainBegin:"").replace("#[Fragment_Definitions]",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Fragment_Definitions?this.CustomParts.Fragment_Definitions:"")).replace("#[Fragment_Custom_Diffuse]",this.CustomParts.Fragment_Custom_Diffuse?this.CustomParts.Fragment_Custom_Diffuse:"").replace("#[Fragment_Custom_Alpha]",this.CustomParts.Fragment_Custom_Alpha?this.CustomParts.Fragment_Custom_Alpha:"").replace("#[Fragment_Before_FragColor]",this.CustomParts.Fragment_Before_FragColor?this.CustomParts.Fragment_Before_FragColor:""),this._isCreatedShader=!0,this._createdShaderName=f,f},t.prototype.SelectVersion=function(e){switch(e){case"3.0.0":this.ShaderVersion=new o}},t.prototype.AddUniform=function(e,i,t){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances=new Array,this._newUniformInstances=new Array),t&&(i.indexOf("sampler"),this._newUniformInstances[i+"-"+e]=t),this._customUniform.push("uniform "+i+" "+e+";"),this._newUniforms.push(e),this},t.prototype.Fragment_Begin=function(e){return this.CustomParts.Fragment_Begin=e,this},t.prototype.Fragment_Definitions=function(e){return this.CustomParts.Fragment_Definitions=e,this},t.prototype.Fragment_MainBegin=function(e){return this.CustomParts.Fragment_MainBegin=e,this},t.prototype.Fragment_Custom_Diffuse=function(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this},t.prototype.Fragment_Custom_Alpha=function(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this},t.prototype.Fragment_Before_FragColor=function(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this},t.prototype.Vertex_Begin=function(e){return this.CustomParts.Vertex_Begin=e,this},t.prototype.Vertex_Definitions=function(e){return this.CustomParts.Vertex_Definitions=e,this},t.prototype.Vertex_MainBegin=function(e){return this.CustomParts.Vertex_MainBegin=e,this},t.prototype.Vertex_Before_PositionUpdated=function(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this},t.prototype.Vertex_Before_NormalUpdated=function(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this},t.ShaderIndexer=1,t})(t);e.CustomMaterial=s})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.NDOTL=!0,i.CUSTOMUSERLIGHTING=!0,i.CELLBASIC=!0,i.DEPTHPREPASS=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r._computeHighLevel=!1,r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(o.CELLBASIC=!this.computeHighLevel,e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix"],d=["diffuseSampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("cell",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this._maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this._diffuseTexture===e},n.prototype.dispose=function(e){this._diffuseTexture&&this._diffuseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.getClassName=function(){return"CellMaterial"},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.CellMaterial",i},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsColor3("diffuse")],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("computeHighLevel")],n.prototype,"_computeHighLevel",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"computeHighLevel",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.CellMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.cellVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\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#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.cellPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n\nvec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow)\n{\ndiffuseBase=info.diffuse*shadow;\n#ifdef CELLBASIC\nfloat level=1.0;\nif (info.ndl<0.5)\nlevel=0.5;\ndiffuseBase.rgb*vec3(level,level,level);\n#else\nfloat ToonThresholds[4];\nToonThresholds[0]=0.95;\nToonThresholds[1]=0.5;\nToonThresholds[2]=0.2;\nToonThresholds[3]=0.03;\nfloat ToonBrightnessLevels[5];\nToonBrightnessLevels[0]=1.0;\nToonBrightnessLevels[1]=0.8;\nToonBrightnessLevels[2]=0.6;\nToonBrightnessLevels[3]=0.35;\nToonBrightnessLevels[4]=0.2;\nif (info.ndl>ToonThresholds[0])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[0];\n}\nelse if (info.ndl>ToonThresholds[1])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[1];\n}\nelse if (info.ndl>ToonThresholds[2])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[2];\n}\nelse if (info.ndl>ToonThresholds[3])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[3];\n}\nelse\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[4];\n}\n#endif\nreturn max(diffuseBase,vec3(0.2));\n}\nvoid main(void)\n{\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#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nlightingInfo info;\nvec3 diffuseBase=vec3(0.,0.,0.);\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}",(function(e,i){var t=i();e&&e.BABYLON||( true?module.exports=t:"function"==typeof define&&define.amd?define(["BJSMaterials"],i):"object"==typeof exports?exports.BJSMaterials=t:e.BABYLON=t)})(this,(function(){return BABYLON}));
  103313. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  103314. /***/ }),
  103315. /* 32 */
  103316. /***/ (function(module, exports, __webpack_require__) {
  103317. "use strict";
  103318. Object.defineProperty(exports, "__esModule", { value: true });
  103319. var defaultViewer_1 = __webpack_require__(3);
  103320. var mappers_1 = __webpack_require__(6);
  103321. function InitTags(selector) {
  103322. if (selector === void 0) { selector = 'babylon'; }
  103323. var elements = document.querySelectorAll(selector);
  103324. for (var i = 0; i < elements.length; ++i) {
  103325. var element = elements.item(i);
  103326. var configMapper = mappers_1.mapperManager.getMapper('dom');
  103327. var config = configMapper.map(element);
  103328. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  103329. }
  103330. }
  103331. exports.InitTags = InitTags;
  103332. /***/ }),
  103333. /* 33 */
  103334. /***/ (function(module, exports, __webpack_require__) {
  103335. /* WEBPACK VAR INJECTION */(function(process, global) {var require;/*!
  103336. * @overview es6-promise - a tiny implementation of Promises/A+.
  103337. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  103338. * @license Licensed under MIT license
  103339. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  103340. * @version 4.1.1
  103341. */
  103342. (function (global, factory) {
  103343. true ? module.exports = factory() :
  103344. typeof define === 'function' && define.amd ? define(factory) :
  103345. (global.ES6Promise = factory());
  103346. }(this, (function () { 'use strict';
  103347. function objectOrFunction(x) {
  103348. var type = typeof x;
  103349. return x !== null && (type === 'object' || type === 'function');
  103350. }
  103351. function isFunction(x) {
  103352. return typeof x === 'function';
  103353. }
  103354. var _isArray = undefined;
  103355. if (Array.isArray) {
  103356. _isArray = Array.isArray;
  103357. } else {
  103358. _isArray = function (x) {
  103359. return Object.prototype.toString.call(x) === '[object Array]';
  103360. };
  103361. }
  103362. var isArray = _isArray;
  103363. var len = 0;
  103364. var vertxNext = undefined;
  103365. var customSchedulerFn = undefined;
  103366. var asap = function asap(callback, arg) {
  103367. queue[len] = callback;
  103368. queue[len + 1] = arg;
  103369. len += 2;
  103370. if (len === 2) {
  103371. // If len is 2, that means that we need to schedule an async flush.
  103372. // If additional callbacks are queued before the queue is flushed, they
  103373. // will be processed by this flush that we are scheduling.
  103374. if (customSchedulerFn) {
  103375. customSchedulerFn(flush);
  103376. } else {
  103377. scheduleFlush();
  103378. }
  103379. }
  103380. };
  103381. function setScheduler(scheduleFn) {
  103382. customSchedulerFn = scheduleFn;
  103383. }
  103384. function setAsap(asapFn) {
  103385. asap = asapFn;
  103386. }
  103387. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  103388. var browserGlobal = browserWindow || {};
  103389. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  103390. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
  103391. // test for web worker but not in IE10
  103392. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  103393. // node
  103394. function useNextTick() {
  103395. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  103396. // see https://github.com/cujojs/when/issues/410 for details
  103397. return function () {
  103398. return process.nextTick(flush);
  103399. };
  103400. }
  103401. // vertx
  103402. function useVertxTimer() {
  103403. if (typeof vertxNext !== 'undefined') {
  103404. return function () {
  103405. vertxNext(flush);
  103406. };
  103407. }
  103408. return useSetTimeout();
  103409. }
  103410. function useMutationObserver() {
  103411. var iterations = 0;
  103412. var observer = new BrowserMutationObserver(flush);
  103413. var node = document.createTextNode('');
  103414. observer.observe(node, { characterData: true });
  103415. return function () {
  103416. node.data = iterations = ++iterations % 2;
  103417. };
  103418. }
  103419. // web worker
  103420. function useMessageChannel() {
  103421. var channel = new MessageChannel();
  103422. channel.port1.onmessage = flush;
  103423. return function () {
  103424. return channel.port2.postMessage(0);
  103425. };
  103426. }
  103427. function useSetTimeout() {
  103428. // Store setTimeout reference so es6-promise will be unaffected by
  103429. // other code modifying setTimeout (like sinon.useFakeTimers())
  103430. var globalSetTimeout = setTimeout;
  103431. return function () {
  103432. return globalSetTimeout(flush, 1);
  103433. };
  103434. }
  103435. var queue = new Array(1000);
  103436. function flush() {
  103437. for (var i = 0; i < len; i += 2) {
  103438. var callback = queue[i];
  103439. var arg = queue[i + 1];
  103440. callback(arg);
  103441. queue[i] = undefined;
  103442. queue[i + 1] = undefined;
  103443. }
  103444. len = 0;
  103445. }
  103446. function attemptVertx() {
  103447. try {
  103448. var r = require;
  103449. var vertx = __webpack_require__(35);
  103450. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  103451. return useVertxTimer();
  103452. } catch (e) {
  103453. return useSetTimeout();
  103454. }
  103455. }
  103456. var scheduleFlush = undefined;
  103457. // Decide what async method to use to triggering processing of queued callbacks:
  103458. if (isNode) {
  103459. scheduleFlush = useNextTick();
  103460. } else if (BrowserMutationObserver) {
  103461. scheduleFlush = useMutationObserver();
  103462. } else if (isWorker) {
  103463. scheduleFlush = useMessageChannel();
  103464. } else if (browserWindow === undefined && "function" === 'function') {
  103465. scheduleFlush = attemptVertx();
  103466. } else {
  103467. scheduleFlush = useSetTimeout();
  103468. }
  103469. function then(onFulfillment, onRejection) {
  103470. var _arguments = arguments;
  103471. var parent = this;
  103472. var child = new this.constructor(noop);
  103473. if (child[PROMISE_ID] === undefined) {
  103474. makePromise(child);
  103475. }
  103476. var _state = parent._state;
  103477. if (_state) {
  103478. (function () {
  103479. var callback = _arguments[_state - 1];
  103480. asap(function () {
  103481. return invokeCallback(_state, child, callback, parent._result);
  103482. });
  103483. })();
  103484. } else {
  103485. subscribe(parent, child, onFulfillment, onRejection);
  103486. }
  103487. return child;
  103488. }
  103489. /**
  103490. `Promise.resolve` returns a promise that will become resolved with the
  103491. passed `value`. It is shorthand for the following:
  103492. ```javascript
  103493. let promise = new Promise(function(resolve, reject){
  103494. resolve(1);
  103495. });
  103496. promise.then(function(value){
  103497. // value === 1
  103498. });
  103499. ```
  103500. Instead of writing the above, your code now simply becomes the following:
  103501. ```javascript
  103502. let promise = Promise.resolve(1);
  103503. promise.then(function(value){
  103504. // value === 1
  103505. });
  103506. ```
  103507. @method resolve
  103508. @static
  103509. @param {Any} value value that the returned promise will be resolved with
  103510. Useful for tooling.
  103511. @return {Promise} a promise that will become fulfilled with the given
  103512. `value`
  103513. */
  103514. function resolve$1(object) {
  103515. /*jshint validthis:true */
  103516. var Constructor = this;
  103517. if (object && typeof object === 'object' && object.constructor === Constructor) {
  103518. return object;
  103519. }
  103520. var promise = new Constructor(noop);
  103521. resolve(promise, object);
  103522. return promise;
  103523. }
  103524. var PROMISE_ID = Math.random().toString(36).substring(16);
  103525. function noop() {}
  103526. var PENDING = void 0;
  103527. var FULFILLED = 1;
  103528. var REJECTED = 2;
  103529. var GET_THEN_ERROR = new ErrorObject();
  103530. function selfFulfillment() {
  103531. return new TypeError("You cannot resolve a promise with itself");
  103532. }
  103533. function cannotReturnOwn() {
  103534. return new TypeError('A promises callback cannot return that same promise.');
  103535. }
  103536. function getThen(promise) {
  103537. try {
  103538. return promise.then;
  103539. } catch (error) {
  103540. GET_THEN_ERROR.error = error;
  103541. return GET_THEN_ERROR;
  103542. }
  103543. }
  103544. function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
  103545. try {
  103546. then$$1.call(value, fulfillmentHandler, rejectionHandler);
  103547. } catch (e) {
  103548. return e;
  103549. }
  103550. }
  103551. function handleForeignThenable(promise, thenable, then$$1) {
  103552. asap(function (promise) {
  103553. var sealed = false;
  103554. var error = tryThen(then$$1, thenable, function (value) {
  103555. if (sealed) {
  103556. return;
  103557. }
  103558. sealed = true;
  103559. if (thenable !== value) {
  103560. resolve(promise, value);
  103561. } else {
  103562. fulfill(promise, value);
  103563. }
  103564. }, function (reason) {
  103565. if (sealed) {
  103566. return;
  103567. }
  103568. sealed = true;
  103569. reject(promise, reason);
  103570. }, 'Settle: ' + (promise._label || ' unknown promise'));
  103571. if (!sealed && error) {
  103572. sealed = true;
  103573. reject(promise, error);
  103574. }
  103575. }, promise);
  103576. }
  103577. function handleOwnThenable(promise, thenable) {
  103578. if (thenable._state === FULFILLED) {
  103579. fulfill(promise, thenable._result);
  103580. } else if (thenable._state === REJECTED) {
  103581. reject(promise, thenable._result);
  103582. } else {
  103583. subscribe(thenable, undefined, function (value) {
  103584. return resolve(promise, value);
  103585. }, function (reason) {
  103586. return reject(promise, reason);
  103587. });
  103588. }
  103589. }
  103590. function handleMaybeThenable(promise, maybeThenable, then$$1) {
  103591. if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
  103592. handleOwnThenable(promise, maybeThenable);
  103593. } else {
  103594. if (then$$1 === GET_THEN_ERROR) {
  103595. reject(promise, GET_THEN_ERROR.error);
  103596. GET_THEN_ERROR.error = null;
  103597. } else if (then$$1 === undefined) {
  103598. fulfill(promise, maybeThenable);
  103599. } else if (isFunction(then$$1)) {
  103600. handleForeignThenable(promise, maybeThenable, then$$1);
  103601. } else {
  103602. fulfill(promise, maybeThenable);
  103603. }
  103604. }
  103605. }
  103606. function resolve(promise, value) {
  103607. if (promise === value) {
  103608. reject(promise, selfFulfillment());
  103609. } else if (objectOrFunction(value)) {
  103610. handleMaybeThenable(promise, value, getThen(value));
  103611. } else {
  103612. fulfill(promise, value);
  103613. }
  103614. }
  103615. function publishRejection(promise) {
  103616. if (promise._onerror) {
  103617. promise._onerror(promise._result);
  103618. }
  103619. publish(promise);
  103620. }
  103621. function fulfill(promise, value) {
  103622. if (promise._state !== PENDING) {
  103623. return;
  103624. }
  103625. promise._result = value;
  103626. promise._state = FULFILLED;
  103627. if (promise._subscribers.length !== 0) {
  103628. asap(publish, promise);
  103629. }
  103630. }
  103631. function reject(promise, reason) {
  103632. if (promise._state !== PENDING) {
  103633. return;
  103634. }
  103635. promise._state = REJECTED;
  103636. promise._result = reason;
  103637. asap(publishRejection, promise);
  103638. }
  103639. function subscribe(parent, child, onFulfillment, onRejection) {
  103640. var _subscribers = parent._subscribers;
  103641. var length = _subscribers.length;
  103642. parent._onerror = null;
  103643. _subscribers[length] = child;
  103644. _subscribers[length + FULFILLED] = onFulfillment;
  103645. _subscribers[length + REJECTED] = onRejection;
  103646. if (length === 0 && parent._state) {
  103647. asap(publish, parent);
  103648. }
  103649. }
  103650. function publish(promise) {
  103651. var subscribers = promise._subscribers;
  103652. var settled = promise._state;
  103653. if (subscribers.length === 0) {
  103654. return;
  103655. }
  103656. var child = undefined,
  103657. callback = undefined,
  103658. detail = promise._result;
  103659. for (var i = 0; i < subscribers.length; i += 3) {
  103660. child = subscribers[i];
  103661. callback = subscribers[i + settled];
  103662. if (child) {
  103663. invokeCallback(settled, child, callback, detail);
  103664. } else {
  103665. callback(detail);
  103666. }
  103667. }
  103668. promise._subscribers.length = 0;
  103669. }
  103670. function ErrorObject() {
  103671. this.error = null;
  103672. }
  103673. var TRY_CATCH_ERROR = new ErrorObject();
  103674. function tryCatch(callback, detail) {
  103675. try {
  103676. return callback(detail);
  103677. } catch (e) {
  103678. TRY_CATCH_ERROR.error = e;
  103679. return TRY_CATCH_ERROR;
  103680. }
  103681. }
  103682. function invokeCallback(settled, promise, callback, detail) {
  103683. var hasCallback = isFunction(callback),
  103684. value = undefined,
  103685. error = undefined,
  103686. succeeded = undefined,
  103687. failed = undefined;
  103688. if (hasCallback) {
  103689. value = tryCatch(callback, detail);
  103690. if (value === TRY_CATCH_ERROR) {
  103691. failed = true;
  103692. error = value.error;
  103693. value.error = null;
  103694. } else {
  103695. succeeded = true;
  103696. }
  103697. if (promise === value) {
  103698. reject(promise, cannotReturnOwn());
  103699. return;
  103700. }
  103701. } else {
  103702. value = detail;
  103703. succeeded = true;
  103704. }
  103705. if (promise._state !== PENDING) {
  103706. // noop
  103707. } else if (hasCallback && succeeded) {
  103708. resolve(promise, value);
  103709. } else if (failed) {
  103710. reject(promise, error);
  103711. } else if (settled === FULFILLED) {
  103712. fulfill(promise, value);
  103713. } else if (settled === REJECTED) {
  103714. reject(promise, value);
  103715. }
  103716. }
  103717. function initializePromise(promise, resolver) {
  103718. try {
  103719. resolver(function resolvePromise(value) {
  103720. resolve(promise, value);
  103721. }, function rejectPromise(reason) {
  103722. reject(promise, reason);
  103723. });
  103724. } catch (e) {
  103725. reject(promise, e);
  103726. }
  103727. }
  103728. var id = 0;
  103729. function nextId() {
  103730. return id++;
  103731. }
  103732. function makePromise(promise) {
  103733. promise[PROMISE_ID] = id++;
  103734. promise._state = undefined;
  103735. promise._result = undefined;
  103736. promise._subscribers = [];
  103737. }
  103738. function Enumerator$1(Constructor, input) {
  103739. this._instanceConstructor = Constructor;
  103740. this.promise = new Constructor(noop);
  103741. if (!this.promise[PROMISE_ID]) {
  103742. makePromise(this.promise);
  103743. }
  103744. if (isArray(input)) {
  103745. this.length = input.length;
  103746. this._remaining = input.length;
  103747. this._result = new Array(this.length);
  103748. if (this.length === 0) {
  103749. fulfill(this.promise, this._result);
  103750. } else {
  103751. this.length = this.length || 0;
  103752. this._enumerate(input);
  103753. if (this._remaining === 0) {
  103754. fulfill(this.promise, this._result);
  103755. }
  103756. }
  103757. } else {
  103758. reject(this.promise, validationError());
  103759. }
  103760. }
  103761. function validationError() {
  103762. return new Error('Array Methods must be provided an Array');
  103763. }
  103764. Enumerator$1.prototype._enumerate = function (input) {
  103765. for (var i = 0; this._state === PENDING && i < input.length; i++) {
  103766. this._eachEntry(input[i], i);
  103767. }
  103768. };
  103769. Enumerator$1.prototype._eachEntry = function (entry, i) {
  103770. var c = this._instanceConstructor;
  103771. var resolve$$1 = c.resolve;
  103772. if (resolve$$1 === resolve$1) {
  103773. var _then = getThen(entry);
  103774. if (_then === then && entry._state !== PENDING) {
  103775. this._settledAt(entry._state, i, entry._result);
  103776. } else if (typeof _then !== 'function') {
  103777. this._remaining--;
  103778. this._result[i] = entry;
  103779. } else if (c === Promise$2) {
  103780. var promise = new c(noop);
  103781. handleMaybeThenable(promise, entry, _then);
  103782. this._willSettleAt(promise, i);
  103783. } else {
  103784. this._willSettleAt(new c(function (resolve$$1) {
  103785. return resolve$$1(entry);
  103786. }), i);
  103787. }
  103788. } else {
  103789. this._willSettleAt(resolve$$1(entry), i);
  103790. }
  103791. };
  103792. Enumerator$1.prototype._settledAt = function (state, i, value) {
  103793. var promise = this.promise;
  103794. if (promise._state === PENDING) {
  103795. this._remaining--;
  103796. if (state === REJECTED) {
  103797. reject(promise, value);
  103798. } else {
  103799. this._result[i] = value;
  103800. }
  103801. }
  103802. if (this._remaining === 0) {
  103803. fulfill(promise, this._result);
  103804. }
  103805. };
  103806. Enumerator$1.prototype._willSettleAt = function (promise, i) {
  103807. var enumerator = this;
  103808. subscribe(promise, undefined, function (value) {
  103809. return enumerator._settledAt(FULFILLED, i, value);
  103810. }, function (reason) {
  103811. return enumerator._settledAt(REJECTED, i, reason);
  103812. });
  103813. };
  103814. /**
  103815. `Promise.all` accepts an array of promises, and returns a new promise which
  103816. is fulfilled with an array of fulfillment values for the passed promises, or
  103817. rejected with the reason of the first passed promise to be rejected. It casts all
  103818. elements of the passed iterable to promises as it runs this algorithm.
  103819. Example:
  103820. ```javascript
  103821. let promise1 = resolve(1);
  103822. let promise2 = resolve(2);
  103823. let promise3 = resolve(3);
  103824. let promises = [ promise1, promise2, promise3 ];
  103825. Promise.all(promises).then(function(array){
  103826. // The array here would be [ 1, 2, 3 ];
  103827. });
  103828. ```
  103829. If any of the `promises` given to `all` are rejected, the first promise
  103830. that is rejected will be given as an argument to the returned promises's
  103831. rejection handler. For example:
  103832. Example:
  103833. ```javascript
  103834. let promise1 = resolve(1);
  103835. let promise2 = reject(new Error("2"));
  103836. let promise3 = reject(new Error("3"));
  103837. let promises = [ promise1, promise2, promise3 ];
  103838. Promise.all(promises).then(function(array){
  103839. // Code here never runs because there are rejected promises!
  103840. }, function(error) {
  103841. // error.message === "2"
  103842. });
  103843. ```
  103844. @method all
  103845. @static
  103846. @param {Array} entries array of promises
  103847. @param {String} label optional string for labeling the promise.
  103848. Useful for tooling.
  103849. @return {Promise} promise that is fulfilled when all `promises` have been
  103850. fulfilled, or rejected if any of them become rejected.
  103851. @static
  103852. */
  103853. function all$1(entries) {
  103854. return new Enumerator$1(this, entries).promise;
  103855. }
  103856. /**
  103857. `Promise.race` returns a new promise which is settled in the same way as the
  103858. first passed promise to settle.
  103859. Example:
  103860. ```javascript
  103861. let promise1 = new Promise(function(resolve, reject){
  103862. setTimeout(function(){
  103863. resolve('promise 1');
  103864. }, 200);
  103865. });
  103866. let promise2 = new Promise(function(resolve, reject){
  103867. setTimeout(function(){
  103868. resolve('promise 2');
  103869. }, 100);
  103870. });
  103871. Promise.race([promise1, promise2]).then(function(result){
  103872. // result === 'promise 2' because it was resolved before promise1
  103873. // was resolved.
  103874. });
  103875. ```
  103876. `Promise.race` is deterministic in that only the state of the first
  103877. settled promise matters. For example, even if other promises given to the
  103878. `promises` array argument are resolved, but the first settled promise has
  103879. become rejected before the other promises became fulfilled, the returned
  103880. promise will become rejected:
  103881. ```javascript
  103882. let promise1 = new Promise(function(resolve, reject){
  103883. setTimeout(function(){
  103884. resolve('promise 1');
  103885. }, 200);
  103886. });
  103887. let promise2 = new Promise(function(resolve, reject){
  103888. setTimeout(function(){
  103889. reject(new Error('promise 2'));
  103890. }, 100);
  103891. });
  103892. Promise.race([promise1, promise2]).then(function(result){
  103893. // Code here never runs
  103894. }, function(reason){
  103895. // reason.message === 'promise 2' because promise 2 became rejected before
  103896. // promise 1 became fulfilled
  103897. });
  103898. ```
  103899. An example real-world use case is implementing timeouts:
  103900. ```javascript
  103901. Promise.race([ajax('foo.json'), timeout(5000)])
  103902. ```
  103903. @method race
  103904. @static
  103905. @param {Array} promises array of promises to observe
  103906. Useful for tooling.
  103907. @return {Promise} a promise which settles in the same way as the first passed
  103908. promise to settle.
  103909. */
  103910. function race$1(entries) {
  103911. /*jshint validthis:true */
  103912. var Constructor = this;
  103913. if (!isArray(entries)) {
  103914. return new Constructor(function (_, reject) {
  103915. return reject(new TypeError('You must pass an array to race.'));
  103916. });
  103917. } else {
  103918. return new Constructor(function (resolve, reject) {
  103919. var length = entries.length;
  103920. for (var i = 0; i < length; i++) {
  103921. Constructor.resolve(entries[i]).then(resolve, reject);
  103922. }
  103923. });
  103924. }
  103925. }
  103926. /**
  103927. `Promise.reject` returns a promise rejected with the passed `reason`.
  103928. It is shorthand for the following:
  103929. ```javascript
  103930. let promise = new Promise(function(resolve, reject){
  103931. reject(new Error('WHOOPS'));
  103932. });
  103933. promise.then(function(value){
  103934. // Code here doesn't run because the promise is rejected!
  103935. }, function(reason){
  103936. // reason.message === 'WHOOPS'
  103937. });
  103938. ```
  103939. Instead of writing the above, your code now simply becomes the following:
  103940. ```javascript
  103941. let promise = Promise.reject(new Error('WHOOPS'));
  103942. promise.then(function(value){
  103943. // Code here doesn't run because the promise is rejected!
  103944. }, function(reason){
  103945. // reason.message === 'WHOOPS'
  103946. });
  103947. ```
  103948. @method reject
  103949. @static
  103950. @param {Any} reason value that the returned promise will be rejected with.
  103951. Useful for tooling.
  103952. @return {Promise} a promise rejected with the given `reason`.
  103953. */
  103954. function reject$1(reason) {
  103955. /*jshint validthis:true */
  103956. var Constructor = this;
  103957. var promise = new Constructor(noop);
  103958. reject(promise, reason);
  103959. return promise;
  103960. }
  103961. function needsResolver() {
  103962. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  103963. }
  103964. function needsNew() {
  103965. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  103966. }
  103967. /**
  103968. Promise objects represent the eventual result of an asynchronous operation. The
  103969. primary way of interacting with a promise is through its `then` method, which
  103970. registers callbacks to receive either a promise's eventual value or the reason
  103971. why the promise cannot be fulfilled.
  103972. Terminology
  103973. -----------
  103974. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  103975. - `thenable` is an object or function that defines a `then` method.
  103976. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  103977. - `exception` is a value that is thrown using the throw statement.
  103978. - `reason` is a value that indicates why a promise was rejected.
  103979. - `settled` the final resting state of a promise, fulfilled or rejected.
  103980. A promise can be in one of three states: pending, fulfilled, or rejected.
  103981. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  103982. state. Promises that are rejected have a rejection reason and are in the
  103983. rejected state. A fulfillment value is never a thenable.
  103984. Promises can also be said to *resolve* a value. If this value is also a
  103985. promise, then the original promise's settled state will match the value's
  103986. settled state. So a promise that *resolves* a promise that rejects will
  103987. itself reject, and a promise that *resolves* a promise that fulfills will
  103988. itself fulfill.
  103989. Basic Usage:
  103990. ------------
  103991. ```js
  103992. let promise = new Promise(function(resolve, reject) {
  103993. // on success
  103994. resolve(value);
  103995. // on failure
  103996. reject(reason);
  103997. });
  103998. promise.then(function(value) {
  103999. // on fulfillment
  104000. }, function(reason) {
  104001. // on rejection
  104002. });
  104003. ```
  104004. Advanced Usage:
  104005. ---------------
  104006. Promises shine when abstracting away asynchronous interactions such as
  104007. `XMLHttpRequest`s.
  104008. ```js
  104009. function getJSON(url) {
  104010. return new Promise(function(resolve, reject){
  104011. let xhr = new XMLHttpRequest();
  104012. xhr.open('GET', url);
  104013. xhr.onreadystatechange = handler;
  104014. xhr.responseType = 'json';
  104015. xhr.setRequestHeader('Accept', 'application/json');
  104016. xhr.send();
  104017. function handler() {
  104018. if (this.readyState === this.DONE) {
  104019. if (this.status === 200) {
  104020. resolve(this.response);
  104021. } else {
  104022. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  104023. }
  104024. }
  104025. };
  104026. });
  104027. }
  104028. getJSON('/posts.json').then(function(json) {
  104029. // on fulfillment
  104030. }, function(reason) {
  104031. // on rejection
  104032. });
  104033. ```
  104034. Unlike callbacks, promises are great composable primitives.
  104035. ```js
  104036. Promise.all([
  104037. getJSON('/posts'),
  104038. getJSON('/comments')
  104039. ]).then(function(values){
  104040. values[0] // => postsJSON
  104041. values[1] // => commentsJSON
  104042. return values;
  104043. });
  104044. ```
  104045. @class Promise
  104046. @param {function} resolver
  104047. Useful for tooling.
  104048. @constructor
  104049. */
  104050. function Promise$2(resolver) {
  104051. this[PROMISE_ID] = nextId();
  104052. this._result = this._state = undefined;
  104053. this._subscribers = [];
  104054. if (noop !== resolver) {
  104055. typeof resolver !== 'function' && needsResolver();
  104056. this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
  104057. }
  104058. }
  104059. Promise$2.all = all$1;
  104060. Promise$2.race = race$1;
  104061. Promise$2.resolve = resolve$1;
  104062. Promise$2.reject = reject$1;
  104063. Promise$2._setScheduler = setScheduler;
  104064. Promise$2._setAsap = setAsap;
  104065. Promise$2._asap = asap;
  104066. Promise$2.prototype = {
  104067. constructor: Promise$2,
  104068. /**
  104069. The primary way of interacting with a promise is through its `then` method,
  104070. which registers callbacks to receive either a promise's eventual value or the
  104071. reason why the promise cannot be fulfilled.
  104072. ```js
  104073. findUser().then(function(user){
  104074. // user is available
  104075. }, function(reason){
  104076. // user is unavailable, and you are given the reason why
  104077. });
  104078. ```
  104079. Chaining
  104080. --------
  104081. The return value of `then` is itself a promise. This second, 'downstream'
  104082. promise is resolved with the return value of the first promise's fulfillment
  104083. or rejection handler, or rejected if the handler throws an exception.
  104084. ```js
  104085. findUser().then(function (user) {
  104086. return user.name;
  104087. }, function (reason) {
  104088. return 'default name';
  104089. }).then(function (userName) {
  104090. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  104091. // will be `'default name'`
  104092. });
  104093. findUser().then(function (user) {
  104094. throw new Error('Found user, but still unhappy');
  104095. }, function (reason) {
  104096. throw new Error('`findUser` rejected and we're unhappy');
  104097. }).then(function (value) {
  104098. // never reached
  104099. }, function (reason) {
  104100. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  104101. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  104102. });
  104103. ```
  104104. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  104105. ```js
  104106. findUser().then(function (user) {
  104107. throw new PedagogicalException('Upstream error');
  104108. }).then(function (value) {
  104109. // never reached
  104110. }).then(function (value) {
  104111. // never reached
  104112. }, function (reason) {
  104113. // The `PedgagocialException` is propagated all the way down to here
  104114. });
  104115. ```
  104116. Assimilation
  104117. ------------
  104118. Sometimes the value you want to propagate to a downstream promise can only be
  104119. retrieved asynchronously. This can be achieved by returning a promise in the
  104120. fulfillment or rejection handler. The downstream promise will then be pending
  104121. until the returned promise is settled. This is called *assimilation*.
  104122. ```js
  104123. findUser().then(function (user) {
  104124. return findCommentsByAuthor(user);
  104125. }).then(function (comments) {
  104126. // The user's comments are now available
  104127. });
  104128. ```
  104129. If the assimliated promise rejects, then the downstream promise will also reject.
  104130. ```js
  104131. findUser().then(function (user) {
  104132. return findCommentsByAuthor(user);
  104133. }).then(function (comments) {
  104134. // If `findCommentsByAuthor` fulfills, we'll have the value here
  104135. }, function (reason) {
  104136. // If `findCommentsByAuthor` rejects, we'll have the reason here
  104137. });
  104138. ```
  104139. Simple Example
  104140. --------------
  104141. Synchronous Example
  104142. ```javascript
  104143. let result;
  104144. try {
  104145. result = findResult();
  104146. // success
  104147. } catch(reason) {
  104148. // failure
  104149. }
  104150. ```
  104151. Errback Example
  104152. ```js
  104153. findResult(function(result, err){
  104154. if (err) {
  104155. // failure
  104156. } else {
  104157. // success
  104158. }
  104159. });
  104160. ```
  104161. Promise Example;
  104162. ```javascript
  104163. findResult().then(function(result){
  104164. // success
  104165. }, function(reason){
  104166. // failure
  104167. });
  104168. ```
  104169. Advanced Example
  104170. --------------
  104171. Synchronous Example
  104172. ```javascript
  104173. let author, books;
  104174. try {
  104175. author = findAuthor();
  104176. books = findBooksByAuthor(author);
  104177. // success
  104178. } catch(reason) {
  104179. // failure
  104180. }
  104181. ```
  104182. Errback Example
  104183. ```js
  104184. function foundBooks(books) {
  104185. }
  104186. function failure(reason) {
  104187. }
  104188. findAuthor(function(author, err){
  104189. if (err) {
  104190. failure(err);
  104191. // failure
  104192. } else {
  104193. try {
  104194. findBoooksByAuthor(author, function(books, err) {
  104195. if (err) {
  104196. failure(err);
  104197. } else {
  104198. try {
  104199. foundBooks(books);
  104200. } catch(reason) {
  104201. failure(reason);
  104202. }
  104203. }
  104204. });
  104205. } catch(error) {
  104206. failure(err);
  104207. }
  104208. // success
  104209. }
  104210. });
  104211. ```
  104212. Promise Example;
  104213. ```javascript
  104214. findAuthor().
  104215. then(findBooksByAuthor).
  104216. then(function(books){
  104217. // found books
  104218. }).catch(function(reason){
  104219. // something went wrong
  104220. });
  104221. ```
  104222. @method then
  104223. @param {Function} onFulfilled
  104224. @param {Function} onRejected
  104225. Useful for tooling.
  104226. @return {Promise}
  104227. */
  104228. then: then,
  104229. /**
  104230. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  104231. as the catch block of a try/catch statement.
  104232. ```js
  104233. function findAuthor(){
  104234. throw new Error('couldn't find that author');
  104235. }
  104236. // synchronous
  104237. try {
  104238. findAuthor();
  104239. } catch(reason) {
  104240. // something went wrong
  104241. }
  104242. // async with promises
  104243. findAuthor().catch(function(reason){
  104244. // something went wrong
  104245. });
  104246. ```
  104247. @method catch
  104248. @param {Function} onRejection
  104249. Useful for tooling.
  104250. @return {Promise}
  104251. */
  104252. 'catch': function _catch(onRejection) {
  104253. return this.then(null, onRejection);
  104254. }
  104255. };
  104256. /*global self*/
  104257. function polyfill$1() {
  104258. var local = undefined;
  104259. if (typeof global !== 'undefined') {
  104260. local = global;
  104261. } else if (typeof self !== 'undefined') {
  104262. local = self;
  104263. } else {
  104264. try {
  104265. local = Function('return this')();
  104266. } catch (e) {
  104267. throw new Error('polyfill failed because global object is unavailable in this environment');
  104268. }
  104269. }
  104270. var P = local.Promise;
  104271. if (P) {
  104272. var promiseToString = null;
  104273. try {
  104274. promiseToString = Object.prototype.toString.call(P.resolve());
  104275. } catch (e) {
  104276. // silently ignored
  104277. }
  104278. if (promiseToString === '[object Promise]' && !P.cast) {
  104279. return;
  104280. }
  104281. }
  104282. local.Promise = Promise$2;
  104283. }
  104284. // Strange compat..
  104285. Promise$2.polyfill = polyfill$1;
  104286. Promise$2.Promise = Promise$2;
  104287. return Promise$2;
  104288. })));
  104289. //# sourceMappingURL=es6-promise.map
  104290. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(34), __webpack_require__(1)))
  104291. /***/ }),
  104292. /* 34 */
  104293. /***/ (function(module, exports) {
  104294. // shim for using process in browser
  104295. var process = module.exports = {};
  104296. // cached from whatever global is present so that test runners that stub it
  104297. // don't break things. But we need to wrap it in a try catch in case it is
  104298. // wrapped in strict mode code which doesn't define any globals. It's inside a
  104299. // function because try/catches deoptimize in certain engines.
  104300. var cachedSetTimeout;
  104301. var cachedClearTimeout;
  104302. function defaultSetTimout() {
  104303. throw new Error('setTimeout has not been defined');
  104304. }
  104305. function defaultClearTimeout () {
  104306. throw new Error('clearTimeout has not been defined');
  104307. }
  104308. (function () {
  104309. try {
  104310. if (typeof setTimeout === 'function') {
  104311. cachedSetTimeout = setTimeout;
  104312. } else {
  104313. cachedSetTimeout = defaultSetTimout;
  104314. }
  104315. } catch (e) {
  104316. cachedSetTimeout = defaultSetTimout;
  104317. }
  104318. try {
  104319. if (typeof clearTimeout === 'function') {
  104320. cachedClearTimeout = clearTimeout;
  104321. } else {
  104322. cachedClearTimeout = defaultClearTimeout;
  104323. }
  104324. } catch (e) {
  104325. cachedClearTimeout = defaultClearTimeout;
  104326. }
  104327. } ())
  104328. function runTimeout(fun) {
  104329. if (cachedSetTimeout === setTimeout) {
  104330. //normal enviroments in sane situations
  104331. return setTimeout(fun, 0);
  104332. }
  104333. // if setTimeout wasn't available but was latter defined
  104334. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  104335. cachedSetTimeout = setTimeout;
  104336. return setTimeout(fun, 0);
  104337. }
  104338. try {
  104339. // when when somebody has screwed with setTimeout but no I.E. maddness
  104340. return cachedSetTimeout(fun, 0);
  104341. } catch(e){
  104342. try {
  104343. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  104344. return cachedSetTimeout.call(null, fun, 0);
  104345. } catch(e){
  104346. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  104347. return cachedSetTimeout.call(this, fun, 0);
  104348. }
  104349. }
  104350. }
  104351. function runClearTimeout(marker) {
  104352. if (cachedClearTimeout === clearTimeout) {
  104353. //normal enviroments in sane situations
  104354. return clearTimeout(marker);
  104355. }
  104356. // if clearTimeout wasn't available but was latter defined
  104357. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  104358. cachedClearTimeout = clearTimeout;
  104359. return clearTimeout(marker);
  104360. }
  104361. try {
  104362. // when when somebody has screwed with setTimeout but no I.E. maddness
  104363. return cachedClearTimeout(marker);
  104364. } catch (e){
  104365. try {
  104366. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  104367. return cachedClearTimeout.call(null, marker);
  104368. } catch (e){
  104369. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  104370. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  104371. return cachedClearTimeout.call(this, marker);
  104372. }
  104373. }
  104374. }
  104375. var queue = [];
  104376. var draining = false;
  104377. var currentQueue;
  104378. var queueIndex = -1;
  104379. function cleanUpNextTick() {
  104380. if (!draining || !currentQueue) {
  104381. return;
  104382. }
  104383. draining = false;
  104384. if (currentQueue.length) {
  104385. queue = currentQueue.concat(queue);
  104386. } else {
  104387. queueIndex = -1;
  104388. }
  104389. if (queue.length) {
  104390. drainQueue();
  104391. }
  104392. }
  104393. function drainQueue() {
  104394. if (draining) {
  104395. return;
  104396. }
  104397. var timeout = runTimeout(cleanUpNextTick);
  104398. draining = true;
  104399. var len = queue.length;
  104400. while(len) {
  104401. currentQueue = queue;
  104402. queue = [];
  104403. while (++queueIndex < len) {
  104404. if (currentQueue) {
  104405. currentQueue[queueIndex].run();
  104406. }
  104407. }
  104408. queueIndex = -1;
  104409. len = queue.length;
  104410. }
  104411. currentQueue = null;
  104412. draining = false;
  104413. runClearTimeout(timeout);
  104414. }
  104415. process.nextTick = function (fun) {
  104416. var args = new Array(arguments.length - 1);
  104417. if (arguments.length > 1) {
  104418. for (var i = 1; i < arguments.length; i++) {
  104419. args[i - 1] = arguments[i];
  104420. }
  104421. }
  104422. queue.push(new Item(fun, args));
  104423. if (queue.length === 1 && !draining) {
  104424. runTimeout(drainQueue);
  104425. }
  104426. };
  104427. // v8 likes predictible objects
  104428. function Item(fun, array) {
  104429. this.fun = fun;
  104430. this.array = array;
  104431. }
  104432. Item.prototype.run = function () {
  104433. this.fun.apply(null, this.array);
  104434. };
  104435. process.title = 'browser';
  104436. process.browser = true;
  104437. process.env = {};
  104438. process.argv = [];
  104439. process.version = ''; // empty string to avoid regexp issues
  104440. process.versions = {};
  104441. function noop() {}
  104442. process.on = noop;
  104443. process.addListener = noop;
  104444. process.once = noop;
  104445. process.off = noop;
  104446. process.removeListener = noop;
  104447. process.removeAllListeners = noop;
  104448. process.emit = noop;
  104449. process.prependListener = noop;
  104450. process.prependOnceListener = noop;
  104451. process.listeners = function (name) { return [] }
  104452. process.binding = function (name) {
  104453. throw new Error('process.binding is not supported');
  104454. };
  104455. process.cwd = function () { return '/' };
  104456. process.chdir = function (dir) {
  104457. throw new Error('process.chdir is not supported');
  104458. };
  104459. process.umask = function() { return 0; };
  104460. /***/ }),
  104461. /* 35 */
  104462. /***/ (function(module, exports) {
  104463. /* (ignored) */
  104464. /***/ })
  104465. /******/ ]);
  104466. });
  104467. //# sourceMappingURL=viewer.js.map